如何在另一个函数中调用一个函数?

2024-04-28 20:40:48 发布

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

我是新来的社区和一般的编码,选择python作为我的第一语言,并完成了一些在线课程。你知道吗

我试图在一个项目上工作,以实践和不断改进,这是一个信用卡号码验证器,检查数字,前缀和校验和,但我陷入了一个非常基本的概念。你知道吗

我定义了一个函数作为用户输入enter de credit card number,然后我想调用另一个函数中的函数来验证前缀和校验和,但是我一直得到一个回溯,好像我的变量没有定义一样。你知道吗

# User inputs the cc number
def inp_cc():
    cc_number = input("Insert credit card number: ")
    return cc_number

# This will validate the prefix and lenght and print it if its correct, 
otherwise will show an error
# Code is not completed as I keep getting the traceback

def val_tc():
    inp_cc()
    if len(cc_number) == 13 or len(cc_number) == 16:
        cc_brand = "Visa"
        print("Credit card number: %s" % cc_number,"Credit card brand: %s" % cc_brand)
    else:
        quit()

# Here I call the val_tc() function that should also call the inp_cc()

val_tc()

这是我得到的错误:

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    val_tc()
  File "main.py", line 11, in val_tc
    if len(cc_number) == 13 or len(cc_number) == 16:
NameError: name 'cc_number' is not defined

提前谢谢!你知道吗


Tags: the函数numberlenif定义valcall
2条回答

出现错误的原因是您没有实际将inp_cc函数的返回值赋给任何对象。以下是固定版本:

def inp_cc():
    cc_number = input("Insert credit card number: ")
    return cc_number



def val_tc():
    cc_number = inp_cc()  # FIXED
    if len(cc_number) == 13 or len(cc_number) == 16:
        cc_brand = "Visa"
        print("Credit card number: %s" % cc_number,"Credit card brand: %s" % cc_brand)
    else:
        quit()


val_tc()

你必须打inp\U cc,而不是int\U cc。 我想只是打错了。你知道吗

相关问题 更多 >