+ 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)
2 Antworten
+ 2
try:
x = int(input())
except ValueError:
print("Enter an integer")
+ 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