Skip to content

Commit aa951c3

Browse files
committed
Introduce while loop
1 parent bafa217 commit aa951c3

1 file changed

Lines changed: 16 additions & 7 deletions

File tree

Ch03/try_except.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
1-
num_from_user = input("Enter a number: ")
1+
# Loop until the user enters a valid number
2+
while True:
3+
# Get input from the user
4+
user_input = input("Enter a number: ")
25

3-
try:
4-
num = int(num_from_user)
5-
except ValueError:
6-
print("You didn't enter a valid number.")
7-
num = 0
6+
try:
7+
# 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
813

9-
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

Comments
 (0)