【问题标题】:Python def function assignment issue [closed]Python def函数分配问题[关闭]
【发布时间】:2022-01-07 01:39:56
【问题描述】:

我被分配了一个任务,我应该通过给出函数的编号来编写执行不同类型计算/函数的程序(必须使用带有 def 的函数)。并严重坚持下去。

1.

choice = int(input("Chosen function: "))
while choice != 0
if choice == 1:
    print("Sum of the list: ", summ_list(lista))
if choice == 2:
    print("Is the chosen number inside?: ", decide_if_in(lista, s))
.......
else:
    print("The program closes.")

如果用户按下 0,程序应该终止。但是尽我最大的努力,如果我做一段时间或 for 循环,它将陷入无限循环,因此我无法解决它。

2.

def decide_if_in():
    s = int(input("Which number do you think is in the list?: "))
    for d in s:
        if d == s:
             print("It is in the list")
        else:
            print("It is not in the list..")

在这里它可以在没有 def 标签的情况下工作,但我不能让它与它一起工作。重点是我给它一个数字,然后它会检查列表中的列表?

【问题讨论】:

  • 请问你能更好地格式化这个问题吗?从代码中不是很清楚发生了什么
  • 从 Python 和编程的基本教程开始。您尝试解决的问题将成为最初一到两百万小时学习的一部分。
  • 你的python代码缩进是否正确?在 python 中,空格很重要,并从代码中定义范围块。

标签: python function loops


【解决方案1】:

在您的示例 1 中,您没有在循环内更新 choice。这就是为什么它陷入无限循环的原因。你可以写成,

choice = int(input("Chosen function: "))
while choice != 0:
    if choice == 1:
        print("Sum of the list: ", summ_list(lista))
        choice = int(input("Chosen function: "))
    if choice == 2:
        print("Is the chosen number inside?: ", decide_if_in(lista, s))
        choice = int(input("Chosen function: "))
.......
    else:
        print("The program closes.")

一点点python中的小技巧,你可以直接将函数放入列表或字典中。所以,你可以做类似的事情

def func1(arg1):
    #do something here
def func2(arg1):
    #do something else

func_dic = {1:func1, 2:func2}
choice = int(input("Whatever: "))
while choice != 0:
    print("Whatever: ", func_dic[choice](list))
                        ^^^^^^^^^^^^^^^^ -> function of choice here
print("close dialogue")

对于您的第二个代码,您的定义是错误的。 你可以简单地做到这一点

def func_name(lista):
    s = int(input("Whatev: "))
    if s in lista:
        return "It's in"
    else:
        return "It's not in"

【讨论】:

    【解决方案2】:
    choice = int(input("Chosen function: "))
    while 1: # Loops infinitely, using exit() to stop the script
        if choice == 1:
            print("Sum of the list: ", summ_list(lista))
        elif choice == 2: # Better to use elif
            print("Is the chosen number inside?: ", decide_if_in(lista))
        .....
        elif choice == 0:
            print("The program closes.")
            exit() # Stops the python script
        choice = int(input("Chosen function: ")) # Asking for input again
    
    def decide_if_in(lista): # Taking the list as an arg
        s = int(input("Which number do you think is in the list?: "))
        if s in list:
            print("It is in the list")
        else:
            print("It is not in the list..")
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2012-05-07
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      相关资源
      最近更新 更多