簡體   English   中英

while循環迭代后變量未更新

[英]Variable not being updated after while loop iterations

該程序應該將用戶的輸入與存儲在 'n' 變量中的隨機創建的整數進行比較。 此外,一旦實現,它應該返回用戶嘗試的次數。 出於某種原因,“嘗試”變量在每次迭代后都不會增加。 我想這個問題與我的 while 循環的位置有關。

import random
import time
import sys

def number_guess():
  n = random.randint(1,75)
  attempts = 0

  print(n)
  guess = int(input('Enter an integer from 1 to 75: '))
  
  if guess == n:
    print ('You Guessed It!')
    print ('You guessed the correct number in %s attempts!!!' % (attempts)) #This line always shows '0 attempts'
    time.sleep(5)
    sys.exit()
  else:
    while guess != n:
      if guess < 1 or guess > 75:
        print ('Remember, the integer should be from 1 to 75')
        attempts += 1
        number_guess()
      else:
        print ('You Missed It')
        attempts += 1
        number_guess()

number_guess()

如您所見,我對編程很陌生。 任何更正將不勝感激。 謝謝!

每次您猜錯時,問題是什么,您都會重新調用number_guess ,而這又會重置attempts 因此,您要解決的問題是,當您再次撥打電話時,將您的嘗試號碼發送給它。 如果您不輸入數字,它將默認為 0。

import random
import time
import sys

def number_guess(attempts=0):
  n = random.randint(1,75)

  print(n)
  guess = int(input('Enter an integer from 1 to 75: '))
  
  if guess == n:
    print ('You Guessed It!')
    print ('You guessed the correct number in %s attempts!!!' % (attempts)) #This line always shows '0 attempts'
    time.sleep(5)
    sys.exit()
  else:
    while guess != n:
      if guess < 1 or guess > 75:
        print ('Remember, the integer should be from 1 to 75')
        attempts += 1
        number_guess(attempts)
      else:
        print ('You Missed It')
        attempts += 1
        number_guess(attempts)

number_guess()

您不需要在自身內部不斷調用 number_guess() (遞歸)。 我移動了你的 while 循環以避免這種情況。 這是一個更好的方法:

import random
import time
import sys

def number_guess():
  n = random.randint(1,75)
  attempts = 0
  guess = 0 # can be any number other than a valid guess number

  print(n)

  while guess != n:
    guess = int(input('Enter an integer from 1 to 75: '))
    
    if guess == n:
      attempts += 1 # added this to add an attempt for correct answers too
      print ('You Guessed It!')
      print ('You guessed the correct number in %s attempts!!!' % (attempts)) #This line always shows '0 attempts'
      time.sleep(5)
      sys.exit()
    else:
      if guess < 1 or guess > 75:
        print ('Remember, the integer should be from 1 to 75')
        attempts += 1
      else:
        print ('You Missed It')
        attempts += 1

number_guess()

暫無
暫無

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

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