This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I am using Python 3.6 currently and my code currently is asking a user to input 2 integers and convert them into binary form, this is not a problem, the issue that I have is when it asks the user to input a number, if they put anything other than an integer, it will break the code and come up with an error, is there a specific few lines of code that will ensure that errors will not display if letters or floats are inputted?
def add():
Num1 = int(input("Input the first number between 0 and 255, the calculated answer must not be above 255: "))
Num2 = int(input("Input the second number between 0 and 255, the calculated answer must not be above 255: "))
I have tried one method which was:
if type(Num1) != int:
print("Please input a number")
add()
However I still get errors when testing the code.
I would like the code to detect that a string or float has been inputted, then reload the "def" function without giving a syntax error.
This is the print result:
This is the gist of how to get an integer from the command line. It works using a while loop and try/except statements. You can add the checks for the integer range. You can use this code to create a function, which can be called twice for your particular problem.
n = None
while True:
n = input('enter an integer')
try:
n = int(n)
break
except:
continue
Related
This question already has answers here:
Python check for integer input
(3 answers)
Closed 1 year ago.
I need python to check if a variable is an integer or not, then act accordingly.
Here is the pertinent code:
def data_grab():
global fl_count #forklift count
print("How many Heavy-lift forklifts can you replace?\n\n"
"Please note: Only forklifts that have greater than 8,000 lbs. of lift capacity will qualify for this incentive.\n"
"**Forklifts do NOT need to be located at a port or airport to be eligible.**")
forklift_count = input("Enter in # of forklifts:")
if type(forklift_count) is int:
fl_count = forklift_count
else:
print("Invalid number. Please try again.")
data_grab()
Currently, when the user actually types in an integer, it will automatically jump to ELSE instead of executing the code under IF.
Any thoughts?
Try the str.isdigit() method:
forklift_count = input("Enter in # of forklifts:")
if forklift_count.isdigit():
# Use int(forklift_count) to convert type to integer as pointed out by #MattDMo
fl_count = forklift_count
else:
print("Invalid number. Please try again.")
From the documentation:
str.isdigit()
Return True if all characters in the string are digits and there is at least one character, False otherwise.
A beginner/possibly incomplete answer here, but you could wrap the input() with int().
forklift_count = int(input("Enter in # of forklifts:"))
input() returns a string so even if you enter an int it will treat as string unless you convert it.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Python: How to keep repeating a program until a specific input is obtained? [duplicate]
(4 answers)
Closed 3 years ago.
I want to get a user input which is bigger than zero. If user enters anything else than a positive integer prompt him the message again until he does.
x = input("Enter a number:")
y= int(x)
while y<0:
input("Enter a number:")
if not y<0:
break
If I add a bad value first then a good one it just keeps asking for a new one. Like Try -2 it asks again but then I give 2 and its still asking. Why?
The first time you assign the result of input to x, and convert x to a number (int(x)) but after the second call to input you don't. That is your bug.
That you have a chance to get this bug is because your code has to repeat the same thing twice (call input and convert the result to a number). This is caused by the fact that Python unfortunately does not have the do/while construct, as you mentioned (because there was no good way to use define it using indentation and Python's simple parser, and now it's too late).
The usual way is to use while True with break:
while True:
x = input("Enter a number:")
y = int(x)
if not y<0:
break
You assign a value to y before the while loop, then you enter the loop without assigning a value to y from the input.
Just change your code:
x = input("Enter a number:")
y= int(x)
while y<0:
y = int(input("Enter a number:"))
print('out?')
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 3 years ago.
I'm writing a program that ask for users input and check if it is an integer. If yes than it converts it into an integer and return with the value. If the user typed something which isn't a number than the program ask the user again to input a number. If the user press only an enter and keep the input empty than it will return with a default value.
def inputNumber(message):
number = input(message)
if number !='':
if number.isdigit():
number = int(number)
return number
else:
print("This is not a whole number! Try again.")
inputNumber(message)
else:
number = int(1000)
return number
The program works well until I write a letter. If I write for example 'x' than it will say try again:
Max cooldown(secs): x
This is not a whole number! Try again.
Max cooldown(secs):
But if I press an enter with empty input it will not return with the default value but with None. It is only happens when I make an error with writing a letter.
You recursively call inputNumber in the case of an input that is not a digit ... and in that condition you should be using:
return inputNumber(message)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am trying to do triple nesting of while loops.
If you input a decimal number it returns error, then if you input number above 31 it returns error, but if you try again to input decimal number code stops. Need help making it indefinite loop no matter how many times, or what order, a user inputs incorrect format. Also need to verify that dates input are valid for number of days in given month?
import string
varD= input("Enter Date/Day:")
while varD.isdigit() or varD.isspace()\
or varD.isdecimal or int(varD)>31 \
or int(varD)==26 or int(varD)<=0:
print ("Error: Enter Valid Number!")
varD= input("Enter Day:")
else:
print ("You have entered:", varD)
Use an infinite loop and break only when all criteria are satisfied instead.
while True:
varD = input("Enter Day:")
if varD.isdigit() and not varD.isspace() and varD.isdecimal() \
and int(varD) < 32 and int(varD) != 26 and int(varD) > 0:
break
print("Error: Enter Valid Number!")
print("You have entered: %s" % varD)
Also, your understanding of the term triple nesting is incorrect. Triple nesting means something like this:
while expression1:
while expression2:
while expression3:
do_something()
This question already has answers here:
Specify input() type in Python?
(2 answers)
Closed 4 years ago.
I am completely new to programming. However, I just wanna write a simple bit of code on Python, that allows me to input any data and the type of the data is relayed or 'printed' back at me.
The current script I have is:
x = input()
print(x)
print(type(x))
However, regardless of i input a string, integer or float it will always print string? Any suggestions?
In Python input always returns a string.
If you want to consider it as an int you have to convert it.
num = int(input('Choose a number: '))
print(num, type(num))
If you aren't sure of the type you can do:
num = input('Choose a number: ')
try:
num = int(num)
except:
pass
print(num, type(num))
1111 or 1.10 are valid strings
If the user presses the "1" key four times and then Enter, there's no magic way to tell if they wanted to enter the number 1111 or the string "1111". The input function gives your program the arbitrary textual data entered by user as a string, and it's up to you to interpret it however you wish.
If you want different treatment for data in particular format (e.g. if they enter "1111" do something with it as a number 1111, and if they enter "111x" show a message "please enter a valid number") then your program needs to implement that logic.