Python基本计算器 [英] Basic Calculator in Python

查看:60
本文介绍了Python基本计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手。我尝试制作一个基本的计算器,但是我找不到真正的问题。它以0退出码返回,但是什么也没有出现,没有输入就什么都没有。任何帮助,将不胜感激。谢谢。

I'm new to Python. I tried to make a basic calculator, but i can't really find the problem. It returns with 0 exit code, but nothing appears, no input no nothing. Any help with this will greatly be appreciated. Thank You.

def add(num1, num2):
    return num1 + num2

def subtract(num1, num2):
    return num1 - num2

def div(num1, num2):
    return num1/num2

def multi(num1,num2):
    return num1*num2

def main():
    operation = input("What do you want to do?(+, -, *, or /):")
    if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
        print("Your input is invalid. Please enter a valid input.")
    else:
        num1 = float(input("Enter value for num1: "))
        num2 = float(input("Enter value for num2: "))
        if (operation == "+"):
            print(add(num1, num2))
        elif (operation == "-"):
            print(subtract(num1, num2))
        elif (operation == "*"):
            print(multi(num1,num2))
        elif (operation == "/"):
            print(div(num1,num2))

    main()


推荐答案

基于上面的代码,您实际上从未运行过 main()。现在,您已经说过 main 的定义是提示用户,检查输入是否正确,然后进行数学计算。最后的 main()使程序在完成所有这些操作之后重复执行(不确定是否要循环)。

Based on the code above, you are never actually running main(). Right now, you have said that the definition of main is to prompt the user, check if the input was correct, and then do the math. The main() at the end causes the program to repeat after doing all this (not sure if you want the loop or not).

如果不想循环,只想运行一次计算器,只需删除最后一个 main(),因为现在缩进意味着它位于 def main()内。只需将其向左移动到与 def main():相同的缩进级别,您的程序就可以正常运行。

If you don't want the loop, and just want to run the calculator once, just remove the indent of the last main(), because right now the indentation means it is inside of def main(). Just move it to the left to be at the same indentation level as the def main(): and your program should run fine.

这篇关于Python基本计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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