+ 1

converting string to int

Is there an easy way to find out if turning an string to an int is "ok" like: x = int(input()) gives an error if the user inputs sth. else than an number (Or do I need a try catch block ... I forgot how they work)

16th Jul 2018, 6:03 PM
Anton Böhler
Anton Böhler - avatar
2 Respuestas
+ 2
try: x = int(input()) except ValueError: print("Enter an integer")
16th Jul 2018, 6:14 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 2
From what I'm aware of you do need to use a try block but they're simple... successful = true try: us_in = int(input()) except ValueError: successful = false Basic idea is that when an error occurs inside the try, Python checks if there's an appropriate except block and lets that handle it if theres not an appropriate one the error gets displayed. If you forget the error something produces just cause that error on purpose and Python will display it when it gets reached or google it. Note: any variables declared in trys can't be accessed by anything outside it
16th Jul 2018, 6:20 PM
TurtleShell
TurtleShell - avatar