gpt4 book ai didi

python - 我在让我的代码执行用户输入选择的函数时遇到问题

转载 作者:行者123 更新时间:2023-12-01 08:24:53 25 4
gpt4 key购买 nike

当运行我的程序并提供用户输入时,它只执行代码中的最后一个函数。我知道代码有什么问题,我正在用不同的参数重新定义相同的函数。但是,我不知道如何更改此设置,以便代码运行与用户输入匹配的函数。这是我为该程序编写的代码。

import math
from math import pi


def equation(Lift):
d = float(input("Input d value: "))
v = float(input("Input v value: "))
A = float(input("Input A value: "))
CL = float(input("Input CL value: "))

Lift = .5 * d * (v ** 2) * A * CL

a = ["Lift = ", Lift, "Newtons"]
for i in range (3):
print(a[i], end =" ")

def equation(VCylinder):
r = float(input("Input r value: "))
h = float(input("Input h value: "))

VCylinder = pi * (r ** 2) * h

a = ["Volume of Cylinder =", VCylinder, "m³ (meters³)"]
for i in range(3):
print(a[i], end =" ")

def equation(Exponentdx):
n = int(input("Input n value: "))

u = n
v = n - 1

a = ["dx =", u,"x","**", v, " "]
for i in range(5):
print(a[i], end =" ")


def Main():
print("Currently only compatible with base metric units (meters,
kilograms, etc.)")
Equation = input("Enter desired equation: ")
equation(Equation)

Main()

最佳答案

您需要为每个方程函数指定一个唯一的名称。这将允许您构建一个字典,将标识符映射到每个标识符。此外,您需要获取一个参数值,以便在调用所选函数之前传递该函数。

这是执行所有这些操作的示例:

import math
from math import pi


def equation1(Lift):
d = float(input("Input d value: "))
v = float(input("Input v value: "))
A = float(input("Input A value: "))
CL = float(input("Input CL value: "))

Lift = .5 * d * (v ** 2) * A * CL

a = ["Lift = ", Lift, "Newtons"]
for i in range (3):
print(a[i], end =" ")

def equation2(VCylinder):
r = float(input("Input r value: "))
h = float(input("Input h value: "))

VCylinder = pi * (r ** 2) * h

a = ["Volume of Cylinder =", VCylinder, "m³ (meters³)"]
for i in range(3):
print(a[i], end =" ")

def equation3(Exponentdx):
n = int(input("Input n value: "))

u = n
v = n - 1

a = ["dx =", u,"x","**", v, " "]
for i in range(5):
print(a[i], end =" ")

# Build dictionary mapping an equation identifer to equation functions.
equations = {
'1': equation1,
'2': equation2,
'3': equation3,
}

def Main():
print("Currently only compatible with base metric units (meters, kilograms, etc.)")
eq_id = input("Enter desired equation function (1, 2, or 3): ")
eq_arg = float(input("Enter value of argument to pass equation function: "))
equations[eq_id](eq_arg) # Call selected equation with argument.

Main()

关于python - 我在让我的代码执行用户输入选择的函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54332615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com