首页 > 解决方案 > 创建python函数以返回值

问题描述

我编写了一个名为“adjust”的函数,所以它需要做的是将用户输入从 0 到 9 并重新调整 0,5 或 10。

我的函数在运行到“elif”之前遇到了语法错误,但我不知道我做错了什么。这就是我现在所拥有的(我尝试使用 control K 来发布代码,但如果一直给我一个错误)

cents = []
def adjust(cents):
    c=0
    for i in cents:
        x=cents.index(i)
        if(i==1 or i==2): 
            j=0
            elif(i==3 or i==4 or i==6 or i==7): 
                j=5
                elif(i ==8 or i==9):
                    j = 10
                    else:
                        j=i
                        return cents


n=int(input("Enter a number of cents between 0 and 9:))
#haven't figure out how to put the user input into my function


示例输出将是:

输入 1,输出 0 输入 4,输出 5 输入 8,输出 10

标签: pythonfunction

解决方案


原因是缩进。在 Python 中,缩进用于表示操作的范围。在您的情况下,您elif在内部if,因此会引发语法错误,因为if在同一范围内之前没有。

只需修复缩进即可解决问题。但是,您的代码也可以写得更简洁(我假设您要返回修改后的版本,而不是原始版本),所以我的版本是:

def adjust(cents):
    # Make copy of provided cents to modify
    adj_cents = list(cents)

    # Loop over all cents and round all values to nearest 5
    for i, x in enumerate(adj_cents):
        if x in (1, 2): 
            adj_cents[i] = 0
        elif x in (3, 4, 6, 7): 
            adj_cents[i] = 5
        elif x in (8, 9):
            adj_cents[i] = 10

    # Return adj_cents
    return(adj_cents)


n=int(input("Enter a number of cents between 0 and 9:))
#haven't figure out how to put the user input into my function

如果你完成了脚本的编写,你将能够提供一个cents你想要调整到函数的迭代,它将返回调整后的那些。无需反复调用它。


推荐阅读