Problem with repetition structure while

2

I made this little code so that it asked for a user and a password. If the data were the same as those defined within the code, show a "success", if the user is different from what is placed in the code, ask the user again.

I tried to use the while repeat structure, but I'm not using it correctly.

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()
    
asked by anonymous 18.06.2017 / 03:15

2 answers

2

I do not know if I understand the question, but come on:

View 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

    
19.06.2017 / 00:09
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 that I imagine you have tried to do.

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 objective is to print on the screen the string 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.

    
19.06.2017 / 01:10