Syntax error with try/except statement highlighting 'except' - python

I have a very simple try/except block to basically force the variable 'password' to be defined as an integer from user input.
It is likely a dumb question, but I have tried looking around and cannot find some solution.
try:
password = int(input('Password: '))
except ValueError:
print("Please do not type letters or symbols!!")
while type(password) != 'int':
try:
password = int(input('Password '))
except ValueError:
print("Please do not type letters or symbols!!")
print('Complete, we have your password.')
But, when I try run this python shell, it comes up with a Syntax Error, highlighting 'except'...

There were couple of problems:
You have to use the comparision like this type(password) is not int:
Define password variable beforehand, otherwise it would not be recognized in your while statement
password=""
try:
password = int(input('Bob should have issued you with your 4-digit numerical password, please enter it here: '))
except ValueError:
print("Please do not type letters or symbols!!")
while type(password) is not int:
try:
password = int(input('Bob should have issued you with your 4-digit numerical password, please enter it here: '))
except ValueError:
print("Please do not type letters or symbols!!")
print('Complete, we have your password.')

Remove the new line after password = .... Shell expects an except block not a new line. Also your parenthesis are not complete.
try:
password = int(input('Bob should have issued you with your 4-digit numerical password, please enter it here: '))
except ValueError:
print("Please do not type letters or symbols!!")

Related

Is there a way to check if the try statement was successful or not? [duplicate]

This question already has answers here:
What is the intended use of the optional "else" clause of the "try" statement in Python?
(22 answers)
Closed 1 year ago.
Just started learning python and wanted to make a calculator. I currently have some code that tries to turn what the user inputs into an integer, but what I want to do is be able to check if the attempt was successful or not.
Here is the part i'm having trouble with.
import sys
first_number = input('Enter a number: ')
try:
int(first_number)
except:
print("Sorry, that's not a number.")
exit()
You can just do:
try:
int(first_number)
print("try successful!")
except ValueError:
print("Sorry, that's not a number.")
print("try unsuccessful!")
exit()
You can set a flag after int that is only set on success:
success=False
nums=iter(['abc','123'])
while not success:
try:
x=int(next(nums))
success=True
except ValueError as e:
print(e, 'Try Again!')
print(x)
Prints:
invalid literal for int() with base 10: 'abc' Try Again!
123
First time with 'abc' is an error, second time a success.
Since nums first try is an error, that will not set success to True. Second time is not an error, success is set to True and the while loop terminates. You can use the same method with user input. The iterator is just simulating that...
So for your example:
success=False
while not success:
try:
n_string = input('Enter a number: ')
int(n_string)
success=True
except ValueError as e:
print(f'"{n_string}" is not a number. Try again')
Which is commonly simplified into this common idiom in Python for user input:
while True:
try:
n_string = input('Enter a number: ')
int(n_string)
break
except ValueError as e:
print(f'"{n_string}" is not a number. Try again')
To have this make more sense, make it a function:
def getNumber():
while True:
number = input('Enter a number: ')
if number.isnumeric():
return int(number)
print( "Not a number, please try again." )

How to check is an input that is meant to be an integer is empty(in python)?

def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = int(input(output_message))
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
As you can see here the code is supposed to check if an input is an integer and it is above a certain value which by default is 0, but could be changed.
When the user inputs random letters and symbols it see that there is a value error and returns "Integers only!(Please do not leave this blank)".
I want to be able to check if the user inputs nothing, and in that case only it should output "This is blank/empty", the current way of dealing with this is to not check at all and just say "Integers only!(Please do not leave this blank)", in case there us a value error. I want to be able to be more specific and not just spit all the reasons at once. Can anyone please help me?
Thanks in advance.
You could do something like this :
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!", above=0, error_3="Please do not leave this blank"):
while True:
user_input = input(output_message)
try:
user_input = int(user_input)
if user_input >= above:
return user_input
break
else:
print(error_1.format(above))
except ValueError:
if(not user_input):
print(error_3)
else:
print(error_2)
I moved the input outside the try/except block to be able to use it in the except ! This worked fine for me, I hope this is what you needed.
You could just break the input and the conversion to int into two steps, like this:
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = input(output_message)
if not user_input:
print("Please do not leave this blank")
continue
user_input = int(user_input)
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)

Why does input only work if I enter a number?

I have successfully made a python password system but the password can only be out of numbers, not letters. Here is the coding behind it:
password = str(input("Please enter password to continue: "))
if password == 'dog':
print ("Welcome")
else:
print ("WRONG PASSWORD")
This doesn't work while having the password be an integer does work.
Edit: Sorry about putting the wrong code, new to this site.
I have now added quotes to 'dog' but it now gives this error in terminal
Please enter password to continue: dog
Traceback (most recent call last):
File "pass.py", line 1, in <module>
password = str(input("Please enter password to continue: "))
File "<string>", line 1, in <module>
NameError: name 'dog' is not defined
Final edit: Fixed it by changing str(input to str(raw_input. It was because I was using terminal which uses python 2. Does anyone know how to make terminal do python 3 instead of 2?
You are trying to pass a string type to an integer, which will not work. You can compare a string to an int!
Strings in python need speech marks ("STRING") around them. If there are no speech marks, python will assume it is an integer or float.
Your correct code should be:
password = str(input("Please enter password to continue: "))
if password == "dog":
print ("Welcome")
else:
print ("WRONG PASSWORD")
EDIT:
It also appears that you are using Python 2 (because you are using terminal). The input function in Python 2 tries to get input as a python expression, not as a string. Try using raw_input instead, if you are using Python 2. This will get the input as a string.
The string speech marks still applies. Your code would look like:
password = str(raw_input("Please enter password to continue: "))
if password == "dog":
print ("Welcome")
else:
print ("WRONG PASSWORD")
"Types" are the key here.
You're casting the input you get from the user (which is a String) to int - Integer:
3 == '3'
That's False! a String can never be equal to an Integer.
I would advise not casting it to int, keep it a str and it should work just fine.
To make it non-recurring:
password="dog"
password1=input("Enter password?")
if password==password1:
print("Welcome")
else:
print("Incorrect password")
However to make it rcurring you just do this:
condition = True
password="dog"
while condition:
password1=input("Enter password?")
if password==password1:
print("Welcome")
else:
print("Incorrect password")
If you're using python 2, try using:
inp = str(raw_input('Please enter password to continue: '))
print("Welcome") if password == "password_here" else print ("WRONG PASSWORD")

'NoneType' Error when using a Try and Except Block

I'm having a strange issue with a try and except block I'm using to catch invalid data entry into a simple Black Jack Game I'm writing.....
def PickNumberOfPlayers():
global log
try:
inputs = int(input("How Many Players Would You Like?: "))
PlayersNumber = inputs
log.write("How Many Players Would You Like?: \n")
return PlayersNumber
except ValueError:
print("Try Typing in A Valid Number")
log.write("Try Typing in A Valid Number\n")
PickNumberOfPlayers()
I then have a method GameStart() which starts a number of method calls:
def GameStart():
global ListOfPlayers
for i in range(0, int(PickNumberOfPlayers())):
name = input("What Would You Like This Players Name To Appear As?:")
ListOfPlayers.update({name: Player(0, name)})
for key, value in ListOfPlayers.items():
value.AccountSetup()
value.Bet()
for key, value in ListOfPlayers.items():
value.PlayerDeal()
Dealer.Deal()
When I run the code and enter proper values ( a valid integer) there is no issue. When I first enter a invalid number (a string or char) I get the appropriate message "Try Typing in A Valid Number, and then when I do enter a valid integer I get the error -
for i in range(0, int(PickNumberOfPlayers())):
TypeError: int() argument must be a string or a number, not 'NoneType'
Any idea?
When you call PickNumberOfPlayers() in your except, you do not return its value. Do return PickNumberOfPlayers() instead.
You should modify PickNumberOfPlayers to always return an int.
def PickNumberOfPlayers():
global log
while 1:
try:
return int(input("How Many Players Would You Like?: "))
except ValueError:
print("Try Typing in A Valid Number")
log.write("Try Typing in A Valid Number\n")

KeyErrors and how to raise a KeyError

For my homework assignment, I am told to raise a key error if the key(text) the user enters contains any non alphabetic characters and reprompt. So far I have this which seems to work but obviously doesn't use the expected try/except structure
key=input("Please enter the key word you want to use: ")
ok=key.isalpha()
while (ok==False):
print("The key you entered is invalid. Please try again")
key=input("Please enter the key word you want to use")
This is not appropriate usage of KeyError (it's supposed to be used for dict lookups, or similar situations), but if it is what you have been asked to do then try something like this :
def prompt_thing():
s = raw_input("Please enter the key word you want to use: ")
if s == '' or not s.isalnum():
print("The key you entered is invalid. Please try again")
raise KeyError('non-alphanumeric character in input')
return s
s = None
while s is None:
try:
s = prompt_thing()
except KeyError:
pass

Categories