python - 如何在 Python 中获取用户输入?
问题描述
我想学习如何编写代码。
这是我想要的样子
Do you want strawberry ice cream? (y:n) n
Do you want chocolate ice cream? (y:n) y
Do you want mint ice cream? (y:n) n
Do you want vanilla ice cream? (y:n) y
那么输出将是:Here is your ice cream.
或者如果你把 N 放在所有,You did not say yes to any.
或者使用 else 语句:I didn't get that, try again.
非常感谢任何帮助,谢谢。
我的测试脚本:
def kind(chosenIce):
chosenIce=input("Do you want a ice cream (y:n) ")
if chosenIce1 == 'y':
ice1 = print("message")
if chosenIce2 == 'y':
ice2 = print("message")
if chosenIce1 == 'n':
ice1 = 0
if chosenIce2 == 'n':
ice2 = 0
else:
print("Sorry, I did not get that. Try again.")
kind(chosenIce)
解决方案
正如一些人所说,你必须使用input
and loop
(即for loop
or while loop
)来实现你的目标。通过阅读您的帖子和评论,您似乎真的是 Python 的新手。所以,下面,我给你一个基本的工作流程,可以满足你的需求。有很多方法可以实现您的目标。您可以查看我的工作流程以获取灵感。
这是代码:
def kind(ices_cream):
choices = []
for ice in ices_cream:
chosenIce = input('Do you want "{}" ice cream (y:n) '.format(ice))
if chosenIce == 'y':
choices.append(ice)
elif chosenIce == 'n':
print("You refuse ", ice)
else:
print("Sorry, I did not get that. Try again.")
if len(choices):
print("\n", "You buy", ' and '.join(choices))
else:
print("\n", "You buy nothing!")
if __name__ == "__main__":
ices_cream = ["Chocolate", "Strawberry", "Mint", "Vanilla"]
kind(ices_cream)
输出:这是一个例子
Do you want "Chocolate" ice cream (y:n) y
Do you want "Strawberry" ice cream (y:n) n
You refuse Strawberry
Do you want "Mint" ice cream (y:n) y
Do you want "Vanilla" ice cream (y:n) n
You refuse Vanilla
You buy Chocolate and Mint
注意:您可以添加一个循环while
来强制用户输入字符y
或n
. 此外,如果您想做得好,您可以添加异常处理。
推荐阅读
- autosar - Autosar DEM_GetEventUdsStatus 与 DEM 事件的关联
- python - 使用 Python 中的定义创建一个定义以覆盖或更多 plt.plot()
- gmail - Gmail API:获取垃圾邮件横幅警告文本
- python - Python:当我打印列表时,append() 函数不起作用?
- django - Django 模型约束
- flutter - 火力基地的错误
- c - 为什么 AVFrame pts 值不会影响帧的比特率?
- curl - HTTP/1.1 401 未经授权
- rust - 如何通过 .iter().enumerate 借用索引回报,并且生锈的寿命更长
- java - 将类对象添加到 ArrayList 时无法解析符号“add”