Bai*_*row 1 python if-statement
由于我是初学者,我正在尝试创建一个小石头剪刀布游戏,但是我的 if 和 elif 语句有问题。
import random
player_score = 0
computer_score = 0
options = ['rock', 'paper', 'scissors']
def player_choice():
input('Rock, Paper or Scissors? ')
return player_choice
def computer_choice():
print(random.choice(options))
return computer_choice
ps = print('player score: ', player_score)
cs = print('computer_score: ',computer_score)
while player_score or computer_score < 10:
player_choice()
computer_choice()
if player_choice == 'rock' and computer_choice == 'rock':
print('Tie')
elif player_choice == 'rock' and computer_choice == 'paper':
print('Computer wins')
computer_score = computer_score + 1
print(ps)
print(cs)
elif player_choice == 'rock' and computer_choice == 'scissors':
print('You win')
player_score = player_score + 1
print(ps)
print(cs)
Run Code Online (Sandbox Code Playgroud)
似乎整个 if/elif 块都被忽略了,并且没有打印或增加任何内容。没有错误弹出,它只是简单地被忽略。
您的代码存在一些问题,我将尝试解决所有问题。
第一个与变量的命名有关。您将函数命名为computer_choiceand player_choice,然后检查它们是否等于"rock"或其他字符串。这只会返回 False 因为它computer_choice是一个函数,而不是一个字符串。我建议将您的函数名称更改为get_computer_choice()和get_player_choice()
其次,ps = print('player score: ', player_score)。我不知道你想在那里做什么。pswill None,因为print()不返回任何东西。
第三,你的函数返回自己。
def my_func():
return my_func
Run Code Online (Sandbox Code Playgroud)
将返回一个函数。您想要为您的两个选择功能做的是:
def get_player_choice():
player_choice = input('Rock, Paper or Scissors? ')
return player_choice
def get_computer_choice():
computer_choice = random.choice(options) # Set computer_choice to computers choice
print(computer_choice)
return computer_choice
Run Code Online (Sandbox Code Playgroud)
第四,在你的 while 循环下,你正在调用函数,但没有对返回做任何事情。改变
while player_score or computer_score < 10:
player_choice()
computer_choice()
Run Code Online (Sandbox Code Playgroud)
到
while player_score or computer_score < 10:
player_choice = get_player_choice()
computer_choice = get_computer_choice()
Run Code Online (Sandbox Code Playgroud)
最后,if ... else语句需要在 while 循环下缩进,否则它们永远不会被执行。
| 归档时间: |
|
| 查看次数: |
258 次 |
| 最近记录: |