如何在Python中获得用户输入?

2024-04-25 06:38:39 发布

您现在位置: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放入all,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)

Tags: yougetifthatnotdoelseprint
3条回答

正如一些人所说,你必须使用inputloop(即for loopwhile 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)

Outputs: It is an example

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

NB:您可以添加循环while,强制用户输入字符yn。此外,如果您想做好工作,还可以添加异常处理。你知道吗

listQue=["Do you want strawberry ice cream?","Do you want chocolate ice cream?","Do 
you want mint ice cream?","Do you want vanilla ice cream?"]

flag=False
for que in listQue:
    ans=input(que)
    if(ans=='Y'):
        res=que.split()
        print("Here is your"," ".join(res[3:6]).rstrip('?'))
        flag=True
   else:
        pass


if(flag==False):
    print("Ohhh sorry you didn't choose anything")

在这个问题中,只考虑你想要什么,你将使用函数input。使用方法如下:

strawberryIceCream=input('Do you want strawberry ice cream? (y/n)')

以此类推,还有其他的选择。记住将每个选项存储在不同的变量中,或者最好是存储在集合或元组中。你知道吗

Further info on ^{}

然而,对你的问题的评论是准确的,切中要害的。这就是为什么我提到这个答案只会回答你的问题。不多不少。你知道吗

相关问题 更多 >