Python 3:随机选择使用if语句命令

2024-10-02 16:25:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python/programming非常陌生,而且,我一直在玩一个小的随机选择生成器。到目前为止,我对所有的工作方式都很满意,但是我对if语句有一个问题。我该如何指示if应该指向table Desert中的第一个生成的选项,而不是生成第二个选择?我尝试过在print命令中嵌套if语句,但是有很多语法错误。代码如下:

import random
import sys

Name = ['Dave', 'Suzane', 'Jim', 'Diana']

Appitizers = ['Spinach & Artichoke Dip', 'Crispy Green Beans', 'Half Chicken Quesadila', 'None, for me, just the main course please']

MainCourse = ['Steak', 'Sea Food', 'Grilled Chicken', 'House Salad', 'Rib Sanwich', 'Soup of the Day']

Desert = ['Pie of the Day', 'Chocolate Moose', 'Cheeze Cake', "No Thanks, I'm Full!"] 

Goodbye = ['Captian', 'Monsiure', 'Sir', 'Madame',]

Goodbye2 = ['Come back again!', 'See you soon', 'Thank you for stopping by', 'Thank you for choosing us!']

print("Hello ", random.choice(Name), "tonight you're meal will be:")
print("Appitizer:", random.choice(Appitizers))
print("Followed by Main Coure:", random.choice(MainCourse))
print("And finally Desert:", random.choice(Desert))
if random.choice(Desert)=="No Thanks, I'm Full!": print('Farwell!', random.choice(Goodbye1)), sys.exit()

print(random.choice(Goodbye2))

谢谢!在


Tags: thenameimportyouforifsysrandom
1条回答
网友
1楼 · 发布于 2024-10-02 16:25:38

random.choice(Desert)的结果赋给一个变量,并在两个适用的地方使用它。(同时,将Goodbye1更改为一个存在的变量,例如Goodbye

x = random.choice(Desert)
print("And finally Desert:", x)
if x=="No Thanks, I'm Full!": 
    print('Farwell!', random.choice(Goodbye)) 
    sys.exit()

相关问题 更多 >