嗨,这是学校的工作,所以请不要给我正确的答案,但告诉我我做错了所以我可以去纠正它。 所以我的代码工作正常,但有一个问题。当我键入" Coin"时,显示硬币翻转后会显示错误消息。这是我的代码:
def program():
error_message = "Answer not recognised!\nMake sure it is spelt right and starts with a capital letter."
Choice = input("Pick either 'Card' or 'Coin' ")
if Choice == "Coin":
import random
r = random.randint(1,2)
if r == 1:
print ("Heads!")
else:
print ("Tails!")
if Choice == "Card":
import random
card_number = random.randint(1,13)
if card_number == 1:
card_number = "Ace"
elif card_number == 11:
card_number = "Jack"
elif card_number == 12:
card_number = "Queen"
elif card_number == 13:
card_number = "King"
if Choice == "Card":
import random
card_suit = random.randint(1,4)
if card_suit == 1:
card_suit = "Hearts"
elif card_suit == 2:
card_suit = "Clubs"
elif card_suit == 3:
card_suit = "Diamonds"
else:
card_suit = "Spades"
if Choice == "Card":
print(card_number ,"of" , card_suit)
#else print error message
else:
print(error_message)
while flag:
program()
flag = input('Would you like to run the program again? [yes/no] ') == 'yes'
else:
print ("The program will now terminate.")
我尝试了许多尝试解决这个问题的不同方法,但我无法弄明白。记住这是学校的工作,所以我想帮助,但不要被告知答案。感谢
答案 0 :(得分:1)
在program()
的最外层,您有四个单独的if
语句。每个人将一个接一个地执行。 else
附加到最终if
。
if Choice == "Card":
print(card_number ,"of" , card_suit)
#else print error message
else:
print(error_message)
当Choice
为Coin
时,Choice == "Card"
评估为false,因此选择了else
分支。你的意思是有一个if
这样的语句:
def program():
error_message = ...
Choice = ...
if Choice == "Coin":
# do all the coin related work
elif Choice == "Card":
# do all the card related work
else:
# handle the error
顺便说一句,它只是作为模块中的第一个代码,在风格上优于import
模块。
答案 1 :(得分:0)
谢谢大家我的代码现在正在运行,我现在只是想缩短它。谢谢 这是完成的代码:
import random
flag = True
def program():
error_message = "Answer not recognised!\nMake sure it is spelt right and starts with a capital letter."
Choice = input("Pick either 'Card' or 'Coin' : ")
if Choice == "Coin":
r = random.randint(1,2)
if r == 1:
print ("Heads!")
else:
print ("Tails!")
elif Choice == "Card":
card_number = random.randint(1,13)
if card_number == 1:
card_number = "Ace"
elif card_number == 11:
card_number = "Jack"
elif card_number == 12:
card_number = "Queen"
elif card_number == 13:
card_number = "King"
card_suit = random.randint(1,4)
if card_suit == 1:
card_suit = "Hearts"
elif card_suit == 2:
card_suit = "Clubs"
elif card_suit == 3:
card_suit = "Diamonds"
else:
card_suit = "Spades"
print(card_number ,"of" , card_suit)
else:
print(error_message)
while flag:
program()
flag = input('Would you like to run the program again? [yes/no] ') == 'yes'
else:
print ("The program will now terminate.")
我知道它的凌乱,但它现在有效,所以现在我将专注于缩短它并整理它。谢谢