簡體   English   中英

為什么我的代碼無限運行?

[英]Why is my code running infinitely?

這是一個偶數奇數計算器,可以無限運行而沒有任何錯誤。 有誰知道如何解決這一問題? 我可以不時用輸入來調用方法嗎?

def calc(time):
    i = 1
    while i <= time:
       num = int(input("Enter your number"))
       i + 1
       x=0
       y=0

       if (int(num) % 2 == 0):
          even = True
          print("even")


       elif (int(num) % 2 != 0):
          odd = True
          print("odd")



       if (odd == True):
         x += 1

       elif (even == True):
         y += 1


times = int(input("How many numbers will you be putting in this calc?"))

calc(times)

只是您錯了幾件事,其余的都還不錯,請在注釋中進行解釋:

[x,y,even,奇數]中的所有變量根本沒有用,所以這就是我刪除它們的原因。

def calc(time):
    i = 1
    while i <= time:
      num = int(input("Enter your number"))
      i+=1 # important thing here, to update the value the symbol is +=, not just +

      if (int(num) % 2 == 0):
          print("even")

      else: # there is no need of elif, if the number is not even, by definition, it is odd
          print("odd")

times = int(input("How many numbers will you be putting in this calc?"))

calc(times)

您可以在這里嘗試一下,看看如何正確完成工作:)-> https://repl.it/Nm70/0

行號5應該是i = i + 1

我假設您在stackoverflow上遇到格式化問題,而在您的實際代碼中沒有遇到格式化問題。 while循環后的行需要縮進,我假設您正在這樣做。 您的問題是您沒有增加i。 輸入后的第一行為i +1。這無濟於事,因為您沒有將其分配給任何東西。 稍后在代碼中將x + = 1和y + = 1遞增並賦值。 因此,基本上將您的i + 1行更改為i + = 1或i = i + 1

在while循環中,您想要的所有內容都需要用一個“制表符”縮進,如下所示:

while i <= time:
    #Code goes here

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM