Home > database >  Syntax issue with my for loop and while loop keeps repeating infinitely (python)
Syntax issue with my for loop and while loop keeps repeating infinitely (python)

Time:01-06

I was working on a for loop and while loop for 2 separate programs asking for the same thing. My for loop is giving me syntax issues and won't come out as expected…

Expectations: A python program that takes a positive integer as input, adds up all of the integers from zero to the inputted number, and then prints the sum. If your user enters a negative number, it shows them a message reminding them to input only a positive number.

reality:

i1 = int(input("Please input a positive integer: "))

if i1 >= 0:

value = 0 # a default, starting value

for step in range(0, i1): # step just being the number we're currently at
    value1 = value   step
print(value1)

else:
   print(i1, "is negative")

And my While loop is printing "insert a number" infinitly…

Here is what my while loop looks like:

while True:
  try:
    print("Insert a number :")
  n=int(input())
  if(n<0):
    print("Only positive numbers allowed")
 else:
    print ((n*(n 1))//2)
 except ValueError:
  print("Please insert an integer")

`Same expections as my for loop but as a while loop

Anyone know anyway I could fix this issue?

CodePudding user response:

You have some indentation issues. This way works:

while True:
    try:
        print("Insert a number: ")
        n = int(input())
        if n <= 0:
            print("Only positive numbers allowed")
        else:
            print(n * (n 1) // 2)
    except ValueError:
        print("Please enter an integer")

Output sample:

Enter a number: 
>>> 10
55
Enter a number: 
>>> 1
1
Enter a number: 
>>> -1
Only positive numbers allowed
Enter a number: 
>>> asd
Please enter an integer
Enter a number: 

See more about indentation in the docs.

CodePudding user response:

I think the issue here is the indentation of the code, try like this: (if this is not the issue please send me a message, I will try to help if I can)

while True:
    try:
        print("Insert a number :")
        n=int(input())
        if n < 0:
            print("Only positive numbers allowed")
        else:
            print((n*(n 1))//2)
    except ValueError:
        print("Please insert an integer")
  •  Tags:  
  • Related