python - 将较少的参数传递给函数然后在 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)
解决方案
如果您不想执行多个操作,那么最好为不同的操作提供不同的功能
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:
.........
推荐阅读
- kubernetes - Metricbeat kubernetes 模块无法连接到 kubelet
- android - android数据绑定代码中的“@get:Bindable”是什么?
- wpf - 如何在 uwp 全屏窗口上制作我的 wpf 窗口
- ios - 我需要从联系人 JSON 响应中提取数据
- java - org.springframework.transaction.CannotCreateTransactionException:: command not found at org.springframework.orm.jpa.JpaTransactionManager.doBegin
- python - 熊猫与收藏:速度
- javascript - 如何使用 Koa nodejs 创建发布请求
- python - 如何在给定目录路径的末尾附加文件分隔符
- vue.js - Vue静态图像在Web服务器上部署时不起作用
- sql-server - 如何在 SQL Server 中选择 somefunction('1 * 2 / 2 + 3') = 4