"Try and Except" to differentiate between strings and integers? [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I'm a beginner in the Python language. Is there a "try and except" function in python to check if the input is a LETTER or multiple LETTERS. If it isn't, ask for an input again? (I made one in which you have to enter an integer number)
def validation(i):
try:
result = int(i)
return(result)
except ValueError:
print("Please enter a number")
def start():
x = input("Enter Number: ")
z = validation(x)
if z != None:
#Rest of function code
print("Success")
else:
start()
start()
When the above code is executed, and an integer number is entered, you get this:
Enter Number: 1
Success
If and invalid value however, such as a letter or floating point number is entered, you get this:
Enter Number: Hello
Please enter a number
Enter Number: 4.6
Please enter a number
Enter Number:
As you can see it will keep looping until a valid NUMBER value is entered. So is it possible to use the "try and except" function to keep looping until a letter is entered? To make it clearer, I'll explain in vague structured English, not pseudo code, but just to help make it clearer:
print ("Hello this will calculate your lucky number")
# Note this isn't the whole program, its just the validation section.
input (lucky number)
# English on what I want the code to do:
x = input (luckynumber)
So what I want is that if the variable "x" IS NOT a letter, or multiple letters, it should repeat this input (x) until the user enters a valid letter or multiple letters. In other words, if a letter(s) isn't entered, the program will not continue until the input is a letter(s). I hope this makes it clearer.

You can just call the same function again, in the try/except clause - to do that, you'll have to adjust your logic a bit:
def validate_integer():
x = input('Please enter a number: ')
try:
int(x)
except ValueError:
print('Sorry, {} is not a valid number'.format(x))
return validate_integer()
return x
def start():
x = validate_integer()
if x:
print('Success!')

Don't use recursion in Python when simple iteration will do.
def validate(i):
try:
result = int(i)
return result
except ValueError:
pass
def start():
z = None
while z is None:
x = input("Please enter a number: ")
z = validate(x)
print("Success")
start()

Related

How to create a exception for a while loop to repeat a input [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 months ago.
I am trying to get this bit of code to work to validate the following input. I want to only accept inputs 1,2,or 3. Here is what I have so far:
number = int(input('Enter a number:'))
done = False
while not done:
try:
if number < 3:
done = True
except:
number = input("Please enter a valid number:")
The expected out put that I want if the input to loop until I get either 1,2, or 3.
Right now it won't do anything to when I input something greater than three. I want to use this number as an input to another function. Any help would be great of if you need more information please let me know!
Try this
number = int(input('Enter a number:'))
done = False
while not done:
if number <= 3:
done = True
else:
number = int(input("Please enter a valid number:"))
except block only run when there is an error in try block code.
Use if-else statement.
You can use this one too.
number = int(input('Enter a number:'))
done = False
while number>3:
number = int(input('Please enter a valid number:'))

Correcting a text if it is not a number [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I am building a basic calculator using python and I have a feature that will detect if the text entered is a number or not. For that I have defined a function ie
def check_num(num):
while not num.isnumeric():
print("Invalid number! Please enter a valid number.")
num = input()
When I take an input of the number it is taking just the first input.
num1 = input()
check_num(num1)
How do I make it take the correct input that is the last input?
Here is an image of the code running in command prompt:
You'll want to change your function definition, so that the function returns num:
def check_num(num):
while not num.isnumeric():
print("Invalid number! Please enter a valid number.")
num = input()
return num
and then call it like this:
num1 = check_num(input())
You could make a recursive function that asks for the number instead of simply checking it:
def ask_num():
num = input()
if num.is_numeric():
return num
print("Invalid number! Please enter a valid number.")
return ask_num()

Printing numbers as long as an empty input is not entered

If I'm asking for a user input of numbers which continues as long as an empty string is not entered, if an empty string is entered then the program ends.
My current code is:
n=0
while n != "":
n = int(input("Enter a number: "))
But obviously this isn't exactly what I want. I could remove the int input and leave it as a regular input, but this will allow all types of inputs and i just want numbers.
Do i ago about this a different way?
calling int() on an empty string will cause a ValueError so you can encapsulate everything in a try block:
>>> while True:
try:
n = int(input('NUMBER: '))
except ValueError:
print('Not an integer.')
break
NUMBER: 5
NUMBER: 12
NUMBER: 64
NUMBER:
not a number.
this also has the added benefit of catching anything ELSE that isn't an int.
I would suggest using a try/except here instead.
Also, with using a try/except, you can instead change your loop to using a while True. Then you can use break once an invalid input is found.
Also, your solution is not outputting anything either, so you might want to set up a print statement after you get the input.
Here is an example of how you can put all that together and test that an integer is entered only:
while True:
try:
n = int(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
If you want to go a step further, and handle numbers with decimals as well, you can try to cast to float instead:
while True:
try:
n = float(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break

Python does not accept my input as a real number

# Math Quizzes
import random
import math
import operator
def questions():
# Gets the name of the user
name= ("Alz")## input("What is your name")
for i in range(10):
#Generates the questions
number1 = random.randint(0,100)
number2 = random.randint(1,10)
#Creates a Dictionary containg the Opernads
Operands ={'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
#Creast a list containing a dictionary with the Operands
Ops= random.choice(list(Operands.keys()))
# Makes the Answer variable avialabe to the whole program
global answer
# Gets the answer
answer= Operands.get(Ops)(number1,number2)
# Makes the Sum variable avialbe to the whole program
global Sum
# Ask the user the question
Sum = ('What is {} {} {} {}?'.format(number1,Ops,number2,name))
print (Sum)
global UserAnswer
UserAnswer= input()
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
def score(Sum,answer):
score = 0
for i in range(10):
correct= answer
if UserAnswer == correct:
score +=1
print("You got it right")
else:
return("You got it wrong")
print ("You got",score,"out of 10")
questions()
score(Sum,answer)
When I enter a float number into the console the console prints out this:
What is 95 * 10 Alz?
950
Please enter a correct input
I'm just curious on how I would make the console not print out the message and the proper number.
this is a way to make sure you get something that can be interpreted as a float from the user:
while True:
try:
user_input = float(input('number? '))
break
except ValueError:
print('that was not a float; try again...')
print(user_input)
the idea is to try to cast the string entered by the user to a float and ask again as long as that fails. if it checks out, break from the (infinite) loop.
You could structure the conditional if statement such that it cause number types more than just float
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
Trace through your code to understand why it doesn't work:
UserAnswer= input()
This line offers no prompt to the user. Then it will read characters from standard input until it reaches the end of a line. The characters read are assigned to the variable UserAnswer (as type str).
if UserAnswer == input():
Again offer no prompt to the user before reading input. The new input is compared to the value in UserAnswer (which was just entered on the previous line). If this new input is equal to the previous input then execute the next block.
UserAnswer= float(input())
For a third time in a row, read input without presenting a prompt. Try to parse this third input as a floating point number. An exception will be raised if this new input can not be parsed. If it is parsed it is assigned to UserAnswer.
elif UserAnswer != float() :
This expression is evaluated only when the second input does not equal the first. If this is confusing, then that is because the code is equally confusing (and probably not what you want). The first input (which is a string) is compared to a newly created float object with the default value returned by the float() function.
Since a string is never equal to a float this not-equals test will always be true.
print("Please enter a correct input")
and thus this message is printed.
Change this entire section of code to something like this (but this is only a representative example, you may, in fact, want some different behavior):
while True:
try:
raw_UserAnswer = input("Please enter an answer:")
UserAnswer = float(raw_UserAnswer)
break
except ValueError:
print("Please enter a correct input")

How to add up a variable?

I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)

Categories