0

我不确定为什么我不断收到“print func()”部分的错误,说它是无效的语法。我试图让切换器为它收到的每个值定义一个定义。代码正确运行循环,这只是我遇到问题的切换器部分。

import numpy as np

i = 0

# get the order the balloons need to be popped in
# just put the number
yellow = input ("When does yellow get popped ")
red = input ("When does red get popped ")
blue = input ("When does blue get popped ")
green = input("When does green get popped ")

print("")

# put them in an array for the switcher function

order = [yellow, red, blue, green]


# a while loop that will go through the switcher until
# all ballons have been popped
while i < 4:

    def yellow_turn():
        return "pop yellow next"
 
    def red_turn():
        return "pop red next"
 
    def blue_turn():
        return "pop blue next"
 
    def green_turn():
        return "pop green next"

    next_ball = order[i]
    print(next_ball)

    def ballon_order(next_ball):
        switcher = {
        0: yellow_turn,
        1: red_turn,
        2: blue_turn,
        3: green_turn,
        }
        func = switcher.get(next_ball, lambda: "Invalid input")
        print func()
    i += 1
4

1 回答 1

0

有很多原因,这段代码不起作用,因为如果这是 python 3 而 print 是一个函数而不是一个语句。

由于每个函数都被重新定义了很多次,所以这在计算中也很浪费。

函数定义可以放在 while 循环之外,将其改为 for 循环可能会很有用。

所以在这一切之后,代码看起来像这样 -

import numpy as np # This is not being used in the snippet but I will still include it
    
    
yellow = input ("When does yellow get popped ")
red = input ("When does red get popped ")
blue = input ("When does blue get popped ")
green = input("When does green get popped ")
    
#you also have to make these into integers to use them as keys later
yellow = int(yellow)
red = int(red)
blue = int(blue)
green = int(green)

def yellow_turn():
    return "pop yellow next"

def red_turn():
    return "pop red next"

def blue_turn():
    return "pop blue next"

def green_turn():
    return "pop green next"

switcher = {0:red_turn, 1:yellow_turn, 2:blue_turn, 3:green_turn}


#The loop will go like this
for i in (red,yellow,blue,green):
     print(switcher[i]())
   

但是这段代码非常冗余和浪费,最好是这样:

colors = ["red","yellow","blue","green"]

# list comprehensions

order = [int(input(f"when does {color} get popped : ")) for color in colors] # this creates a list of integers, in which the balloons will be popped the first will be red's number, second yellow's etc

for i in order:
    print(f"{colors[i]} will be popped next")

使用和输出如下:

PS C:\Users\anubi\OneDrive\Documents> python st.py
when does red get popped : 3
when does yellow get popped : 1
when does blue get popped : 2
when does green get popped : 0
green will be popped next
yellow will be popped next
blue will be popped next
red will be popped next
于 2021-04-07T06:01:14.313 回答