Home > front end >  Python Loop For (Error in printing final exit program)
Python Loop For (Error in printing final exit program)

Time:04-13

  1. I need to run a code using 'loop for' 20 times.
  2. If there is no user input (enter), my code should print "Exit program~~" and break the loop.
  3. If the code is ran 20 times already, the code should print "Exit program~~" AFTER printing the last (2oth) input number.
  4. I need ' /- number' to be printed after every time user inputs the number.
  5. The output must be printed with str.format()

Output should be like this: Enter the number : 0 0 : zero Enter the number : 17 17 : positive Enter the number : -8 -8 : negative Enter the number: Exit program~~

My problem: My code works, but I can't figure out how to print "Exit program~~" after I input numbers 20 times. *But "Exit program~~" works when I exit before inputting all 20 times.

My code:

sign = ['positive', 'negative', 'zero']

for i in range(20):
    num = input('Enter the number : ')
    if num == '':
        print('{}'.format('Exit program~~'))
        break
    else:
        if int(num) > 0:
            print('{: .0f} : {}'.format(int(num), sign[0]))
        else:
            if int(num) < 0:
                print('{:-.0f} : {}'.format(int(num), sign[1]))
            else:
                print('{: .0f} : {}'.format(int(num), sign[2]))

CodePudding user response:

Simply

print('Exit program~~')

right after the for loop. So after the for loop runs 20 times, Exit program~~ will be printed.

CodePudding user response:

sign = ['positive', 'negative', 'zero']

for i in range(20):
    num = input('Enter the number : ')
    if num == '':
        break
    else:
        if int(num) > 0:
            print('{: .0f} : {}'.format(int(num), sign[0]))
        else:
            if int(num) < 0:
                print('{:-.0f} : {}'.format(int(num), sign[1]))
            else:
                print('{: .0f} : {}'.format(int(num), sign[2]))

print('{}'.format('Exit program~~'))

Have you considered something like this? Just removing the print for the case where nothing is entered and just having one print for anytime the loop is exited.

  • Related