I have a problem with a program I am making to do with an arithmetic quiz.when I enter a name the quiz should print the welcome message however if I enter a blank or a number then the programme should loop the question but tell the user that they have made an error. I used the try statement and the NameError statement to try and resolve this problem but when I use the function "except" and run it in idle it says that I have an invalid syntax.
here is the code i am trying to fix:
import random
while True:
try:
UserName = input("What is your name:")
except NameError:
print ("The answer given does not compute!! Try again")
continue
else:
break
print(UserName," welcome to the Arithmetic Quiz.")
I have edited the code for the program, but still when I try to run it in Idle it highlights except and then says invalid syntax.
You don't need a try-except to check for an empty string
while True:
UserName = input("What is your name:")
if not UserName:
print("The answer given does not compute!! Try again")
continue
else:
break
print(UserName," welcome to the Arithmetic Quiz.")
This is what the proper indentation should be for the try: except: else: block
import random
while True:
try:
UserName = input("What is your name:")
except NameError:
print("The answer given does not compute!! Try again")
continue
else:
break
print(UserName," welcome to the Arithmetic Quiz.")
caveat (thanks cricket_007) this loop will never end. I had meant this comment to show how the try: indentation should have been for the OP.
Related
Im new to python and I'm trying to code a python login program. Instead of printing out "Welcome to the database" when the username provided is correct, it printed out both "Welcome to the database" and "Username invalid. Please try again.". May I know which part of my code needs to be corrected?
def login():
while True:
name = input("Name: ")
with open('username.txt', "r")as name_file:
for line in name_file.readlines():
if name == line.strip():
print("welcome to database")
else:
print("Username invalid. Please try again")
You are looping through all the users in the text file and for each of them printing to the console. The thing you probably want could be done like this:
def login():
while True:
loginSucessful = False
name = input("Name: ")
with open('username.txt', "r")as name_file:
for line in name_file.readlines():
if name == line.strip():
loginSucessful = True
break
if loginSucessful:
print("welcome to database")
else:
print("Username invalid. Please try again")
You could use a boolean variable to keep track of successful logins like #Michalor did. Or you can use Python's for/else loop to do the same thing without adding a new variable. If the login is successful and you break out of the loop, the "else" statement isn't executed. Using "break" also has the advantage that you don't need to test all of the other users after you have found a successful login.
def login():
while True:
name = input("Name: ")
with open('username.txt', "r")as name_file:
for line in name_file.readlines():
if name == line.strip():
print("welcome to database")
break
else:
print("Username invalid. Please try again")
Of course, this kind of function doesn't provide much security, as you can keep guessing the names in the text file until you find a valid one, or if you can get your hands on the text file itself you can just look the names up. For actual login code, it's probably best to use some kind of login library that handles the security details for you.
beginner programmer with python here. I'm wondering why my "attempt" counter only updates once despite the loop continuing.
def login():
attempt = 3
username = input("Enter your username:\n> ")
while True:
if username in userNamePassword:
password = input("Enter your password:\n> ")
if userNamePassword[username] == password:
print("Logged in")
return True
elif userNamePassword[username] != password:
attempt -=1
print("Sorry, the password is invalid. You have", attempt,"attempts remaining.")
login()
if attempt == 0:
print("Sorry, you have exhausted your password attempts. Please restart the process.")
exit()
It only ever prints 1 as the attempt remaining however continues the loop asking for the user and pass once more. It's possibly a small, overlooked issue but I'm scratching my head here. Thanks
Remove that login() call. When you call the function, the attemps will reset to 3. If you don't call it, you will stay in loop and the attemps will decrement. I recommend you, instead of exit() to use break
Please, I need help with this login system that I am currently working on, but I keep on getting the indented block error at def password(). I'm new to python but have worked with Java for a few years.
I have tried to indent the def password(), but it just keeps on popping up.
def username():
userinputname = input('Please enter the username')
if userinputname == user:
password()
elif userinputname != user:
print('Wrong username, please try again')
username()
else:
# problems()3
def password():
userinputpass = input('Please enter the password')
if userinputpass == passs:
main()
elif userinputpass != passs
for x <=5:
print('Wrong password, please try again')
x++
exit
else:
# problems()
def register():
registeragain = False
user = input('Please register your username')
passs = input('Please register your password')
register = input('Do you want to register another account? Y/N')
if register == 'Y':
registeragain = True
elif register == 'N':
username()
else:
print("Error")
# problems()
register()
I ran the problem and the error showed expected an indented block (, line 12)
else:
# problems()3
def password():
The expected indented block error happens because you're supposed to have an indented block of code following an else:. Instead, you go directly from there to an unindent (starting a new function definition).
If you put a pass statement under your else that will satisfy the requirement for there to be a block under it. Alternatively you could just remove the else since it's not doing anything.
You've declared an else statement at the end of each function without including anything to execute within the statement. Else statements expect an indented block of code, hence the problem.
If your intention is to do nothing in an 'else' block, use a 'pass' statement.
else:
pass
# problems()
Instead of below, which is causing problems.
else:
# problems()
I'm writing a script that takes in user input at multiple points. If the input is correct, all I need is to break out of the loop and continue. But if it's wrong, what I'm trying to do is delete and then re-prompt for that input. Here is a general case of what I'm working towards:
while True:
test = input("Enter test to check: ")
if test == expected:
break
else:
print("Error: test is incorrect")
#Clear/overwrite test
#Re-prompt for input
I've been doing some research but I haven't found anything that really makes sense to me. Is there a way to delete or overwrite the value entered by the user so that once test is entered again, it's an entirely new value?
If that's very important to you to clear the screen before asking user again for input you could wait some time after displaying error message and then ask user for input again wiping out error message.
import time
expected = 'foo'
while True:
print(' '*30 + '\r', end='')
test = input("Enter test to check: ")
if test == expected:
break
else:
print("Error: {} is incorrect\r".format(test), end='')
time.sleep(2)
If you would like to clear error message and previous input you could use for example os.system('clear').
solution:
else:
print("Error: test is incorrect")
test = input("Enter test to check")
You don't have to 'clear' test as you're reprompting and therefore changing the value of test each time
Why not do something like this
lol=True
while lol:
test = input("Enter test to check: ")
if test == expected:
lol=False
print("Corect!!!")
else:
print("Error: test is incorrect")
Hope it helps
So i am making a password system.
It ask for the user to enter the password, then check if it's right. I am getting a error with:
%Run HelloPython.py
File "/home/pi/Python Coding/HelloPython.py", line 17
print('Welcome home,', name,)
^
SyntaxError: expected an indented block
Something is wrong.
Code:
print('What is your name?')
# Stores everything typed up until ENTER
name = sys.stdin.readline()
print('Hello', name,'Enter password.')
password = sys.stdin.readline()
if password == ("1"):
print('Welcome home,', name,)
else:
print("Password:", password,"Is incorect. Please try again.")
SyntaxError: expected an indented block
Indent your if-else statements like below.
To check "is equal to", use == instead of = which is an assignment.
readline returns a string, so you should compare it with '1' string.
readline includes a newline \n at the end, so call strip() on it.
import sys
print('What is your name?')
# Stores everything typed up until ENTER
name = sys.stdin.readline()
print('Hello', name, 'Enter password.')
password = sys.stdin.readline().strip()
if password == '1':
print("Welcome home,", name)
else:
print("Password:", password, "Is incorrect. Please try again.")
So I've re-wrote your code. You're forgetting to indent your if-statements. http://www.secnetix.de/olli/Python/block_indentation.hawk
import sys # Import the 'sys' module
print('What is your name?')
name = sys.stdin.readline()
print('Hello ', name, '. Enter password.')
password = sys.stdin.readline()
# Use '=='
if password == 1:
print("Welcome home, ", name)
# Here you need indentation.
else:
print("Password: ", password," is incorect. Please try again.")
This is not your only error, but it is probably the most easily overlooked:
if password = 1:
What's going on here: 1 is getting stored to the variable password (Since = is the storing operator). Then if password is getting evaluated; variables are truthy in python, so that will evaluate to True, regardless of what you had stored in password above.
To remedy this, use == for comparing password, and also since password is a string, put the 1 in quotes so that it is compared as a string.
if password == "1":
You need to fix your indentation as well, python is dependent on whitespace.