使用变量定义函数?

2 投票
6 回答
3432 浏览
提问于 2025-04-17 05:04

我正在尝试定义一个函数,这个函数会包含一个变量 n,其中 n 是一个数字字符串,比如 "3884892993"。这个函数的定义是从 is_true(n) 开始的。不过,如果 n 是一个字符串,应该还是用 is_true(n) 吗?然后在定义了字符串后,我可以用一个示例字符串来测试这个函数,比如 n = "3884892993"。但是当我使用 is_true(n) 时却出现了语法错误。我只是想知道如何用一个示例字符串来测试这个函数。

我整个函数的定义在这里展示:http://oi44.tinypic.com/282i3qo.jpg,但请记住我还是个新手,所以可能会有很多错误,如果有专家能帮我一下,我会非常感激 :)

def is_valid("n"): #n is the number to be checked.
    number = 
    [int(y) for y in A] #converts the string into a list of useable digits.
    altern1 = integer[-2::-2] #sets altern1 as one set of alternating digits.
    double = [x*2 for x in altern1] #doubles each element of the list altern1.
    sum1 = sum(double) # adds together all the doubled items of the list.
    altern2 = integer[-1::-2] #sets altern2 as the other set of alternating digits.
    return sum2 = sum(altern2)#sums the other set of alternating digits.
    sumtotal = sum1 + sum2 #works out the total sum to be worked with.
    for mod = sumtotal % 10: #works out remainder when sumtotal is divided by 10
        if mod == 0 : #if remainder is zero sumtotal is a multiple of 10
            print 'True' #sumtotal is a multiple of 10 therefore n is a credit card number
        else:
            print 'False' #sumtotal is NOT a multiple of 10 therefore not a valid credit card number

这里是实际的问题:

验证一个数字的算法如下: (a) 从倒数第二位数字开始,向前到第一位数字,每隔一个数字就把它乘以2。 (b) 把乘以2后的数字相加,像13这样的数字要分开相加,比如1+3,然后把这个结果加上没有乘以2的数字的总和。 (c) 如果这个总和能被10整除,那么这个数字就是一个有效的信用卡号码。

编写并测试一个函数 is_valid(),这个函数接受一个信用卡号码的字符串作为参数(例如 is_valid("49927398716")),并根据这个号码是否是有效的信用卡号码返回 True 或 False。

6 个回答

1

来自于维基百科关于Luhn算法的文章

def is_luhn_valid(cc):
    num = map(int, str(cc))
    return sum(num[::-2] + [sum(divmod(d * 2, 10)) for d in num[-2::-2]]) % 10 == 0
4

引号只用来表示字符串字面量,也就是说,你不会用引号把变量或参数名包起来来表示它是一个字符串。函数的定义看起来会是这样的:

def is_true(n):

然后在函数的主体部分,你可以用 n 来引用调用者传入的值。

如果你想用一个具体的值来调用这个函数,你可以这样做:

is_true("3884892993")

顺便提个建议:给你的函数和变量起个更能说明问题的名字会更好。例如,你的函数可以叫 is_valid_card_number,这样更容易理解。

1

我不太确定你的问题是什么,但如果你想:

  • 正确地定义一个函数:
    • 要注意缩进(这是Python的要求!),
    • 可以在这里查看函数定义的例子,
  • 把一个字符串变量转换成整数,你可以这样做:

    new_var = int(old_var)
    

    一般来说,请注意数据类型,因为在某些动态类型的语言中,字符串会自动转换成数字,但在Python中,你需要明确地进行转换。

  • 根据变量的名字读取它的值:

    my_var = vars().get('variable_name')
    

    (这里的 variable_name 是变量的名字,你可以在 vars 后面加上括号来提供上下文 - 具体可以查看 help(vars))

以上内容有没有解决你的问题?

编辑(根据澄清):

这个应该能解决你的问题:

def is_true(my_variable):
    # Here the variable named "my_variable" is accessible

如果你想对传入的变量进行“就地”操作,我有个坏消息:在Python中,字符串和整数是不可变的,所以你不能简单地改变它们 - 你应该把它们作为函数的返回值(有至少两种变通方法,但如果你是Python新手,我不推荐这些方法)。

编辑(关于代码风格):

你可能应该阅读PEP 8,了解Python脚本的编码标准 - 这个标准在Python社区中被广泛使用,你应该遵循它(到某个时候你会感激它的)。

撰写回答