This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I'm just starting to learn Python (it's my first language). I'm trying to make a simple program that checks if the number the user inputs is an integer.
My code is:
number = input('Insert number: ')
if isinstance(number, int):
print('INT')
else:
print('NOT')
I have no idea why, but every number gets it to print 'NOT'. If I just make a statement 'number = 1' in the code, it prints 'INT', but if I input '1' in the console when the program asks for input, it prints 'NOT' no matter what. Why is that?
(I'm using Python 3.8 with PyCharm)
When you input something, the type is always a str. If you try:
number = input('Insert number: ')
if isinstance(number, str):
print('INT')
else:
print('NOT')
you will always get:
INT
If all you want is to detect whether the input is an integer, you can use str.isdigit():
number = input('Insert number: ')
if number.isdigit():
print('INT')
else:
print('NOT')
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
What's the canonical way to check for type in Python?
(15 answers)
How can I read inputs as numbers?
(10 answers)
Closed last year.
I am a beginner when it comes to coding. I am trying to run a program on python that takes in kilometers(user input) and returns it in miles(output). I know how to do the task but I wanted to challenge myself by using if statements to check if the user has entered a number:
Kilometers = input("Please insert number of Kilometers: ")
if type(Kilometers) == int or float:
print("This is equivalent to", float(Kilometers)/1.609344, "Mile(s)")
else:
print("This is not a number")
I understand that whatever the user inputs will be saved as a string. However, whenever I run the code, the program always tries to convert the input into miles.
I have specified in the if statement that the type has to equal a float or an int, so shouldn't the output always be "This is not a number" until I change the first line to:
Kilometers = float(input("Please insert number of Kilometers: "))
or
Kilometers = int(input("Please insert number of Kilometers: "))
When programming if statements in Python, each condition must be fully rewritten. For example, you would write if type(Kilometers) == int or type(Kilometers) == float rather than if type(Kilometers) == int or float. Another important thing in your code is that if someone inputs 5.5, you would expect a float value, but Python interprets that to be a string. In order to circumvent this, you can use a try/except clause like this:
Kilometers = input("Please insert number of Kilometers: ")
try:
Kilometers = float(Kilometers)
print("This is equivalent to", Kilometers/1.609344, "Mile(s)")
except ValueError:
print("This is not a number")
What this is doing is trying to set Kilometers as a float type, and if the user inputs a string that cannot be interpreted as a float, it will cause a ValueError, and then the code inside except will run. You can find more on try/except clauses here: Python Try Except - W3Schools
One more thing I noticed is that you should name your variables according to the standard naming conventions, so Kilometers should be kilometers. You can find more on the naming conventions here: PEP 8
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 can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I want to take from the user an input integer, and turning to a string in my code.
My line of code for that is:
num1 = input(int(str("Enter a number: ")))
But the console says: ValueError: invalid literal for int() with base 10: 'Enter a number: '
If this line isn't correct can you show me a way how can I turn an integer that is given by the user to a string in my code?
You have the functions in the wrong order: First you need to turn the input into a Python object, so input() has to be the innermost function (to be applied first). Also, input() will cast the input as a string by default, so you don't need str().
So the line should read:
num1 = input("Enter a number: ")
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 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.