这是我的代码:
name = input("What is your name? ")
print name + " do you want to play a game?"
answer = input("To play the game, type either yes or no. ")
if answer == yes:
print "Great," + name + "lets get started!"
elif answer == no:
print "Okay, good bye!"
import random
number = random.randint(1,50)
guess = input ("Pick a number between 1 and 50. This number cannot be a decimal. ")
if guess > number:
print "Your guess is too high!"
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
else import random
number = random.randint(1,50)
if guess == number:
print "You guessed it!"
print "Great job."
print "Do you want to play again?"
while answer == yes:
import random
number = random.randint(1,50)
guess = input ("Pick a number between 1 and 50. This number cannot be a decimal. ")
if guess > number:
print "Your guess is too high!"
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
if guess == number:
print "You guessed it!"
print "Great job."
print "Do you want to play again?
elif answer == no:
print "Okay. Good game " + name + "!"
print "Play again soon!"
好的,我的第一个问题是为什么python不能将name变量的输入识别为字符串。
第二个问题是最后一个elif语句一直给我一个语法错误。我不知道为什么。
最后一个问题是,我可以更轻松地循环此代码吗?
答案 0 :(得分:2)
在Python 2x版本中,input()
将变量变为integer
,您可以使用raw_input()
将其作为字符串。
因此,基本上将input()
更改为raw_input()
,以便将数据作为字符串。
在Python 3x版本中没有raw_input,只有input(),它将数据作为字符串。
第二个问题;
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
else import random
number = random.randint(1,50)
这不是正确的语法,您的else
需要一个if
块。如果没有else
阻止,您就无法使用if
。如果您想一秒钟,这是有道理的。
您的上一个问题不符合SO规则。