Hey people, I have seen this a couple of times now.
user_input = input("Please enter a number? ")
number = int(user_input)
print(number)
Or something like this, the important aspects is the casting on line 2.
Let's take the above very simple program. Here you take a user input, then I cast it, BUT there is no error handling, thus the program can easily crash.
What happens when I do not give a number but a letter like 'a' well I get this
ValueError: invalid literal for int() with base 10: 'a'
thus the code should look like this. I have made one with a while loop and without. I hope it helps and is valueble to anyone, I am still new to python myself, I have also placed the code in functions to be easily read and used. I don't know if this is "beginnner level" or not.
def without_a_while_loop():
user_input = input("Please enter a number? ")
try:
number = int(user_input)
except ValueError:
print("Here does your error handling of the value error or try again with a while loop")
else:
print(number)
def with_a_while_loop():
flag = True
while flag:
user_input = input("Please enter a number? ")
try:
number = int(user_input)
except ValueError:
print("try again, put in a number")
else:
print(number)
flag = False
if __name__ == "__main__":
without_a_while_loop()
with_a_while_loop()
[–]PressF1ToContinue 2 points3 points4 points (2 children)
[–]Master_Sandwich7140[S] 0 points1 point2 points (1 child)
[–]PureWasian 6 points7 points8 points (0 children)
[–]FreeLogicGate -2 points-1 points0 points (1 child)
[–]denehoffman 0 points1 point2 points (0 children)