首页 > 解决方案 > 如何在 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)

标签: python

解决方案


正如一些人所说,你必须使用inputand loop(即for loopor 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来强制用户输入字符yn. 此外,如果您想做得好,您可以添加异常处理。


推荐阅读