-2

I have been working on a project and I came across this problem in my program and was wondering if somebody is able to tell me a fix. Here I have to take input from the user the number of times they want the program to run. I do take inputs during the course of my loop and run the loop in range N (the number of times the user wants the program to run), but I terminate the program when 1 < N < 100. Here is sample code -

n = int(input("Number of times you want the program to run - "))
if n <= 0 or n >= 100 : 
    print("Number entered too large/big")
    quit()

for i in range(n):
    string = input("Enter a word - ")
    print(i)

I have tried running the code without the input and it all runs fine but as soon as I start taking inputs the program malfunctions. When I enter N less than zero the program quits and when N in the valid range the program works fine but when N > 100 the program continues till completion and the closes the console (working in Spyder). Would really appreciate some help :)

Pythaconda
  • 39
  • 1
  • 5

1 Answers1

0

So i found the problem with the code, the quit() doesn't do anything, hence whenever you enter any value, the for loop will always run.

Now why does quit() work for when n<=0? Easy answer, it doesn't. When you enter for i in range(n) and if n <= 0 for example n= -3, then this is what the for loop resolves to

i=0
while i < n:
   i += 1

so when n = -3 or n<=1 then for loop never executes, thus acting as if the quit() worked. To get it to work, either use sys.exit to shut python file, or do something like

n = int(input("Number of times you want the program to run - "))
if n <= 0 or n >= 100 : 
    print("Number entered too large/big")
else:
    for i in range(n):
        string = input("Enter a word - ")
        print(i)

This code works as desired

P.S As to why quit() doesn't work, that i wouldn't know, i have never used spyder and hence haven't come across the quit() function

Imtinan Azhar
  • 1,595
  • 7
  • 25
  • Thanks. The sys.exit solved my problem but why doesn't the quit() work? Isn't quit() also used for terminating the program/console? – Pythaconda Sep 17 '19 at 10:43
  • That i am not really sure of, could be spyder specific issues, i dont have experience with that, apologies in that regard :) – Imtinan Azhar Sep 17 '19 at 10:44
  • You may refer to this for understanding why quit doesn't work https://stackoverflow.com/questions/19747371/python-exit-commands-why-so-many-and-when-should-each-be-used/19747562 – Imtinan Azhar Sep 17 '19 at 10:48