Python暖/冷声明变量外循环

时间:2016-10-12 18:09:44

标签: python while-loop

我正在用Python编写一个简单的更温暖/更冷的猜数游戏。

我有它工作,但我有一些重复的代码,导致一些问题,我不知道如何解决它。

from __future__ import print_function
import random

secretAnswer = random.randint(1, 10)

gameOver = False
attempts = 0
currentGuess = int(input("Please enter a guess between 1 and 10: "))
 originalGuess = currentGuess

while gameOver == False and attempts <= 6:
    currentGuess = int(input("Please enter a guess between 1 and 10: "))
    attempts += 1

originalDistance = abs(originalGuess - secretAnswer)
currentDistance = abs(currentGuess - secretAnswer)

if currentDistance < originalDistance and currentGuess != secretAnswer:
    print("Getting warmer")

elif currentDistance > originalDistance:
    print("Getting colder")

if currentDistance == originalDistance:
    print("You were wrong, try again")

if currentGuess == secretAnswer or originalGuess == secretAnswer:
    print("Congratulations! You are a winner!")
    gameOver = True

if attempts >= 6 and currentGuess != secretAnswer:
    print("You lose, you have ran out of attempts.")
    gameOver = True

print("Secret Answer: ", secretAnswer)
print("Original Dist: ", originalDistance)
print("Current Dist: ", currentDistance)

它在我进入循环之前要求输入,这是为了允许我设置一个原始猜测变量,帮助我计算出我的秘密答案的距离。

但是,因为这需要在循环之前输入它会使我所拥有的任何验证/逻辑(例如if语句)无效,然后需要在此猜测之后直接输入,现在在循环内部。

有没有办法让我在循环中声明originalGuess而不更新用户输入猜测每次迭代,反之亦然而不重复currentGuess?

由于

1 个答案:

答案 0 :(得分:1)

在你进入循环之前似乎不需要询问用户...你可以检查一下猜猜是否猜测= ...

gameOver=False
guesses = 0
while not gameOver:
    guesses += 1
    getUserInput
    if guesses = 1 and userInput != correctAnswer:
      print "try again!"  
    checkUserInput
print "good job!, it took you {} guesses!".format(guesses)
相关问题