Devan F. answered 11/16/23
Microsoft AI Engineer & Cornell Grad For Computer Science Tutoring
Hi Liz, the problem here is related to flow of Python conditional statements.
An else statement in python only executes code when the preceding if block evaluates to false.
If we look at the code you provided, this means python will print 'user_num2 is less than or equal to 14', any time if user_num2 > 14 evaluates to false.
This means that any time user_num2 is less than or equal to 14, user_num2 is less than or equal to 14 will be printed. The problem occurs because this statement will be printed when a negative number is inputted (user_num2<14). In this scenario, both `user_num1 is negative` and user_num2 is less than or equal to 14 will be printed.
To fix this issue, we can use the else if functionality. This will ensure that only one print statement will be executed:
user_num1 = int(input())
user_num2 = int(input())
if user_num1 < 0:
print('user_num1 is negative')
elif user_num2 > 14:
user_num_2 = 2
print('user_num2 is', user_num2)
else:
print('user_num2 is less than or equal to 14')
Once we replace the if with an else if, if use_num1 <0, we print ('user_num1 is negative') and then exit the branches. The last branch will be skipped and only user_num1 is negative will be printed.