首页 > 解决方案 > 将较少的参数传递给函数然后在 Python 中定义

问题描述

如果我有一个具有多个功能的功能,比如说计算面积或添加三个数字。用户选择 1 用于计算面积,2 用于通过输入添加数字

def func_calculate(numberOne, numberTwo, numberThree, userChoise):
    if userChoise == "1":
        calculate Area
        do something
    if userChoise == "2":
        calculate addition
        do something

userChoise 是用户的输入

如果用户想计算面积,函数只有两个参数而不是三个,如果用户想进行加法。

那么,最后的问题是......处理它的最合适的方法是什么?

当我调用该函数时,当用户想要计算面积时,我应该将 numberThree 变量设置为零还是什么,或者它是一种更“正确”的方式吗?

if userChoie == "1":    
    inputNumberOne = input(...
    inputNumberTwo = input(...
    inputNumberThree == 0 
    func_calculate(inputNumberOne, inputNumberTwo, inputNumberThree, userChoise)

标签: pythonfunctionargs

解决方案


如果您不想执行多个操作,那么最好为不同的操作提供不同的功能

choice = input("what user want's to do")

if choice == 1:
     add()
elif choice == 2: 
     multiply()

而不是从用户那里获取参数进行该操作,例如

def add():
      num1 = input("num1")
      num2 = input("num2")
      num3 = input("num3")
      print(num1 + num2 + num3)

和类似的其他操作

但如果你不想拥有多个功能,你可以做

def func(choice):
    #choice is the integer which user opted
    if choice == 1:
          num1 = input("num1")
          num2 = input("num2")
          num3 = input("num3")
          print(num1 + num2 + num3)
    elif choice == 2:
          .........

推荐阅读