Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 十个绿色瓶子计划_Python - Fatal编程技术网

Python 十个绿色瓶子计划

Python 十个绿色瓶子计划,python,Python,我正在用Python编写一个程序,根据用户输入的瓶子数量打印十个绿色瓶子程序。这就是我目前所拥有的 x=input("How many bottles to start with?\n") while x > 0: if(x==1):

我正在用Python编写一个程序,根据用户输入的瓶子数量打印十个绿色瓶子程序。这就是我目前所拥有的

x=input("How many bottles to start with?\n")                                                    
while x > 0:                                                    
  if(x==1):                                                 
    print (str(x) + " "+"green bottle, hanging on the wall")                                                    
    print (str(x) + " "+ "green bottle hanging on the wall")                                                    
    print ("and if one green bottle, should accidentally falls")                                                    
    x = x - 1                                                   
    print("there'd be no green bottle hanging on the wall")                                                 
    print("\n")                                                 
  elif(x==2):                                                   
    print (str(x) + " "+"green bottles, hanging on the wall")                                                   
    print (str(x) + " "+ "green bottles hanging on the wall")                                                   
    print ("and if one green bottle should accidentally fall")                                                  
    x = x - 1                                                   
    print ("there'd be "  + str (x)  + " green bottle, hanging on the wall")                                                    
    print("\n")                                                 
  else:                                                 
    print (str(x) + " "+"green bottles, hanging on the wall")                                                   
    print (str(x) + " "+ "green bottles hanging on the wall")                                                   
    print ("and if one green bottle should accidentally falls")                                                 
    x = x - 1                                                   
    print ("there'd be "  + str (x)  + " green bottles, hanging on the wall")                                                   
    print("\n")                                                 
  

问题1:我还需要将“1”改为“1”。我正在考虑写一个函数,因为我只需要将1改为10。请告诉我如何做到这一点。

要将数字转换为各自的英语单词,建议使用字典:

x = int(input("How many bottles to start with?\n")) # Convert the input to an int
int_to_str = {
1: "one",
2: "two",
...
10: "ten"
}
print ("there'd be "  + int_to_str[x] + " green bottles, hanging on the wall")
看看如何通过使用小功能消除冗余。

问题1 这可以简单地用if语句完成。因为你提到你只需要1到10,所以声明应该是这样的

x=int(输入(“开始时有多少瓶?”)
如果(x>10或x<1):
打印(f“不能以{x}瓶开始。请选择1到10之间的数字。”)
退出()
问题2 这可以用字典来完成

map\u to\u str={
0:“否”,
1:"一",,
二:"两个",,
三:"三",,
四:"四",,
五:"五",,
6:“六”,
七:"七",,
八:"八",,
9:“九”,
10:“十”
}
代码的另一个问题是大量代码被不必要地重复。首先,我将使用for循环。我还将编写一个函数,将瓶子数作为字符串返回

def瓶到def瓶(def瓶的数量):
返回f“{map_to_str[num_of_瓶子]}绿色瓶子“+”s*(num_of_瓶子!=1)
此函数将数字作为参数,并使用字典将其转换为字符串。它还检查瓶子数是否不等于1(False也可以解释为0,True解释为1)。如果瓶数不是1,则计算为
“s”*1
,即
“s”
,否则计算为
“s”*0
,即空字符串

主循环将如下所示

范围(x,0,-1)内的i的
:
印刷品(悬挂在墙上的“{瓶子_至_str(i)}”)
印刷品(悬挂在墙上的“{瓶子_至_str(i)}”)
打印(f“如果一个绿色瓶子意外掉落,”)
打印(f“将有{瓶子{u到{u str(i-1)}挂在墙上\n”)

为了处理这个问题,我会编写一个字典,用整数作为键和写数的值

a_python_dictionary = {'key_some_name1' : 'value_some_value1',
                       'key_some_name2' : 'value_some_value2'}

Example:
number_dict = {0:'zero', 1:'one', 2:'two',
                     ...etc...,
               8:'eight', 9:'nine', 10:'ten'}
接下来,用f-strings(一种字符串格式)编写将使用字典的函数

因此,在这个函数中发生的是:

"""
Line 1.
    def greenbottles(info=number_dict):
        defines a function called 'greenbottles' and presets a keyword argument of
        'info' equal to premade dictionary variable called 'number_dict'
Line 2.
    user_input = input("Please enter a whole number.\n")
        makes a variable inside the function called 'user_input' and prompts the
        user to enter a number. Now, this make the variable a defaulted string.
Line 3.
    try:
        this command will attempt to run thru the next lines of code indented under
        'try:'. If it returns an error, it will pass to the exception line 'except:'
Line 4:
    user_input = int(user_input)
        takes the 'user_input' variable and converts the data type to 'int' an integer
Line 5:
    while user_input > 0:
        starts a 'while loop', meaning while condition is true, do this.. the
        conditional is 'user_input' greater than '0'?
Line 6:
    if user_input >= 2:
        conditional inside the while, is 'user_input' greater than or equal to '2'
Line 7:
    print(f"{(info[user_input]).capitalize()} blah plural")
        if lines 5 & 6 result in True, print to the screen, this f-string.
        the f-string will format logic result inside '{}' to a string,
        with the rest of the string.
        Python uses a first in, first out approach.
          if the variable 'user_input' equals integer 5 
          ...a step by step break down of the line...
            print(f"{(info[user_input]).capitalize()} plural sentence")
                    ~turns into~
            print(f"{(info[5]).capitalize()} your plural sentence")
                    ~turns into~
            print(f"{('five').capitalize()} your plural sentence")
                    ~turns into~
            print(f"{'Five'} your plural sentence")
                    ~turns into~
            print("Five your plural sentence")
Line 8:
    user_input -= 1
        take value of variable and make it equal to 1 less than original value
Line 9:
    else:
        when Line 6 'if' conditional is not true, do this
Line 10:
    print(f"{(info[user_input]).capitalize()} your singular sentence")
        if Line 5 results in True, but Line 6 results in False 
        print to the screen, this f-string.
        the f-string will format logic result inside '{}' to a string,
        with the rest of the string.
        Python uses a first in, first out approach.
          the variable 'user_input' will only equal integer 1 
          ...a step by step break down of the line...
            print(f"{(info[user_input]).capitalize()} your singular sentence")
                    ~turns into~
            print(f"{(info[1]).capitalize()} your singular sentence")
                    ~turns into~
            print(f"{('one').capitalize()} your singular sentence")
                    ~turns into~
            print(f"{'One'} your singular sentence")
                    ~turns into~
            print("One your singular sentence")
Line 11:
    user_input -= 1
        take value of variable and make it equal to 1 less than original value
Line 12:
    print("There are no more bottles.")
        when Line 5 returns false, it ends while loop and print to the screen,
        'There are no more bottles.'
Line 13:
    except:
        if for any reason Lines 4 thru 12 return a error, do this...
        otherwise skip
Line 14:
    print("You did not enter a number.")
        most likely cause, is user didn't enter a number, print that message to
        screen.
"""
# Bonus
# using triple quotation marks, single or double: '''some text''' """some text"""
# are great ways of making multi-line strings, you can even use formatting
f'''some text {1+1} 
some more text'''
f"""some text {2+1} 
some more text {1+1}"""
# so, instead of using multi 'print' statements, use one...
print(f"""Here's a mulit-line
{'f-string'.capitalize()} with
some formating {'of'.upper()}
{'things '*3},
as a {'EXAMPLE'.lower()}.
""")

我希望这有助于您以及您对python的理解D

建议您如何编写函数。只需补充说明,python输入默认为字符串,当然可能需要使用int(x)索引。我习惯将数字输入转换为浮点或int,所以我忽略了这一点。谢谢
def greenbottles(info=number_dict):
    user_input = input("Please enter a whole number.\n")
    try:
        user_input = int(user_input)
        while user_input > 0:
            if user_input >= 2:
                print(f"{(info[user_input]).capitalize()} your plural sentence")
                user_input -= 1
            else:
                print(f"{(info[user_input]).capitalize()} your singular sentence")
                user_input -= 1
        print("There are no more bottles.")
    except:
        print("You did not enter a number.")
"""
Line 1.
    def greenbottles(info=number_dict):
        defines a function called 'greenbottles' and presets a keyword argument of
        'info' equal to premade dictionary variable called 'number_dict'
Line 2.
    user_input = input("Please enter a whole number.\n")
        makes a variable inside the function called 'user_input' and prompts the
        user to enter a number. Now, this make the variable a defaulted string.
Line 3.
    try:
        this command will attempt to run thru the next lines of code indented under
        'try:'. If it returns an error, it will pass to the exception line 'except:'
Line 4:
    user_input = int(user_input)
        takes the 'user_input' variable and converts the data type to 'int' an integer
Line 5:
    while user_input > 0:
        starts a 'while loop', meaning while condition is true, do this.. the
        conditional is 'user_input' greater than '0'?
Line 6:
    if user_input >= 2:
        conditional inside the while, is 'user_input' greater than or equal to '2'
Line 7:
    print(f"{(info[user_input]).capitalize()} blah plural")
        if lines 5 & 6 result in True, print to the screen, this f-string.
        the f-string will format logic result inside '{}' to a string,
        with the rest of the string.
        Python uses a first in, first out approach.
          if the variable 'user_input' equals integer 5 
          ...a step by step break down of the line...
            print(f"{(info[user_input]).capitalize()} plural sentence")
                    ~turns into~
            print(f"{(info[5]).capitalize()} your plural sentence")
                    ~turns into~
            print(f"{('five').capitalize()} your plural sentence")
                    ~turns into~
            print(f"{'Five'} your plural sentence")
                    ~turns into~
            print("Five your plural sentence")
Line 8:
    user_input -= 1
        take value of variable and make it equal to 1 less than original value
Line 9:
    else:
        when Line 6 'if' conditional is not true, do this
Line 10:
    print(f"{(info[user_input]).capitalize()} your singular sentence")
        if Line 5 results in True, but Line 6 results in False 
        print to the screen, this f-string.
        the f-string will format logic result inside '{}' to a string,
        with the rest of the string.
        Python uses a first in, first out approach.
          the variable 'user_input' will only equal integer 1 
          ...a step by step break down of the line...
            print(f"{(info[user_input]).capitalize()} your singular sentence")
                    ~turns into~
            print(f"{(info[1]).capitalize()} your singular sentence")
                    ~turns into~
            print(f"{('one').capitalize()} your singular sentence")
                    ~turns into~
            print(f"{'One'} your singular sentence")
                    ~turns into~
            print("One your singular sentence")
Line 11:
    user_input -= 1
        take value of variable and make it equal to 1 less than original value
Line 12:
    print("There are no more bottles.")
        when Line 5 returns false, it ends while loop and print to the screen,
        'There are no more bottles.'
Line 13:
    except:
        if for any reason Lines 4 thru 12 return a error, do this...
        otherwise skip
Line 14:
    print("You did not enter a number.")
        most likely cause, is user didn't enter a number, print that message to
        screen.
"""
# Bonus
# using triple quotation marks, single or double: '''some text''' """some text"""
# are great ways of making multi-line strings, you can even use formatting
f'''some text {1+1} 
some more text'''
f"""some text {2+1} 
some more text {1+1}"""
# so, instead of using multi 'print' statements, use one...
print(f"""Here's a mulit-line
{'f-string'.capitalize()} with
some formating {'of'.upper()}
{'things '*3},
as a {'EXAMPLE'.lower()}.
""")