How to use input() to only accept positive numbers as int, [duplicate] - python

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.

Related

Function to detect integers instead string in Python [duplicate]

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 ...

Problem with checking if input is integer (very beginner) [duplicate]

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')

How do i represent an integer in python? [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 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

Data type conditions in python [duplicate]

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")

Seeing if a user typed in an integer for input [duplicate]

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.

Categories

Resources