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) 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.')怎么找bug
时间: 2024-02-24 17:57:56 浏览: 51
这段代码有几个问题。
1. 在第 7 行后面应该加上 `guess = guess.lower()` 将用户输入的字符串转成小写,从而避免大小写不一致导致的错误。
2. 在第 9 行中,`random.randint(0, 1)` 会随机生成 0 或 1,但是这里的 `guess` 变量存储的是字符串,因此需要将 `toss` 转换成字符串,即 `toss = 'heads' if random.randint(0, 1) == 0 else 'tails'`。
3. 在第 11 行和第 14 行应该将 `guesss` 改成 `guess`,否则会导致程序运行出错。
修改后的代码如下:
```
import random
guess = ''
while guess not in ('heads','tails'):
print('Guess the coin toss! Enter heads or tails:')
guess = input().lower()
toss = 'heads' if random.randint(0, 1) == 0 else 'tails'
if toss == guess:
print('You got it!')
else:
print('Nope! Guess again!')
guess = input().lower()
if toss == guess:
print('You got it!')
else:
print('Nope. You are really bad at this game.')
```
这样就可以正常运行了。
阅读全文