+ 1
How can I check using if statement if variable isn't a string to enlist certain instructions after?
help
8 odpowiedzi
+ 3
try:
a = int(input())
except ValueError:
print('Enter an integer')
This will raise an exception if the input can't be converted into an integer
+ 1
you can use an 'if' statement to check if it is a string
if type(var) != str:
"""Do this"""
else:
"""Do something else""""
+ 1
Just did a couple of changes for your question
a=input('Enter a Number between 1-10: ')
if not a.isdigit():
print("Must be a Number")
else:
a = int(a)
if a<=5:
print("Correct")
if a>5 and a<=10:
print("Wrong")
if a==7:
print("but atleast you are lucky.")
else:
print()
print("Number must be between 1 to 10")
0
a=int(input('Enter a Number between 1-10: '))
if a(!int(input)):
print("Must be a Number")
if a<=5:
print("Correct")
if a>5 and a<=10:
print("Wrong")
if a==7:
print("but atleast you are lucky.")
else:
print()
print("Number must be between 1 to 10")
So you can see I am meaning to try that if user input isn't a number like specified, how would I program that? I would like a variety of ways so even more than one if anyone knows 😁
0
I'm not totally sure what exactly you want to do...
User input in Python is always of type str.
Do you want to see if the input is a number?
If it's an int you want you can check with the isdigit-method.
while True:
inp = input()
if inp.isdigit():
break
inp = int(inp)
You can also use a try-except pattern.
while True:
inp = input()
try:
inp = float(inp)
break
except:
print('Number I said!')
0
a=int(input('Enter a Number between 1-10: '))
This piece of code only lets integers be entered.
I just want to have print used to say enter a number if someone enters a string instead.
0
No, your piece of code lets a string be entered - like input in Python ALWAYS does (as I explained above).
Try it with your line. Enter a few letters and hit return. Tell me what happened.
0
a=int(input('Enter a Number: '))
print()
print(a)
ValidError: invalid literal for int() with base 10: 't'
T is the letter entered. Integers only work for the code above.