This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
How do i give a condition in which for example; if x is not an integer print("type an integer")
With your sample code, your best bet is to catch the ValueError and try again:
def get_int():
try:
return int(input('Type an integer:'))
except ValueError:
print("Not an int. Try again.")
return get_int()
The reason is because if the user enters a non-integer string, then the exception gets raised before you have a chance to check the type, so isinstance doesn't really help you too much here.
One way would be casting the value to into and handle the exception:
try:
parsed = int(user_input)
print ("int")
except:
print ("not int")
Related
This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
How can I check if string input is a number?
(30 answers)
Closed 1 year ago.
I'm trying to make a function that count the numbers of characters in a string and detect when an integer is typed, the condition is use "if" function. I'd expect that if I type any integer like"4464468" instead a string, the program displayed: "Sorry, you typed an integer". But, instead, counts the total number and displayed "The word you type has 7 characters".
My code is next:
def string_lenght(mystring):
return len(mystring)`
#Main Program
mystring = (input("Type a word: "))
if type(mystring) == int or type(mystring) == float:
print("Sorry, you typed an integer")
else:
print("The word you typed has",string_lenght(mystring), "characters")
I'm Newbie at Python. I really appreciate your help and patience.
Best regards.
input() always returns a string so you can try to convert it into int/float, if the operation is successful then it's a number, else it is a string:
try:
float(mystring)
print("Sorry you typed an integer")
except ValueError:
# Rest of the code ...
This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 4 years ago.
I'm trying to build a code which executes the length of a string
This code should be able to accept only Strings and return their length but when integer or float values are given, it counts their length too.
def length(string):
if type(string)== int:
return "Not Available"
elif type(string) == float:
return "Not Allowed"
else:
return len(string)
string=input("Enter a string: ")
print(length(string))
Output:
Enter a string: 45
2
You expect to get output 'Not Available' for the input 45. But it won't happen because,
while reading input from keyboard default type is string. Hence, the input 45 is of type str. Therefore your code gives output 2.
input returns a string so if you check its type it will always be string. To check if its an int or a float you have to try to cast it.
try:
int(input)
except ValueError:
# not an int
return "Not Available"
try:
float(input)
except ValueError:
# not a float
return "Not Allowed"
return len(string)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed 4 years ago.
im really new in Python 3.7
im testing some stuff out, and i try to understand how can i ask someone his age. but if he enter a letter or a negative number it say, only positive number please then it ask the question again, if the number is positive then the program continue.
here is my code so far giving me an error:
while true :
age = input('Your age : ')
try:
age = int(age)
except ValueError:
print ('Numbers only')
continue
else:
break
giving me as error : ,
> line 10
age = input()
^
SyntaxError: expected an indented block
Does this help? This works:
while True:
age = input('Your age')
try:
age = int(age)
break
except ValueError:
print ('Numbers only')
Explanation: condition 'True' is True by definition, so the loop occurs indefinitely until it hits a "break." Age takes standard input and tries to convert it to an integer. If a non-integer character was entered, then an exception (ValueError) will occur, and "Numbers only" will be printed. The loop will then continue. If the user enters an integer, the input will be converted to an integer, and the program will break from the loop.
In regard to syntax errors: In Python syntax, it the keyword is "True" instead of true. You need to indent all items following a loop or conditional (in this instance, the error occurred when the program encountered age=input('Your age :'), which needs to be indented.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am taking in intro CS course and am playing around with some of my old code from an early lab. The program asks for four separate inputs from the user and will then spit out a graph according to the four inputs. I'm trying to get it where if the user does not enter a number then it asks for them to try again and prompt for another input. I've tried things like:
(if x != int:) and (if x =\= int:) but nothing has worked for me.
You could do something like this:
userInput = 0
while True:
try:
userInput = int(input("Enter an integer: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yay an integer!")
break
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
hours = 0.0
while hours != int:
try:
hours = int(raw_input('Enter how many hours ahead you want to know the weather: '))
break
except ValueError:
print "Invalid input. Please enter an integer value."
hours = int(raw_input('Enter how many hours ahead you want to know the weather: '))
Okay, so I am trying to make sure a user inputs an integer value. If I don't type in an integer the "Invalid input, Please enter an integer value." will come up and I will then enter in another non integer value and will end up getting an error message. So why does it work the first time and not the second?
Use break statement to get out of the loop when user input correct integer string.
hours = 0.0
while True:
try:
hours = int(raw_input('Enter how many hours ahead you want to know the weather: '))
break # <---
except ValueError:
print "Invalid input. Please enter an integer value."
# No need to get input here. If you don't `break`, `.. raw_input ..` will
# be executed again.
BTW, hours != int will always yield True. If you want to check type of the object you can use isinstance. But as you can see in the above code, you don't need it.