We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent bafa217 commit aa951c3Copy full SHA for aa951c3
1 file changed
Ch03/try_except.py
@@ -1,9 +1,18 @@
1
-num_from_user = input("Enter a number: ")
+# Loop until the user enters a valid number
2
+while True:
3
+ # Get input from the user
4
+ user_input = input("Enter a number: ")
5
-try:
- num = int(num_from_user)
-except ValueError:
6
- print("You didn't enter a valid number.")
7
- num = 0
+ try:
+ # Try to convert the input to an integer
8
+ number = int(user_input)
9
+ except ValueError:
10
+ # If the input can't be converted to an integer, print an error message and continue the loop
11
+ print("You didn't enter a valid number. Please try again.")
12
+ continue
13
-print(f"Your number squared is {num**2}")
14
+ # If the input was successfully converted to an integer, break the loop
15
+ break
16
+
17
+# Print the square of the number
18
+print(f"Your number squared is {number**2}")
0 commit comments