0

I'm currently a few weeks into my first programming course. The language is Python and the assignment was to write a program that will take two numbers from user input and provide the sum. If the sum is >100, print a message saying it's a big number and don't print the value. If the sum is <100, add the two numbers the input provides and print the sum value.

Here's my code for that which seems to fit what the assignment asked for:

print("Please enter a number between 1 and 100: ")
num1 = int(input())
if num1 > 99:
    print("That number is greater than 100. Please try again.")
elif num1 < 1:
    print("That number is less than 1. Please try again.")

print("Again, please type any number between 1-100")
num2 = int(input())
if num2 > 99:
    print("That number is greater than 100. Please try again.")
elif num2 < 1:
    print("That number is less than 1. Please try again.")

sum = num1 + num2
if sum > 100:
    print("They add up to a big number")
elif sum < 100:
    print("Sum of ", num1, " and ", num2, " is = ", sum)

With this code however, if I for example input '0' as a value for example, it'll print to try again but of course proceed to the next instruction of num2.

In every programming assignment, the instructor gives bonus points for going the extra mile and learning on your own how to somehow better the code, which I always try and achieve. In this example, I'm trying to make it so that if I for example as stated above input the value '0', it'll print to try again and then loop back to the first input instruction rather than proceeding to num2.

I'm not looking for someone to do my homework, but rather a step in the right direction. I've done some research and am not sure what works best here, but it seems like a while loop might work? I'm unsure how to start implementing it with my code already existing.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
ajdbnabad13
  • 355
  • 3
  • 11

1 Answers1

0

In such cases it's better to use boolean flags.

bool lock = true;

while(lock):
    print("Please enter a number between 1 and 100: ")
    num1 = int(input())
    if num1 > 99:
        print("That number is greater than 100. Please try again.")
    elif num1 < 1:
        print("That number is less than 1. Please try again.")
    else:
        lock = false

It'll make sure that till the time a valid input is not entered the loop iterates and asks the user to input the same number again and again.

You could repeat it for the second number too.