我有几天的Python知识。我上过Codecademy之类的课程,我想潜入一个项目。在该项目开始时,我观看了YouTube视频,以了解其精髓。
我的游戏会询问是否要玩,如果是,它将继续玩。如果“否”,程序将停止。我不知道如何更改它以使其继续播放。
程序也不会显示该数字大于或小于显示while
循环之后的数字。最初,我在while
循环之后使用了这段代码,但是没有什么区别。
我只是一个总初学者,想通过实际项目更好地学习Python,所以我真的不确定在这里采取哪些步骤:
import random
number = random.randint(1,10)
tries = 1
name = input("Hello, What is your name?")
print("Hello there,", name)
question = input("Time to guess, ready? [Y/N]")
if question == "n":
print("sorry, lets go!")
if question == "y":
print("Im thinking of a number between 1 and 10.")
guess = int(input("Have a guess"))
if guess < number:
print("That is too low!")
if guess == number:
print("Congrats! You win!!")
if guess > number:
print("That is too high!")
while guess != number:
tries += 1
guess = int(input("Try again: "))
。
Hello, What is your name?name
Hello there, name
Time to guess, ready? [Y/N]y
Im thinking of a number between 1 and 10.
Have a guess1
That is too low!
Try again: 10
Try again: 10
Try again: 10
Try again:
永远不会显示消息“太高”。
答案 0 :(得分:0)
答案 1 :(得分:0)
使用elif
不连续的if
语句。更改您的while
循环以允许break
退出,以便您可以显示正确的获胜消息。
import random
number = random.randint(1,10)
tries = 1
name = input("Hello, What is your name?")
print("Hello there,", name)
question = input("Time to guess, ready? [Y/N]")
if question == "n":
print("sorry, lets go!")
if question == "y":
print("Im thinking of a number between 1 and 10.")
guess = int(input("Have a guess"))
while True:
if guess < number:
print("That is too low!")
elif guess == number:
print("Congrats! You win!!")
break
elif guess > number:
print("That is too high!")
tries += 1
guess = int(input("Try again: "))
答案 2 :(得分:0)
我使用@furas,因为这实际上应该是一对嵌套的while
循环,其结构类似于:
import random
name = input("Hello, What is your name? ")
print("Hello there,", name)
answer = "y"
while answer.lower().startswith("y"):
number = random.randint(1, 10)
print("I'm thinking of a number between 1 and 10.")
guess = int(input("Have a guess: "))
while True:
if guess < number:
print("That is too low!")
elif guess > number:
print("That is too high!")
else:
print("Congrats! You win!")
break
guess = int(input("Try again: "))
answer = input("Play again? [Y/N]: ")
print("Goodbye!")