Use of try/except for input validation? - python

I am trying to validate user input to check that, when they enter their name, it is more than 2 characters and is alphabetic. I am attempting to do this using try/except as I have been told that it is the best loop for user validation. Unfortunately if the user enters characters that are not alphabetic, nothing happens, and the program proceeds like normal. I also do not know how to check if the input is longer than 2 characters in the try/except loop as it is very new to me. Any help is much appreciated.
list = []
def users_name():
while True:
try:
name = str(input("Please enter your first name: "))
list.append(name)
break
except TypeError:
print("Letters only please.")
continue
except EOFError:
print("Please input something....")
continue
users_name()

You program will continue to run because of the continue clause in the catch block.
You can also check to see if the length of what they entered is longer than two characters.
list = []
def users_name():
while True: # Never ending loop
try:
name = str(input("Please enter your first name: "))
if (len(name) > 2)
list.append(name)
break
except TypeError:
print("Letters only please.")
continue # This causes it to continue
except EOFError:
print("Please input something....")
continue # This causes it to continue
users_name()
Also, you might want to stop the loop somehow. Maybe put in a break clause when you insert into the array?
if(len(name) > 2)
list.append(name)
break
...
To check if the input is a digit or an alphabet character use isdigit() or isalpha()
if a.isalpha():
#do something
elif a.isdigit():
#do something
Your code will then look like this:
list = []
def users_name():
while True: # Never ending loop
try:
name = str(input("Please enter your first name: "))
if (len(name) > 2 && name.isalpha()):
list.append(name)
break
else:
raise TypeError
except TypeError:
print("Letters only please.")
continue # This causes it to continue
except EOFError:
print("Please input something....")
continue # This causes it to continue
users_name()
Also if you are using Python < 3 consider using raw_input(). input() will actually evaluate the input as Python code.

To check the length of your String you can use the method len() to obtain its character length. You can then select those that are greater than 2 or your desired length.
To check if you string has only alphabetic characters you can use the str.isalpha() method to check so.
Therefore, if you check len(name) > 2 and name.isalpha() will help you filter those string that do not match what you want:
>>> name = "MyName"
>>> len(name) > 2 and name.isalpha()
True
>>> wrong_name = "My42Name"
>>> len(wrong_name) > 2 and wrong_name.isalpha()
False
>>> short_name = "A"
>>> len(short_name) > 2 and short_name.isalpha()
False

Related

How to use try/except blocks for multiple variables that require user input?

while True:
try:
age = int(input("Enter your age: "))
if age <= 0:
raise TypeError("Enter a number greater than zero")
except ValueError:
print("Invalid age. Must be a number.")
except TypeError as err:
print(err)
except:
print('Invalid input')
break
while True:
try:
height = float(input('Enter your height in inches: '))
if height <= 0:
raise TypeError("Enter a number greater than 0")
break
except ValueError:
raise ValueError("Height must be a number.")
I have multiple variables that need user input in order for the program to run. I need to get 3 variables from a user and they need to input the values correctly. I thought I should use try/except blocks for each of the variables but when I use the try/except block for the first variable and begin writing the second block the program skips over the exceptions even if the user input is incorrect.
I thought about using another while loop but I'm not sure how to write in python the idea of; if previous condition is met move onto next block of code. I tried using the same try/except block for two variables and failed. Any insight would be helpful. The problem is that when an incorrect value is entered the program still continues onto the next try block.
For the expected integer input, you don't need to use the try-except block. Use isdecimal() string method instead:
while True:
age = input("Enter your age: ").strip()
if age.startswith("-") or not age.isdecimal() or int(age) == 0:
print("Invalid age. Must be a number greater than zero.")
continue
else:
age = int(age)
break
For the expected float input, use almost the same code:
while True:
height = input("Enter your height in inches: ").strip()
if height.startswith("-") or not height.replace(".", "", 1).isdecimal() \
or float(height) == 0:
print("Invalid height. Must be a number greater than zero.")
continue
else:
height= float(height)
break
The only difference (beside using float() instead of int()) is temporary removing a possible dot symbol (.) – but at most one such symbol – before applying the isdecimal() testing method:
height.replace(".", "", 1).isdecimal()
^^^^^^^^^^^^^^^^^^^^
From the String Methods in the Python Library Reference:
str.isdecimal()
Return True if all characters in the string are decimal characters and there is at least one character, False
otherwise. Decimal characters are those that can be used to form
numbers in base 10, e.g. U+0660, ARABIC- INDIC DIGIT ZERO.
Formally a decimal character is a character in the Unicode General
Category “Nd”.
str.replace(old, new[, count])
Return a copy of the string with all
occurrences of substring old replaced by new. If the optional argument
count is given, only the first count occurrences are replaced.
See also What's the difference between str.isdigit(), isnumeric() and isdecimal() in Python?
You can put your user input request into a function that is called for each unique variable see the following as an example:
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp

Exception message not printing when I give a string character

`I'm trying to get this exception to trigger so I can see if python can handle when I input a string instead of an int.
I've tried changing the ValueError statement to a different type of exception such as TypeError instead of Value Error. I've also checked for syntax issues.
try:
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
except ValueError: #this is supposed to be thrown when I put
# a string character instead of an int. Why is this
#not being invoked
#when I put a str character in?!?!
print("da fuq!?!. That ain't no int!")
I'm trying to get the program to print my last line shown when I input a string character, such as a (k) or something, instead it's throwing an error message.
Here's the full code that someone asked for:
u_list = []
list_sum = 0
for i in range(10):
userInput = int(input("Gimme a number: "))
try:
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
except ValueError: #this is supposed to be thrown when I put
# a string character instead of an int. Why is this not being invoked
#when I put a str character in?!?!
print("da fuq!?!. That ain't no int!")
print("u_list: {}".format(u_list))
print("The sum of tha even numbers in u_list is: {}.".format(list_sum))
ValueError will be thrown when failing to convert a string to an int. input() (or raw_input() in Python 2) will always return a string, even if that string contains digits, and trying to treat it like an integer will not implicitly convert it for you. Try something like this:
try:
userInput = int(userInput)
except ValueError:
...
else:
# Runs if there's no ValueError
u_list.append(userInput)
...
Add the userInput in the try-except block and check it for ValueError. If its an integer then append it to the list.
Here's the Code:
u_list = []
list_sum = 0
for i in range(10):
try:
userInput = int(input("Gimme a number: "))
except ValueError:
print("da fuq!?!. That ain't no int!")
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
print("u_list: {}".format(u_list))
print("The sum of tha even numbers in u_list is: {}.".format(list_sum))
I hope it helps!

How to break while loop when two conditions are true - Calculator

I'm building my first calculator. Trying to implement While loop to get a number through user input. I want the While to break once user put a number.
num1 = raw_input("Add mumber one: " )
try:
input = int(num1)
except ValueError:
print "This is not a number"
attempt = 0
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
print "You are not putting number. So, goodbuy"
operation = raw_input("Add Operator: ")
Try this:
for _ in range(5):
num1 = unicode(raw_input("Add number one: "))
if num1.isnumeric():
break
Another method you can try is to have num1 and do the following in the while loop:
if type(num1) is int:
break
What this does is check the type of the variable num1. If it is an integer, int, then it breaks out of the while loop.
I want the While to break once user put a number.
You already are doing that in the condition for your while loop by having type(num) != int so your while loop should stop after the user enters an integer.
You have several errors here:
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
The break statement shoud be inside the loop, but the indentation is wrong. As you write, it is after the loop (hence useless). Also, when you read from standard input, you always get a string even if it is a number. So when you check type(num1) != int this is always false. You must convert num1 with int() each time you read from standard input, not only the first time:
while True:
num1 = raw_input("Add Number one again: " )
try:
input = int(num1)
break
except ValueError:
print "This is not a number"
if attempt == 5:
break
attempt += 1
Here I try to convert to an integer the string read from stdin. If it works, I break the loop immediately. If it does not work (the except clause) I check how many attempts have been done, and break the loop if the attempts are equal to 5.

How do I avoid error while using int()?

I have a question concerning int(). Part of my Python codes looks like this
string = input('Enter your number:')
n = int(string)
print n
So if the input string of int() is not a number, Python will report ValueError and stop running the remaining codes.
I wonder if there is a way to make the program re-ask for a valid string? So that the program won't just stop there.
Thanks!
You can use try except
while True:
try:
string = input('Enter your number:')
n = int(string)
print n
break
except ValueError:
pass
Put the whole thing in an infinite loop. You should catch and ignore ValueErrors but break out of the loop when you get a valid integer.
What you're looking for isTry / Except
How it works:
try:
# Code to "try".
except:
# If there's an error, trap the exception and continue.
continue
For your scenario:
def GetInput():
try:
string = input('Enter your number:')
n = int(string)
print n
except:
# Try to get input again.
GetInput()
n = None
while not isinstance(n, int):
try:
n = int(input('Enter your number:'))
except:
print('NAN')
While the others have mentioned that you can use the following method,
try :
except :
This is another way to do the same thing.
while True :
string = input('Enter your number:')
if string.isdigit() :
n = int(string)
print n
break
else :
print("You have not entered a valid number. Re-enter the number")
You can learn more about
Built-in String Functions from here.

Check for a string in if-statement

I have a program with some user inputs and I need to check if what the user entered was a string or an integer value between 1 and 10 million.
My code looks like this (simplified):
while True:
inp = raw_input("Enter a value between 1 and 10 million: ")
if inp < 1:
print "Must be higher than 1"
continue
elif inp > 10.000.000:
print "Must be less than 10.000.000"
continue
elif 'inp is a string': #here's my problem
print "Must be an integer value!"
continue
else:
'execute the rest of the code'
I don't know how to solve this. My program always terminates when I enter a string by mistake.
Thank you!
First, you're using Python 2, which will happily compare strings to integers. You don't want to do that. Secondly, raw_input() will always return a string. What you're hoping to do is check if that string could possibly represent a number. Third, 10.000.000 is improper syntax. Don't use separators. Fourth, you only need to continue if you want to go to the top of the loop early. If everything's in an if..elif..else block at the end of the loop, only one of those will be executed, so you don't need to put a continue at the end of each branch. You can use continue statements or restructure your branch. Finally, don't use in as a variable name, because that's a Python keyword.
while True:
inp = raw_input("Enter a value between 1 and 10 million: ")
if not inp.isdigit():
print "Must be an integer value!"
continue # each of these continue statements acts like a "failed, try again"
inp = int(inp)
if inp < 1:
print "Must be higher than 1"
continue # same for this one
if inp > 10000000:
print "Must be less than 10.000.000"
continue # and this one
# execute the rest of the code
You can use .isdigit() to check if string consists of numbers to make sure it can be convertible to integer:
while True:
in = raw_input("Enter a value between 1 and 10 million: ")
if in.isdigit():
number = int(in)
if number < 1:
print "Must be higher than 1"
continue
elif number > 10**6:
print "Must be less than 10.000.000"
continue
else:
'execute the rest of the code'
else:
print "Must be an integer value!"
continue
I have no idea how you came up with your code but here are different suggestions:
Don't use "in" as variable name because it's a python operator.
After the input you can check whether it is an int or a string.
Your program can look like this:
while True:
try:
input_int = int(raw_input("Enter a value between 1 and 10 million: "))
if input_int < 1 :
print "Must be higher than 1"
elif input_int > 10**7:
print "Must be less than 10.000.000"
except:
print "Must be an integer value!"
else: #You can use else with try/except block
#'execute the rest of the code'
Voilà

Categories