我正在尝试在Python 2.7中编写一个猜词程序。用户有50次机会正确猜出该单词。我已经编写了一个从单词列表中生成随机单词的函数。用户需要正确猜出单词。
例如,如果正确的单词是“dog”并且用户猜到“apple”,程序将返回“太低”,然后用户将再次猜测。如果用户猜到“梨”,程序将返回“太高”。
我真的不知道如何开始编写这段代码。我尝试使用while循环,但我不知道从哪里开始。谢谢大家。
这是我到目前为止所拥有的:
注意:“正确”是用户试图猜测的字词;猜是用户猜到的词
while guess != 'correct':
if guess < correct:
print 'Too low'
guess = int(raw_input('Enter a word')
elif guess > correct:
print 'Too high'
guess = int(raw_input('Enter a word')
else:
print 'You finally got it!'
break
print
while tries < 50:
guess = raw_input('Guess a word')
if guess not in word:
print "Sorry, try again."
else:
print 'Good job!'
else:
print "Sorry. My word was ", word, ". Better luck next time!"
答案 0 :(得分:2)
不需要2个循环。你可以使用 AND 如果一个人猜到这个词是对的,或者那个人的生命已经用完,那么这将停止你的循环。您也不需要为输入说 int(),因为您只输入一个单词。如果单词“太低”,则打印它会减少生命并输入一个新单词,类似于“太高”。当你的生命处于0或你猜到了
这个词时,你会停下来guess = raw_input('Guess a word: ')
correct = 'dog'
lives = 50
while guess != correct and lives != 0:
if guess < correct:
print 'Too low'
lives -= 1
guess = raw_input('Enter a word: ')
else:
print 'Too high'
lives -= 1
guess = raw_input('Enter a word: ')
if lives == 0 and guess != correct:
print "Sorry. My word was", correct,". Better luck next time!"
else:
print "You finally got it!"
答案 1 :(得分:2)
我喜欢OmO Walker's answer这个问题。以下是OmO代码的略微变化。
# I like adding a .lower() so the person doesn't have to worry about the case matching.
correct = 'dog'.lower()
lives = 2
guess = None
# I like doing a > check not an != because stuff happens and if lives become < 0 you
# get stuck in an infinite loop. BUT in some cases comparisons <, > can be slower than ==.
# So if speed is a problem stick to ==
while not guess == correct and not lives <= 0:
# Moving this here makes it so there are fewer places you have to get input.
# Prints how many lives the user has left.
print "{} lives remaining".format()
guess = raw_input('Guess a word: ').lower()
if guess < correct:
print '{} was too low'.format(guess)
elif guess > correct:
print '{} was too high'.format(guess)
lives -= 1
if not lives > 0 and not guess == correct:
# I like using the format string method instead of adding strings or using ',' in a print. It is more reliable if
# the variable you are trying to print is not a string.
print "Sorry. My word was {}. Better luck next time!".format(correct)
# Makes sure the guess is really right before giving the confirmation
elif guess == correct:
print "You got it! The word was {}".format(correct)
# This is an added safety that will be triggered if some how the other conditions fall through. Its better to
# have an error thrown than have a program silently break.
else:
print "ERROR. Something is broken"