+ 1

How can I check using if statement if variable isn't a string to enlist certain instructions after?

help

11th May 2019, 8:46 PM
Jack
Jack - avatar
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
12th May 2019, 5:24 AM
Anna
Anna - avatar
+ 1
you can use an 'if' statement to check if it is a string if type(var) != str: """Do this""" else: """Do something else""""
11th May 2019, 10:45 PM
Brian Petry
Brian Petry - avatar
+ 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")
12th May 2019, 4:26 AM
Choe
Choe - avatar
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 😁
11th May 2019, 10:49 PM
Jack
Jack - avatar
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!')
11th May 2019, 11:05 PM
HonFu
HonFu - avatar
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.
11th May 2019, 11:25 PM
Jack
Jack - avatar
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.
11th May 2019, 11:42 PM
HonFu
HonFu - avatar
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.
12th May 2019, 12:04 AM
Jack
Jack - avatar