【问题标题】:Trouble with codecademy exercise 2 issuecodecademy 练习 2 问题
【发布时间】:2022-08-12 21:54:59
【问题描述】:

大家好,我是编写 Python 程序的初学者,我正在努力从https://www.codecademy.com/resources/blog/python-code-challenges-for-beginners/ 编写这个特殊的练习

它的练习 2 对列表进行排序,这就是我到目前为止所拥有的,但它一直失败说订单未定义。我不确定在哪里定义函数以便触发 if 和 elif 语句,感谢任何帮助:


\"\"\"create a function with two parameters\"\"\"
def digits(num_list, order):
    if order == \'asc\':
        print(digits(num_list.sort()))
    elif order == \'desc\':
        print(digits(num_list.sort(reverse=True)))
    else:
        print(digits(num_list))


digit_list = [12, 15, 2, 7, 8, 25, 5, 45, 2]

digits(digit_list, \'asc\')
  • 看起来你正在造成某种无限循环。为什么在函数本身内部的 print 函数内部调用函数 digits() ?
  • 此外,您提供的代码失败并出现错误TypeError: digits() missing 1 required positional argument: \'order\',而不是您所说的错误。
  • 欢迎来到堆栈溢出!请使用tour 并阅读what\'s on-topic here、How to Ask 和question checklist。
  • 当您在函数内部调用数字时,未定义数字。因此,没有任何东西通过。从 print 函数中完全删除 digits() 并进行排序。
  • def digits(num_list, order): if order == \'asc\': print(num_list.sort()) elif order == \'desc\': print(num_list.sort(reverse=True)) else: print(num_list)

标签: python


【解决方案1】:

当您不希望它成为递归函数时,它似乎是递归的。 在第 4 行,看看print(digits(num_list.sort())) 是如何再次调用digits 函数的——没有定义订单参数?

这似乎是您所追求的代码。

"""create a function with two parameters"""
def digits(num_list, order):
    if order == 'asc':
        print(num_list.sort())
    elif order == 'desc':
        print(num_list.sort(reverse=True))
    else:
        print(num_list)


digit_list = [12, 15, 2, 7, 8, 25, 5, 45, 2]

digits(digit_list, 'asc')

请告诉我进展如何!欢迎来到 Python!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    相关资源
    最近更新 更多