Problem with while repetition structure

Asked

Viewed 399 times

2

I made this little code so he’d ask for a username and a password. If the data were the same as those defined within the code, show a "success", if the user is different from the one placed in the code, ask again the user.

I tried using the while repeating structure, but I’m not using it properly.

import getpass

user = str(input('Usuário: '))
def login():
    while(user!='admin'):
    user = str(input('Usuário: '))

if (user=='admin'):
    passwd = getpass.getpass('Senha: ') 
else:
    login()

2 answers

2


I don’t know if I understand the question, but come on:

See the code running on rel.it.

import getpass

def login():
    usr = 'Admin'
    while True:
        user = str(input('Usuário: '))
        if user != usr:
            print('Usuário inválido')
        else:
            print ('Senha: ')
            getpass.getpass('Senha: ')
            print ('ok')
            break

login()        

Usuário:  afasdfasf
Usuário inválido
Usuário:  Admin
Senha: 
 master
ok

DEMO

  • Your code repeats Password: twice after it is typed the user and enter keyboard, but it was very interesting. I will give a studied!

  • I did so because on some consoles getpass is "invisible", including where I posted the code.

1

import getpass

user = str(input('Usuário: ')) # user é variavel global
def login(): # user não existe dentro de login()
    while(user!='admin'): 
    user = str(input('Usuário: ')) # essa linha deveria estar identada pra ficar dentro do loop while

if (user=='admin'):
    passwd = getpass.getpass('Senha: ') 
else:
    login()

I made some punctual comments in your original code, below is the code I imagine you tried to make.

import getpass

user = str(input('Usuário: '))
def login(user): # user passado por parametro pra poder ser acessado dentro da função
    while(user!='admin'):
        user = str(input('Usuário: ')) # informação dentro do loop while identada corretamente
if (user=='admin'):
    passwd = getpass.getpass('Senha: ') 
else:
    login(user) # variavel user sendo passada por parametro pra função login.
    passwd = getpass.getpass('Senha: ') # recebe passwd após sair da função

I imagine the end result would be this. Note that if the goal is to print the string on the screen Senha: before the user enters the password, you will have to do something like @Sidon did, because the getpass.getpass function does not print the string passed by parameter.

  • I analyzed the comments you made in my code and noticed some mistakes I made. Your code was very useful!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.