简体   繁体   English

创建 python function 以返回值

[英]creating python function to return value

I have written a function called "adjust", so what it needs to do is to take user input from 0 to 9 and to retune either 0,5 or 10.我写了一个名为“adjust”的 function,所以它需要做的是将用户输入从 0 到 9 并重新调整 0,5 或 10。

My function has come across a syntax error when it runs until "elif", But I can't figure out what I did wrong.我的 function 在运行到“elif”时遇到了语法错误,但我不知道我做错了什么。 This is what I have now ( I try to use control K to post the code but if keep giving me an error)这就是我现在所拥有的(我尝试使用 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


The example output would be:示例 output 将是:

input 1, output 0 input 4, output 5 input 8, output 10输入 1,output 0 输入 4,output 5 输入 8,output 10

The reason for that is indentation.原因是缩进。 In Python, indentation is used to indicate the scope of the operation.在 Python 中,使用缩进表示操作的 scope。 In your case, your elif is inside the if and thus raises a Syntax error, as there was no if before it in the same scope.在您的情况下,您的elifif内,因此会引发语法错误,因为在同一 scope 之前没有if

Simply fixing your indentation will solve the issue.只需修复缩进即可解决问题。 However, your code could also be written a bit cleaner (and I am assuming you want to return the modified versions, not the originals), so my version would be:但是,您的代码也可以写得更简洁(我假设您要返回修改后的版本,而不是原始版本),所以我的版本是:

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

If you finish writing your script, you will be able to provide an iterable of cents you want to adjust to the function, which will return you the adjusted ones.如果您完成脚本的编写,您将能够提供您想要调整到 function 的可迭代的cents ,这将返回您调整后的美分。 No need to call it iteratively.无需反复调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM