python编写计算器输入1或2代表+或x_用Python编写四则计算器

介绍

Python编程语言是使用数字和计算数学表达式时使用的一个很好的工具。这种质量可以用来做出有用的程序。

本教程介绍了一个学习练习,以帮助您在Python

3中创建一个简单的命令行计算器程序。虽然我们将通过一种可能的方式来制作此程序,但是有很多机会来改进代码并创建一个更健壮的计算器。

我们将使用数学运算符 , 变量 , 条件语句 ,函数和处理用户输入使我们的计算器。

先决条件

对于本教程,您应该在本地计算机上安装Python

3,并在机器上设置一个编程环境。如果您需要请安装Python或设置环境,你可以按照这样做的与您的操作系统相应的指南 。

第1步 – 提示用户输入

当人类提供计算机求解的方程时,计算器工作得最好。我们将开始编写我们的程序,在这里人类输入他们希望计算机工作的数字。

要做到这一点,我们将使用Python的内置input()接受从键盘用户生成的输入功能。

内的括号的input()函数,我们可以通过一个串来提示用户。我们将用户的输入分配给一个变量。

对于这个程序,我们希望用户输入两个数字,让我们让程序提示两个数字。当要求输入时,我们应该在字符串的末尾包含一个空格,以便在用户的输入和提示字符串之间有一个空格。

number_1=input('Enter your first number: ')number_2=input('Enter your second number: ')

在写完我们的两行之后,我们应该在运行它之前保存该程序。我们可以调用这个程序calculator.py并在终端窗口中,我们可以通过使用命令在我们的编程环境中运行该程序python

calculator.py 。您应该能够响应每个提示输入到终端窗口。

OutputEnteryour first number:5Enteryour second number:7

如果你运行这个程序几次,并改变你的输入,你会注意到,你可以输入任何你想要的时候提示,包括单词,符号,空格,或只是输入键。这是因为input()获取数据作为字符串 ,并且不知道我们正在寻找一个数字。

我们想在这个程序中使用一个数字有两个原因:1)使程序执行数学计算,和2)验证用户的输入是一个数字字符串。

根据我们的计算器的需求,我们可能想从进来的字符串转换input()函数整数或浮点数。

对于我们来说,整数适合我们的目的,所以我们会包住input()函数中的int()函数来转换输入到整数数据类型 。

calculator.py

number_1=int(input('Enter your first number: '))number_2=int(input('Enter your second number: '))

现在,如果我们输入两个整数,我们不会遇到错误:

OutputEnteryour first number:23Enteryour second number:674

但是,如果我们输入字母,符号或任何其他非整数,我们会遇到以下错误:

OutputEnteryour first number:sammyTraceback(most recent calllast):File"testing.py",line1,innumber_1=int(input('Enter your first number: '))ValueError:invalid literalforint()withbase10:'sammy'

到目前为止,我们已经设置了两个变量来以整数数据类型的形式存储用户输入。您还可以尝试将输入转换为浮动。

第2步 – 添加运算符

我们的程序完成之前,我们会增加一共有4 数学运算符 : +加法, -减法, *乘法,和/除法。

当我们构建我们的程序时,我们要确保每个部分都正常工作,所以在这里我们开始设置添加。我们将在打印函数中添加这两个数字,以便使用计算器的人将能够看到输出。

calculator.py

number_1=int(input('Enter your first number: '))number_2=int(input('Enter your second number: '))print(number_1+number_2)

让我们运行程序,并在提示时输入两个数字,以确保它按预期工作:

OutputEnteryour first number:8Enteryour second number:311

输出显示我们程序正常工作,所以让我们添加一些上下文,让用户在程序的整个运行时间得到充分的通知。要做到这一点,我们将使用字符串格式化来帮助我们正确地格式化我们的文字,并提供反馈。我们希望用户接收关于他们输入的数字和正在生成的结果旁边使用的运算符的确认。

calculator.py

number_1=int(input('Enter your first number: '))number_2=int(input('Enter your second number: '))print('{} + {} = '.format(number_1,number_2))print(number_1+number_2)

现在,当我们运行程序时,我们将有额外的输出,让用户确认程序正在执行的数学表达式。

OutputEnteryour first number:90Enteryour second number:71790+717=807

使用字符串格式化器为用户提供更多反馈。

此时,您可以使用我们用于添加的相同格式将剩余的运算符添加到程序中:

calculator.py

number_1=int(input('Enter your first number: '))number_2=int(input('Enter your second number: '))# Additionprint('{} + {} = '.format(number_1,number_2))print(number_1+number_2)# Subtractionprint('{} - {} = '.format(number_1,number_2))print(number_1-number_2)# Multiplicationprint('{} * {} = '.format(number_1,number_2))print(number_1*number_2)# Divisionprint('{} / {} = '.format(number_1,number_2))print(number_1/number_2)

我们加入剩余运算符, - * ,和/入上面的程序。如果我们此时运行程序,程序将执行上述所有操作。但是,我们希望将程序限制为一次只执行一个操作。为此,我们将使用条件语句。

第3步 – 添加条件语句

随着我们calculator.py计划,我们希望用户能够在不同的运营商之间进行选择。所以,让我们开始在程序的顶部添加一些信息,以及一个选择,让人知道该做什么。

我们将使用三个引号在一些不同的行上写一个字符串:

'''

Please type in the math operation you would like to complete:

+ for addition

- for subtraction

* for multiplication

/ for division

'''

我们使用各操作的符号为用户做出他们的选择,所以,如果用户想要进行分裂,它们将输入/ 。

我们可以选择我们想要的任何符号,不过,像1foraddition ,或bforsubtraction 。

因为我们是要求输入用户,我们要使用的input()函数。

我们将会把字符串内input()函数,并将输入的值传递给一个变量,我们将其命名operation 。

calculator.py

operation=input('''Please type in the math operation you would like to complete:+ for addition- for subtraction* for multiplication/ for division''')number_1=int(input('Enter your first number: '))number_2=int(input('Enter your second number: '))print('{} + {} = '.format(number_1,number_2))print(number_1+number_2)print('{} - {} = '.format(number_1,number_2))print(number_1-number_2)print('{} * {} = '.format(number_1,number_2))print(number_1*number_2)print('{} / {} = '.format(number_1,number_2))print(number_1/number_2)

在这一点上,如果我们运行我们的程序,我们在第一个提示符输入没有关系,所以让我们将条件语句添加到程序中。由于我们如何构建我们的程序中, if声明将在这里执行此外,将有3否则,如果还是elif语句其他每个经营者,以及else声明将到位,以处理错误如果该人没有输入操作符号。

python.py

operation=input('''

Please type in the math operation you would like to complete:

+ for addition

- for subtraction

* for multiplication

/ for division

''')number_1=int(input('Enter your first number: '))number_2=int(input('Enter your second number: '))ifoperation=='+':print('{} + {} = '.format(number_1,number_2))print(number_1+number_2)elifoperation=='-':print('{} - {} = '.format(number_1,number_2))print(number_1-number_2)elifoperation=='*':print('{} * {} = '.format(number_1,number_2))print(number_1*number_2)elifoperation=='/':print('{} / {} = '.format(number_1,number_2))print(number_1/number_2)else:print('You have not typed a valid operator, please run the program again.')

要遍历这个程序,首先它提示用户放入一个操作符号。我们会说用户输入*繁殖。

接下来,程序要求2的数字,和用户输入58和40 。此时,程序显示执行的方程和乘积。

OutputPleasetypeinthe math operation you would like to complete:+foraddition-forsubtraction*formultiplication/fordivision*Pleaseenter the first number:58Pleaseenter the second number:4058*40=2320

由于我们如何组织程序,如果用户输入%当被问及在第一个提示的操作,他们将不会收到反馈再次尝试,直到输入数字后。您可能需要考虑其他可能的选项来处理各种情况。

在这一点上,我们有一个全功能的程序,但我们不能执行第二或第三个操作,而不再次运行程序,所以让我们添加一些更多的功能到程序。

第4步 – 定义函数

为了处理按照用户需要多次执行程序的能力,我们将定义一些函数。让我们先把我们现有的代码块放到一个函数中。我们将其命名函数calculate()和函数本身中添加缩进的附加层。为了确保程序运行,我们还将调用文件底部的函数。

calculator.py

# Define our functiondefcalculate():operation=input('''

Please type in the math operation you would like to complete:

+ for addition

- for subtraction

* for multiplication

/ for division

''')number_1=int(input('Please enter the first number: '))number_2=int(input('Please enter the second number: '))ifoperation=='+':print('{} + {} = '.format(number_1,number_2))print(number_1+number_2)elifoperation=='-':print('{} - {} = '.format(number_1,number_2))print(number_1-number_2)elifoperation=='*':print('{} * {} = '.format(number_1,number_2))print(number_1*number_2)elifoperation=='/':print('{} / {} = '.format(number_1,number_2))print(number_1/number_2)else:print('You have not typed a valid operator, please run the program again.')# Call calculate() outside of the functioncalculate()

接下来,让我们创建一个由更多条件语句组成的第二个函数。在这个代码块中,我们想给用户选择他们是否想再次计算。我们可以依据这一关我们的计算器条件语句,但在这种情况下,我们就只有一个if一elif ,一个else来处理错误。

我们将其命名这个函数again()并将其添加低于我们的defcalculate():代码块。

calculator.py

...# Define again() function to ask user if they want to use the calculator againdefagain():# Take input from usercalc_again=input('''Do you want to calculate again?Please type Y for YES or N for NO.''')# If user types Y, run the calculate() functionifcalc_again=='Y':calculate()# If user types N, say good-bye to the user and end the programelifcalc_again=='N':print('See you later.')# If user types another key, run the function againelse:again()# Call calculate() outside of the functioncalculate()

虽然有一些错误处理与上面的else语句,我们也许可以做得更好一点接受,也就是说,一个小写y和n除了大写Y和N 。

要做到这一点,让我们添加字符串函数 str.upper()

calculator.py

...defagain():calc_again=input('''

Do you want to calculate again?

Please type Y for YES or N for NO.

''')# Accept 'y' or 'Y' by adding str.upper()ifcalc_again.upper()=='Y':calculate()# Accept 'n' or 'N' by adding str.upper()elifcalc_again.upper()=='N':print('See you later.')else:again()...

在这一点上,我们应该加again()函数到年底calculate()函数,这样我们就可以触发,要求用户不管他们是否愿意继续代码。

calculator.py

defcalculate():operation=input('''

Please type in the math operation you would like to complete:

+ for addition

- for subtraction

* for multiplication

/ for division

''')number_1=int(input('Please enter the first number: '))number_2=int(input('Please enter the second number: '))ifoperation=='+':print('{} + {} = '.format(number_1,number_2))print(number_1+number_2)elifoperation=='-':print('{} - {} = '.format(number_1,number_2))print(number_1-number_2)elifoperation=='*':print('{} * {} = '.format(number_1,number_2))print(number_1*number_2)elifoperation=='/':print('{} / {} = '.format(number_1,number_2))print(number_1/number_2)else:print('You have not typed a valid operator, please run the program again.')# Add again() function to calculate() functionagain()defagain():calc_again=input('''

Do you want to calculate again?

Please type Y for YES or N for NO.

''')ifcalc_again.upper()=='Y':calculate()elifcalc_again.upper()=='N':print('See you later.')else:again()calculate()

现在,您可以运行您的程序python

calculator.py在终端窗口,你就可以计算出很多次,你想。

第5步 – 改进代码

我们现在有一个很好的,功能完整的程序。然而,还有很多,你可以做,以改善这个代码。例如,您可以添加欢迎函数,欢迎人们加入程序顶部的程序代码,如下所示:

defwelcome():print('''

Welcome to Calculator

''')...# Don’t forget to call the functionwelcome()calculate()

有机会在整个程序中引入更多的错误处理。对于初学者来说,可以保证程序继续运行,即使用户类型plankton当记者问了许多。

作为该计划是,现在,如果number_1和number_2不是整数,则用户会得到一个错误,程序将停止运行。

此外,对于当用户选择除法运算符(件/ )和类型0为他们的第二个数字( number_2 ),用户将收到一个ZeroDivisionError:divisionbyzero错误。

为此,您可能需要使用异常处理与try...except声明。

我们仅限于4个运算符,但您可以添加其他运算符,如:

...operation=input('''

Please type in the math operation you would like to complete:

+ for addition

- for subtraction

* for multiplication

/ for division** for power% for modulo''')...# Don’t forget to add more conditional statements to solve for power and modulo

此外,您可能想用循环语句重写部分程序。

有许多方法来处理错误,并修改和改进每个编码项目。重要的是要记住,没有一个正确的方法来解决我们提出的问题。

结论

本教程通过一个可能的方法在命令行上构建计算器。完成本教程后,您将能够修改和改进代码,并对需要在命令行上进行用户输入的其他项目进行工作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值