如何根据用户的选择更改数值?

huangapple go评论83阅读模式
英文:

How can I change a value based on a users selection?

问题

I can help you with the translation:

我是Python的初学者,我正在挑战自己制作一个根据用户提供的值计算形状面积的计算器。我卡在了如何根据用户的选择更改测量单位上。例如,如果用户选择了平方英尺作为主要测量单位,然后想要将其转换为平方米,我该如何将值从平方英尺更改为平方米,反之亦然?

我只能完成了从米到英尺的转换,因为制作所有可能选择的代码将耗费大量时间。我想知道是否有更简单的方法,而不是为每种可能的选择制作代码?
这是我尝试过的内容,其中'Choice2'是我卡住的地方:

ChoiceI = int(input(Fore.RESET + "\n选择测量单位:\n英尺 (1),米 (2),英寸 (3) "))
米 = "平方米"
英尺 = "平方英尺"
英寸 = "英寸"
if ChoiceI == 1:
宽度 = int(input("\n矩形的宽度是多少? "))
if 宽度 >= 1:
长度 = int(input("\n矩形的长度是多少? "))
if 长度 >= 1:
面积 = 宽度 * 长度
print("矩形的面积是", round(面积), "英寸")
if ChoiceI == 2:
宽度 = int(input("\n矩形的宽度是多少? "))
if 宽度 >= 1:
长度 = int(input("\n矩形的长度是多少? "))
if 长度 >= 1:
面积 = 宽度 * 长度
print("矩形的面积是", round(面积), "平方米")
if ChoiceI == 3:
宽度 = int(input("\n矩形的宽度是多少? "))
if 宽度 >= 1:
长度 = int(input("\n矩形的长度是多少? "))
if 长度 >= 1:
面积 = 宽度 * 长度
print("矩形的面积是", round(面积), "平方英尺")
Choice2 = input("\n是否要转换单位? (y/n) ")
if Choice2 == 'y':
转换 = int(input("\n选择测量单位:\n英尺 (1),米 (2),英寸 (3)"))
if 转换 == 1:
print("矩形的面积是", round(面积), "英尺")
elif Choice2 == 'n':
print("矩形的面积是", round(面积), 米)


对于'Choice2',如何使其根据用户选择更改打印的内容呢?
英文:

I'm a beginner to Python and I'm challenging myself to make a calculator that calculates the area of shapes based on values given by the user. I'm stuck on how I can make it change the measurement based on the users selection. For example, if a user picked square feet as their main measurement and then wanted to convert it to square meters, how would I be able to change the value from square feet to square meters and vice versa?

I've only accomplished meters to feet as doing all combinations would be time consuming. I was wondering if there is an easier way to do it rather than making code for every combination of a possible choice?
Here's what I've tried, where 'Choice2' is where I am stuck;

ChoiceI = int(input(Fore.RESET + "\nPick the measurement:\nFeet (1), Meters (2), Inches (3) "))
 Meters = "m2"
 Feet = "ft2"
 Inches = "inches"
 if ChoiceI == 1:
            Width = int(input("\nWhat is the width of the rectangle?  "))
            if Width >= 1:
                Length = int(input("\nWhat is the length of the rectangle?  "))
                if Length >= 1:
                            Area = Width * Length
                            print("The area of the rectangle is", round(Area), "inch")
 if ChoiceI == 2:
            Width = int(input("\nWhat is the width of the rectangle?  "))
            if Width >= 1:
                Length = int(input("\nWhat is the length of the rectangle?  "))
                if Length >= 1:
                            Area = Width * Length
                            print("The area of the rectangle is", round(Area), "m2")
 if ChoiceI == 3:
            Width = int(input("\nWhat is the width of the rectangle?  "))
            if Width >= 1:
                 Length = int(input("\nWhat is the length of the rectangle?  "))
                 if Length >= 1:
                            Area = Width * Length
                            print("The area of the rectangle is", round(Area), "ft2")
 Choice2 = input("\nDo you want to convert the measurement? (y/n) ")
 if Choice2 == 'y':
            Convert = int(input("\nChoose the measurement:\nFeet (1), Metres (2), Inches (3)"))
            if Convert == 1:
                         print("The area of the rectangle is", round(Area), "feet")
            elif Choice2 == 'n':
                         print("The area of the rectangle is", round(Area), Meters)

For 'Choice2'; How can I make it change what is prints based on what the user chose?

答案1

得分: 2

唯一变化的是测量单位(UOM)。无论测量单位如何,高度和宽度的值都是相同的。

您可以按如下方式消除大部分重复的代码:

UMAP = {
    '1': ('英寸', 'in'),
    '2': ('英尺', 'ft'),
    '3': ('米', 'm')
}

while (m := input('选择测量单位 1) 英寸, 2) 英尺, 3) 米, 9) 退出: ')) != '9':
    if (unit := UMAP.get(m)):
        try:
            w = float(input(f'输入宽度({unit[0]}): '))
            h = float(input(f'输入高度({unit[0]}): '))
            print(f'矩形的面积是 {w*h:.2f}{unit[1]}²')
        except ValueError:
            print('无效的高度/宽度')
    else:
        print('无效的选项')

示例:

选择测量单位 1) 英寸, 2) 英尺, 3) 米, 9) 退出: 2
输入宽度(英尺): 4
输入高度(英尺): 3.5
矩形的面积是 14.00ft²
选择测量单位 1) 英寸, 2) 英尺, 3) 米, 9) 退出: 9
英文:

The only thing that changes is the unit of measurement (UOM). The height and width values are the same regardless of the UOM.

You can eliminate most of your repetitive code as follows:

UMAP = {
    '1': ('inches', 'in'),
    '2': ('feet', 'ft'),
    '3': ('metres', 'm')
}

while (m := input('Select unit of measurement 1) inches, 2) feet, 3) metres, 9) exit: ')) != '9':
    if (unit := UMAP.get(m)):
        try:
            w = float(input(f'Enter width in {unit[0]}: '))
            h = float(input(f'Enter height in {unit[0]}: '))
            print(f'Area of rectangle is {w*h:.2f}{unit[1]}\u00B2')
        except ValueError:
            print('Invalid height/width')
    else:
        print('Invalid option')

Example:

Select unit of measurement 1) inches, 2) feet, 3) metres, 9) exit: 2
Enter width in feet: 4
Enter height in feet: 3.5
Area of rectangle is 14.00ft²
Select unit of measurement 1) inches, 2) feet, 3) metres, 9) exit: 9

答案2

得分: 1

你可以创建一个类似这样的字典:

dict = {'measurement unit1': 'measurement unit 1的换算公式',
        'measurement unit2': 'measurement unit 2的换算公式'
}

示例:

measure_dict = {'meters - inches': 39.37 * <meter units>,
                'inches - meters': 0.0254 * <inches units>
}

此外,我已经整理了你的代码并实现了该字典以查看其工作情况。你可以对上述的每个其他测量单位以及任何其他你想要实现的测量单位做同样的操作。

ChoiceI = int(input("\n选择测量单位:\n英尺 (1), 米 (2), 英寸 (3) "))
measure = {
    1: 39.37 * ChoiceI,
    2: 0.0254 * ChoiceI,
    3: 0.3048 * ChoiceI,
}
while 0 < ChoiceI <= 3:
    Width = int(input("\n矩形的宽度是多少? "))
    if ChoiceI == 1:
        if Width >= 1:
            Length = int(input("\n矩形的长度是多少? "))
            if Length >= 1:
                Area = Width * Length
                print(f"矩形的面积为 {round(Area)} 英寸")
    elif ChoiceI == 2:
        if Width >= 1:
            Length = int(input("\n矩形的长度是多少? "))
            if Length >= 1:
                Area = Width * Length
                print(f"矩形的面积为 {round(Area)} 平方米")
    elif Width >= 1:
        Length = int(input("\n矩形的长度是多少? "))
        if Length >= 1:
            Area = Width * Length
            print(f"矩形的面积为 {round(Area)} 平方英尺")
    Choice2 = input("\n是否要转换测量单位? (y/n) ")
    if Choice2 == "y":
        ChoiceI
        print(f"矩形的面积为 { measure[ChoiceI]} 英尺")
    elif Choice2 == "n":
        print(f"矩形的面积为 {round(Area)} 米")
    else:
        print("无效选择!")
print("无效选择!")

为了避免多次使用if/elif语句,如果你使用Python 3.11,你可以使用match case语句。

这段代码未经测试,但应该能完成任务。

英文:

You could make a dictionary like this:

dict={&#39;measurement unit1&#39;:&#39;measurement unit 1&#39;s conversion formula&#39;,
      &#39;measurement unit2&#39;:&#39;measurement unit 2&#39;s conversion formula&#39;
}

Example:

measure_dict={&#39;meters - inches&#39;:39.37*&lt;meter units&gt;
              &#39;inches - meters&#39;: 0.0254 *&lt;inches units&gt;
              }

Further, i've cleaned up your code and implemented the dict to see it working. You could do the same with every other measurement above and any other measures you wish to implement.

ChoiceI = int(input(&quot;\nPick the measurement:\nFeet (1), Meters (2), Inches (3) &quot;))
measure = {
    1: 39.37 * ChoiceI,
    2: 0.0254 * ChoiceI,
    3: 0.3048 * ChoiceI,
}
while 0 &lt; ChoiceI &lt;= 3:
    Width = int(input(&quot;\nWhat is the width of the rectangle?  &quot;))
    if ChoiceI == 1:
        if Width &gt;= 1:
            Length = int(input(&quot;\nWhat is the length of the rectangle?  &quot;))
            if Length &gt;= 1:
                Area = Width * Length
                print(f&quot;The area of the rectangle is {round(Area)} inch&quot;)
    elif ChoiceI == 2:
        if Width &gt;= 1:
            Length = int(input(&quot;\nWhat is the length of the rectangle?  &quot;))
            if Length &gt;= 1:
                Area = Width * Length
                print(f&quot;The area of the rectangle is {round(Area)} m2&quot;)
    elif Width &gt;= 1:
        Length = int(input(&quot;\nWhat is the length of the rectangle?  &quot;))
        if Length &gt;= 1:
            Area = Width * Length
            print(f&quot;The area of the rectangle is {round(Area)} ft2&quot;)
    Choice2 = input(&quot;\nDo you want to convert the measurement? (y/n) &quot;)
    if Choice2 == &quot;y&quot;:
        ChoiceI
        print(f&quot;The area of the rectangle is { measure[ChoiceI]} feet&quot;)
    elif Choice2 == &quot;n&quot;:
        print(f&quot;The area of the rectangle is {round(Area)} meters&quot;)
    else:
        print(&quot;Invalid choice!&quot;)
print(&quot;Invalid choice!&quot;)

To avoid multiple if/elifs, if you have python 3.11, you could use match case statement.

The code is untested, but should get the job done

huangapple
  • 本文由 发表于 2023年7月12日 20:57:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76670837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定