41.9k views
1 vote
# line 1 age = int(input("Enter your age: ")) # line 3 print("Invalid input") If we want the computer to display "Invalid input" whenever a floating point number such as 20.5 is entered by the user, what should be inserted in line 1 and line 3?

1 Answer

5 votes

Answer:

Insert

'try:' at line 1

'except:' at line 3

Step-by-step explanation:

The "try and except" commands in Python are used for exception handling.

try: the statements under this block are executed normally

except: the the statements under this block are executed when there is an exception.

We can use these commands to handle errors, for example, in the given scenario we don't want the user to enter a floating point number such as

1.5, 2.6 etc.

When the user enters an integer number then the except command is not executed.

When the user enters a floating point number then the except command is executed, program is stopped and error message is shown that is at line 4

Python code:

# line 1

try:

# line 2

age = int(input("Enter your age: "))

# line 3

except:

# line 4

print("Invalid input")

Output:

Test 1:

Enter your age: 20

Test 2:

Enter your age: 20.5

Invalid input

# line 1 age = int(input("Enter your age: ")) # line 3 print("Invalid-example-1
# line 1 age = int(input("Enter your age: ")) # line 3 print("Invalid-example-2
User Adam Jagosz
by
5.4k points