调试硬币抛掷
下面程序的意图是一个简单的硬币抛掷猜测游戏。玩家有两次猜测机会(这是一个简单的游戏)。但是,程序中有一些缺陷。让程序运行几次,找出缺陷,使该程序能正确运行。
import random
guess = ''
while guess not in ('heads', 'tails'):
print('Guess the coin toss! Enter heads or tails:')
guess = input()
toss = random.randint(0, 1) # 0 is tails, 1 is heads
if toss == guess:
print('You got it!')
else:
print('Nope! Guess again!')
guesss = input()
if toss == guess:
print('You got it!')
else:
print('Nope. You are really bad at this game.')
更改过后:
主要是在第一次猜错的情况下,第二次猜没有随机硬币正反面,即如果第一次猜错,第二次猜其相反的那边就一定会猜对。其次就是随机数值0和1要和字符串‘heads’和‘tails’对应。
import random
guess = ''
while guess not in ('heads', 'tails'):
print('Guess the coin toss! Enter heads or tails:')
guess = input()
toss = random.randint(0, 1) # 0 is tails, 1 is heads
if toss==0:
toss='tails'
else:
toss = 'heads'
if toss == guess:
print('You got it!')
else:
print('Nope! Guess again!')
guess = input()
toss = random.randint(0, 1) # 0 is tails, 1 is heads
if toss == 0:
toss = 'tails'
else:
toss = 'heads'
if toss == guess:
print('You got it!')
else:
print('Nope. You are really bad at this game.')