我在Python的计算器程序中得到了错误的输出 [英] I am getting wrong output in my calculator program in Python

查看:79
本文介绍了我在Python的计算器程序中得到了错误的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我做了一个基本的计算器程序,但我得不到正确的输出,这是我的代码



hey i made a basic calculator program but i am not getting correct output from it this is my code

def add(first,second):
    return  first+second

def multiply(first,second):
    return  first*second

def subtract(first,second):
    return  first-second

def divide(first,second):
    return  first/second

print("1.division")
print('2.multiplication')
print('3.subraction')
print('4.addition')

user_input = input('enter your choice:')
first_num = float(input('enter first number:'))
second_num = float(input('enter another number:'))

if user_input==1:
    print(divide(first_num,second_num))

elif user_input==2:
    print(multiply(first_num,second_num))

elif user_input==3:
    print(subtract(first_num,second_num))
else:
    print(add(first_num,second_num))



我得到的输出是这样的



1.division

2.multiplication

3 .subraction

4.addition

输入您的选择:2

输入第一个数字:8

输入另一个数字:5

13.0

有人可以帮忙吗?



我尝试了什么:



我尝试使用不同的数字


the output i am getting is like this

1.division
2.multiplication
3.subraction
4.addition
enter your choice:2
enter first number:8
enter another number:5
13.0
Can Someone help please?

What I have tried:

I tried using different numbers

推荐答案

您的输入选择不是数字,而是串。因此,它将直接转到else语句。 (另外)



希望这有帮助。
Your input choice is not a number, but a string. It will therefore directly go to the else statement. (addition)

Hope this helps.


将您的代码更改为:

Change your code to:
if user_input==1:
    print(divide(first_num,second_num))

elif user_input==2:
    print(multiply(first_num,second_num))

elif user_input==3:
    print(subtract(first_num,second_num))

elif user_input==4:
    print(add(first_num,second_num))

else:
    print(add('Error: wrong choice'))



这样,你没有得到错误的结果,你被告知用户选择不是认识。


This way, you don't get wrong result, you are told that the user choice was not recognized.

引用:

我尝试使用不同的数字



As对于代码中的问题,解决方案1给出了原因。
所有输入都是a字符串,所以你需要转换为整数或与字符串比较。


As for the problem in code, solution 1 give you the reason.
All input is a string, so you need to convert to integer or compare with string.


这篇关于我在Python的计算器程序中得到了错误的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆