使用变量定义函数?

2024-10-01 15:35:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图定义一个函数,它将包含一个变量n,其中n是一个数字串,例如"3884892993",函数的定义从is_true(n)开始,但是如果n是一个字符串,它应该是is_true(n),然后一旦这个字符串被定义,我就可以用一个示例字符串如n = "3884892993"来测试这个函数。但是,当我使用is_true(n)时,我得到了一个语法错误。我只是想知道如何用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) 从倒数第二个数字开始,向第一个数字移动,每两个数字交替。 (b) 将两位数相加,将13视为1+3,以此类推,并将结果加到无疑问的和上 数字 (c) 如果总数可以被10整除,则该号码是有效的信用卡号。在

编写并测试函数is_valid(),该函数将信用卡号码作为参数作为字符串 (eg is valid(“49927398716”))并根据数字是否为a返回True或False 有效信用卡号。在


Tags: ofthe函数字符串truenumberfor定义
3条回答

引号只用于字符串文本,您不会将变量或参数名称括在引号中以指示它将是字符串。函数定义如下:

def is_true(n):

然后在函数体中使用n来引用调用方传入的值。在

要对特定值调用函数,请执行以下操作:

^{pr2}$

附加建议:为函数和变量考虑更多的解释性名称。例如,您的函数似乎可以合理地称为is_valid_card_number。在

我不知道你的问题是什么,但如果你想:

  • 正确定义函数:
    • 注意缩进(这是Python所必需的!)你说
    • 有关函数定义的示例,请参见here
  • 将字符串变量转换为整数,可以执行以下操作:

    new_var = int(old_var)
    

    一般来说,请注意类型,因为它与其他一些动态类型语言不同,字符串也不会动态地转换为数字—您应该显式地进行转换。

  • 根据变量的名称读取变量的值:

    ^{pr2}$

    (其中variable_name是变量的名称,您可以选择在vars后面的括号内给出上下文-有关详细信息,请参见help(vars)

以上这些都解决了你的问题吗?在

编辑(基于澄清):

这样可以解决您的问题:

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

如果您想对传递的变量执行“就地”操作,我有个坏消息:字符串和整数在Python中是不可变的,因此您不能简单地更改它们-您可能应该作为函数的结果返回它们(至少有两种解决方法,但如果您是Python的新手,我不推荐它们)。在

编辑(用于正确的代码样式):

您可能应该阅读PEP 8来熟悉Python脚本的编码标准——这是Python社区中常用的,您应该遵循这个标准(在某个时候您应该很欣赏它)。在

Wikipedia article on the Luhn algorithm

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

相关问题 更多 >

    热门问题