创建计算器,但操作顺序始终默认为加法

2024-06-16 10:27:59 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,为了开始编码,我决定创建一个简单的计算器,它从用户那里获取输入,将其转换为两个单独的列表,然后询问您要使用哪些操作,并计算公式。问题是,我会说我想使用减法,例如,我的两个数字是10和5,然后输出是15。这是我的密码:

    first_numbers = [] 
second_number = []
maxLengthList = 1
while len(first_numbers) < maxLengthList:
    item = input("Enter Your First Number To Be Calculated: ")
    first_numbers.append(item)
while len(second_number) < maxLengthList:
    item = input("Enter Your Second Number To Be Calculated: ")
    second_number.append(item)


type_of_computing = raw_input('(A)dding  or  (S)ubtracting  or  (M)ultiplying  or  (Dividing): ')

if type_of_computing == 'A' or 'a':
    print ('Final Result:')
    sum_list = [a + b for a, b in zip(first_numbers, second_number)]
    print sum_list



elif type_of_computing == 'S' or 's':
    print ('Final Result:')
    difference_list = [c - d for c, d in zip(first_numbers, second_number)]
    print difference_list




elif type_of_computing == 'M' or 'm':
    print ('Final Result:')
    product_list = [e * f for e, f in zip(first_numbers, second_number)]
    print product_list




elif type_of_computing == 'D' or 'd':
    print ('Final Result:')
    quotient_list = [g / h for g, h in zip(first_numbers, second_number)]
    print quotient_list





 

Tags: orofinnumberfortyperesultitem
2条回答

你的问题是if声明

if type_of_computing == 'A' or 'a':

应该是if type_of_computing == 'A' or type_of_computing == 'a'

因为您正在检查两种不同的情况。”'是一个已定义的字符,因此它总是返回true,这就是代码总是添加的原因。您还应该用elif语句修复这个问题,这个问题应该得到解决。然而,我没有自己测试这个

此外,由于您试图添加两个值,因此输入(第一个\u编号列表的每个项目和第二个\u编号列表的每个项目)应该是整数,而不是字符串

检查中的or表达式总是导致True,因为'a'是真(truthy)值。要测试某个值是否是您可以执行的两项操作之一,请执行以下操作:

if type_of_computing == 'A' or type_of_computing == 'a':

或:

if type_of_computing in ('A', 'a'):

但是对于不区分大小写的比较的特殊情况,只需使用upper()lower()规范化字符串并进行单个比较就更容易了:

if type_of_computing.upper() == 'A'

您还可以通过使用字典而不是一堆if语句来简化这类逻辑(并避免大量复制和粘贴)。下面是一种将代码改写为更短的方法:

maxLengthList = 1
first_numbers = [
    int(input("Enter Your First Number To Be Calculated: ")) 
    for _ in range(maxLengthList)
]
second_numbers = [
    int(input("Enter Your Second Number To Be Calculated: ")) 
    for _ in range(maxLengthList)
]


type_of_computing = input(
    '(A)dding  or  (S)ubtracting  or  (M)ultiplying  or  (Dividing): '
).upper()
compute = {
    'A': int.__add__,
    'S': int.__sub__,
    'M': int.__mul__,
    'D': int.__truediv__,
}[type_of_computing]

print('Final Result:')
print([compute(a, b) for a, b in zip(first_numbers, second_numbers)])

相关问题 更多 >