gpt4 book ai didi

python 剪刀石头布

转载 作者:行者123 更新时间:2023-12-01 04:07:27 26 4
gpt4 key购买 nike

我是编程新手,正在尝试使用 python 2.7 构建一个简单的石头剪刀布程序。在我的函数中,我有 2 个主要的 if 语句

rules = raw_input("Before we being playing would you like to hear the rules first? ")
if rules.lower() == "yes":
print """
Scissors cuts Paper
Paper covers Rock
Rock crushes Scissors"""

第二个

choice = raw_input("please enter your choice? (Must be either rock, paper or scissors) ")
computer = random.choice(["rock", "paper", "scissors"])

if choice == "rock" or "paper" or "scissors":
if choice == computer :
print "Its a tie !"
elif choice == "rock" and computer == "scissors":
print "Rock beats scissors you win!."

elif choice == "rock" and computer == "paper":
print "Paper beats rock you loose !."

elif choice == "paper" and computer == "scissors":
print "Scissors beats paper you loose !."

elif choice == "paper" and computer == "rock":
print "Paper beats rock you win !."

elif choice == "scissors" and computer == "paper":
print "Scissors beats paper you win !."

elif choice == "scissors" and computer == "rock":
print "Rock beats scissors you loose !."
else :
print "Invalid Entry Please try again."

这两段代码分别按其应有的方式工作,但是当我尝试将它们放在一个函数中时,第一个 if 语句询问规则有效,但随后在具有程序主要功能的第二个 if 语句之前退出。我尝试在第一个 if 语句中缩进第二位代码,但似乎不起作用

我想知道是否有办法让这两个代码片段在一个简单的函数中工作?或者我应该创建一个具有这两个函数的类?另外,如果有人对如何使我的程序变得更好有任何建议,请告诉我。感谢您提前提供的任何帮助。

这是完整代码

import random 

def rock_paper_scissors_spock():

rules = raw_input("Before we being playing would you like to hear the rules first? ")
if rules.lower() == "yes":
print """
Scissors cuts Paper
Paper covers Rock
Rock crushes Scissors"""

choice = raw_input("please enter your choice? (Must be either rock, paper or scissors) ")
computer = random.choice(["rock", "paper", "scissors"])

if choice == "rock" or "paper" or "scissors":
if choice == computer :
print "Its a tie !":

elif choice == "rock" and computer == "scissors":
print "Rock beats scissors you win!."

elif choice == "rock" and computer == "paper":
print "Paper beats rock you loose !."

elif choice == "paper" and computer == "scissors":
print "Scissors beats paper you loose !."

elif choice == "paper" and computer == "rock":
print "Paper beats rock you win !."

elif choice == "scissors" and computer == "paper":
print "Scissors beats paper you win !."

elif choice == "scissors" and computer == "rock":
print "Rock beats scissors you loose !."
else :
print "Invalid Entry PLease try again."


rock_paper_scissors_spock()

最佳答案

你说if choice == "rock"or "paper"or "scissors":,但是Python并没有将choice ==连接到所有的选择。你可以在 choice == "rock" 两边加上括号,它会做同样的事情。将其更改为 if choice in ("rock", "paper", "scissors")

关于 python 剪刀石头布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35379410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com