简体   繁体   English

我的 for 循环和 while 循环的语法问题不断重复(python)

[英]Syntax issue with my for loop and while loop keeps repeating infinitely (python)

I was working on a for loop and while loop for 2 separate programs asking for the same thing.我正在为两个不同的程序开发一个 for 循环和 while 循环来要求相同的东西。 My for loop is giving me syntax issues and won't come out as expected…我的 for 循环给了我语法问题,并且不会按预期出现......

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.期望:一个 python 程序,它以正 integer 作为输入,将所有从零到输入数字的整数相加,然后打印总和。 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: ")) i1 = int(input("请输入正数 integer:"))

if i1 >= 0:如果 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…而我的 While 循环正在无限打印“插入数字”……

Here is what my while loop looks like:这是我的 while 循环的样子:

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 `与我的 for 循环相同的期望,但与 while 循环相同

Anyone know anyway I could fix this issue?任何人都知道我可以解决这个问题吗?

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: Output 样品:

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 .docs中查看有关缩进的更多信息。

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM