Python data type validation integer - python

Hello I am creating a registration program and need to ask the user to input their age . However I want to make sure its not a letter by just consisting of numbers. How do I limit the user to only getting a number and if they input other character a error message shows up
while True:
age = int(input("Age: "))
if not (age) != int:
print ("Not a valid age")
continue
else:
break

You can use try and except statements here.
try:
age=int(age) #Do not typecast the age variable before this line
except ValueError:
print("Enter number")
If you do not want the program to proceed until the user enters a number, you can use a flag variable and put the code block mentioned above in a while loop.

Related

how to deny someone to enter something using python input function

Ok the title is a bit weird. But, basically what i want to ask is:
read = input("Enter some numbers: ")
# The user should only enter numbers and nothing else
But the thing is the user can enter something else other than a numerical value.
How do i stop someone from entering an alphabet in realtime from the terminal?
Lets say the user inputs 123 then enters an "e". How do i make this e not even appear on the
terminal even if the user presses the e key?
you can repeat asking int values if user enters a string.
while True:
try:
# 👇️ use int() instead of float
# if you only accept integers
num = float(input('Your favorite number: '))
print(num)
break
except ValueError:
print('Please enter a number.')

Try and Except Block for User Input - Accounting for multiple scenarios

I am currently creating a Python program that requires a user to input an amount.
My code is below:
while True:
try:
integer_user = int(input('Please enter your amount:'))
if integer_user > 1000 and integer_user < self.owner.getValue():
break
except ValueError:
print(f'Please enter a positive integer as your amount!')
The issue is, that I want to present two different error messages for the user.
If the user puts in a value that is greater than the owner value, I want to tell them, you cannot enter an amount greater than the owner value.
If the user (for example) writes a string, I want to tell them, Please enter a positive integer as your amount.
I am struggling to account for both scenarios. I can only account for the latter and not the former. Can anyone provide insight?
If the condition isn't true, you'll continue executing after the break. So put the error message there.
while True:
try:
integer_user = int(input('Please enter your amount:'))
if 1000 < integer_user < self.owner.getValue():
break
print(f"Your amount must be between 1000 and {self.owner.getValue()}")
except ValueError:
print(f'Please enter an integer as your amount!')

Responding to errors in python

I am new to python and have faced this issue. What this program does is ask the user his or her age. The age has to be a number or else it will return a value error. I have used the try/except method to respond to the error, but i also want it so that the age the user enters is below a specific value(eg 200).
while True:
try:
age=int(input('Please enter your age in years'))
break
except ValueError:
print ('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
except:
if age>=200:
print ('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
print (f'Your age is {age}')
I tried this and a bunch of other stuff. Can anyone help?
You first need to check if value entered is an integer, do this in try clause.
You then need to check if the value is within the range, do this in the else clause which only gets executed if the try block is successful.
Break out if the value is within the range.
Below code shows this.
while True:
try:
age=int(input('Please enter your age in years'))
except ValueError:
print ('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
else:
if age>=200:
print ('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
else:
break
print (f'Your age is {age}')
A possible solution:
while True:
age_input = input("Please enter your age in years: ")
# Check both if the string is an integer, and if the age is below 200.
if age_input.isdigit() and int(age_input) < 200:
print("Your age is {}".format(age_input))
break
# If reach here, it means that the above if statement evaluated to False.
print ("That's not a valid Number.\nPlease try Again.")
You don't need to do exception handling in this case.
isdigit() is a method of a String object that tells you if the given String contains only digits.
You can do an if statement right after the input(), still keeping the except ValueError, example:
while True:
try:
age=int(input('Please enter your age in years'))
if age < 200:
# age is valid, so we can break the loop
break
else:
# age is not valid, print error, and continue the loop
print('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')
except ValueError:
print('\n\n\n\nThat\'s not a valid Number.\nPlease try Again.\n\n\n\n')

How to loop a try and except ValueError code until the user enters the coorect value? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I have this code:
try:
phone = int(input("Enter your telephone no. : "))
except ValueError:
print("You must enter only integers!")
phone = int(input("Enter your telephone no. : "))
I want the user to enter their telephone number. But if they type anything else apart from integers an error message comes up saying that you can only type integers. What I want to do is to loop this section of the code so that every time the user enters a non-integer value the error message comes up. So far all this code does is, it prints the error message only for the first time. After the first time if the user enters a non-integer value the program breaks.
Please provide a not too complicated solution...I'm just a beginner.
I'm thinking you're meant to use a while loop but I don't know how?
I believe the best way is to wrap it in a function:
def getNumber():
while True:
try:
phone = int(input("Enter your telephone no. : "))
return phone
except ValueError:
pass
You can do it with a while loop like this
while True:
try:
phone = int(input("Enter your telephone no. : "))
except ValueError:
print("You must enter only integers!")
else: # this is executed if there are no exceptions in the try-except block
break # break out of the while loop

why this while true is not looping back

def erVal():
print("The value entered is not vaild, enter a valid value")
name = input("Enter your name ")
while True:
erVal()
if name.isalpha() is True:
break
does not loop back WHY??
i am trying to display the error message when the user leave the name input blank
the while loop works but it keeps running printing the errVal
To answer your question. Assuming the formatting is correct this code will enter an endless loop if a non alpha value is entered. It will not return to ask for the name again. Entering an alpha value for name will cause the break to be executed which will end the while loop.
I assume you meant something more like the following:
def erVal():
print("The value entered is not valid, enter a valid value.")
while True:
name = input("Enter your name ")
if name.isalpha() is True:
break # will exit the while if name is alpha
else:
erVal()
Python is very interactive, in the future I suggest you test smaller pieces of the code such as playing with the while loop to see what break does. This will improve your understanding of the code.

Categories

Resources