while循环下面的脚本

时间:2015-11-20 19:48:47

标签: python while-loop

我目前正在创建一个游戏,它会一遍又一遍地循环,直到你猜出正确的数字。

我遇到的问题是让循环命令正确。我想要进行一段时间的循环,但我可以让它工作,对于脚本的某些部分。如果我使用“while true”循环,if语句的print命令会一遍又一遍地重复,但如果我使用任何符号(<,>,< =,> =等),我似乎无法让它来处理elif语句。代码可以在下面找到:

#GAME NUMBER 1: GUESS THE NUMBER
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
attempt = 1
while  
    if num == x:
        print("Good job! it took you ",attempt," tries!")
        num + 1
    elif num >= x:
        print("Too high!")
        attempt = attempt + 1      
    elif num <= x:
        print("Too low!")
        attempt = attempt + 1
    else:
        print("ERROR MESSAGE!")

感谢任何和所有帮助。

3 个答案:

答案 0 :(得分:2)

您可以在while

中使用布尔值
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
attempt = 1
not_found = True
while not_found:
    num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
    if num == x:
        print("Good job! it took you ",attempt," tries!")
        not_found = False
    elif num > x: #Don't need the equals
        print("Too high!")
    elif num < x: #Don't need the equals
        print("Too low!")
    else:
        print("ERROR MESSAGE!")
    attempt = attempt + 1

答案 1 :(得分:1)

你需要一个冒号和一个条件

 while True:

如果你使用一段时间为True:你必须结束循环,你可以使用一个变量。

while foo:
    #Your Code

    if num == x:
        foo = False

此外,您可以使用字符串格式而不是破坏您的字符串。例如,

print("Good job! it took you %s tries!" % attempt)

print("Good job! it took you {0} tries!".format(attempt))

答案 2 :(得分:1)

你应该把你的问题放在循环中,因为你想在每次失败后重复询问是否正确。然后当用户找到它时,break循环:

attempt = 0
while True:  
    attempt = attempt + 1
    num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
    if num == x:
        print("Good job! it took you ",attempt," tries!")
        break
    elif num >= x:
        print("Too high!")
        attempt = attempt + 1      
    elif num <= x:
        print("Too low!")
    else:
        print("ERROR MESSAGE!")