Python Program For Simple Calculator
7 answers
Awarded as helpful by the questioner
print("" ==================================================== == calculator == ==================================================== """) num1 = input("Enter the first number: ") oper = input("Which arithmetic operation (+,-,*,/) should be performed? ") num2 = input("Enter the second number: ") num1 = int(num1) num2 = int(num2) if (oper == "+"): print("\nYour calculation: \n", num1, " + ", num2) print("Result: \n", num1 + num2) elif (oper == "-"): print("\nYour calculation: \n", num1, " - ", num2) print("Result: \n", num1 - num2) elif (oper == "/"): print("\nYour bill: \n", num1, " / ", num2) print("Result: \n", num1 / num2) elif (oper == "*"): print("\nYour calculation: \n", num1, " * ", num2) print("Result: \n", num1 * num2) else: print("\nNo valid input");
print("" ==================================================== == calculator == ==================================================== This calculator adds, subtracts, multiplies and divides your numbers given in the following """)
num1 = int(input(“Enter the first number: “)) num2 = int(input(“Enter the second number: “)) sum1=num1+num2 sum2=num1-num2 sum3=num1*num2 sum4=num1/num2 print(num1, ” + “, num2) print(“Result: “, sum1) print(num1, ” – “, num2) print(“Result:”, sum2) print(num1, ” / “, num2) print(“Result:”, sum4) print(num1, ” * “, num2) print(“Result:”, sum3)
>>>#e.g.: >>> a = input() 1+2+3 >>> print a 6
>>>#This is much easier than the code mentioned so far.
What do you want to know?
We can do simple arithmetic in Python as we are used to from elementary school.
Addition and subtraction
For an addition we simply make the following input in the command line:
3 + 3
We get “6” as the result. The complete form would actually be:
print(3 + 3)
For the sake of clarity, we will always use the short form in this chapter. Of course, this also works with minus (but then you get a different result).
3 - 3
Multiply
At some point in school, multiplication and division came up in math class. We can also do this with the usual mathematical signs:
3 * 3
And as a result we get “9”
Division
And we already in school a division by the “/” is possible but also in Python a division by 0 is not possible.
3/3
Gives as result “1”. If we try to divide by “0”, we get an error message!
3/0
This leads to an error message “Traceback …” with an indication of the program line (“line X”) where the error occurred. Additionally we get the error name in English. In this case then “ZeroDivisionError: … division by zero”.
Modulo in Python
Much later in school, division with “remainder” is the order of the day. Mathematicians would call this mathematical function modulo (mod), which returns as output the remainder when dividing integers. In the following example it becomes comprehensible and understandable. The notation of modulo is the percent sign. We want to get the remainder of the division of 7 and 2:
7%2
As result we get “1”. The 2 goes 3 times completely into the 7 – i.e. 2+2+2 results in 6 and then a 1 remains from the 7. Instead of the remainder, we can also get the number of times the number “completely enters” the number to be divided. In our example above with
7//2
Our 2 goes 3 times into the 7 and the rest is ignored. Now we have already introduced the notation. Here we have simply 2 x “/”. These 2 functions only work with integer numbers.
Up anything
What is still missing in the typical functions? The typical “high” – speak in the nice mathematical notation 23. Here we have then as notation in Python:
2**3
Calculated internally “2 * 2 * 2” and as a result we get “8”. With 32 we get 9.
Square root
Who still misses the root extraction now. The square root is the simplest case. It runs over the trick with 0.5 So as notation:
9**0.5
As result we get the “3”. Here we also see that the notation in Python is always written with a dot – in German we speak of decimal numbers! So in Python we have “NachPUNKTzahlen”. If you do not only want to draw the square root, then you need the module “math”, which will be introduced later in the course. For the sake of completeness, here is simply the notation:
import math as m print(m.sqrt(25))
So much for the basic arithmetic operations and the application in Python.
TIP: Large numbers well readable
Once we get into the millions, large numbers become hard to read. In Python we can use the underscore (_) to make the number easy to read, but for the calculation this dash doesn’t matter at all. Just try it once:
# bad readable number1 = 1000000 number2 = 1000000 print(number1 + number2) # good readable number3 = 1_000_000 number4 = 100_000_000 print(number3 + number4) # both times the same result! # 101000000
It is and remains also an integer number. With the statement type()
we can query the variable type.
number3 = 1_000_000 print(type(number3))
As result comes:
Recommend – Social Bookmarks – Thank you
-
- tweet
-
- share Facebook
- pin it
- Share
-
- share
-
- share
-
- share
Python with the Casio FX-CG 50
Operating system: 3.50 MicroPython: 1.9.4 (Python 3)
Implementation, range of functions and performance
Those who know the power of Python and the possibilities it offers are quickly disillusioned when they realize what is behind “Casio-Python”. It is by no means standard Python, but merely a (further slimmed down) variant of MicroPython, a special Python version for microcontrollers. Apart from the language basics with all builtin functions, in OS version 3.3 only the modules math and random were added, which is sufficient for classic Python console programs including input and output. With OS version 3.4 was added with casioplot a new module was added, which now also allows – very!) rudimentary – graphics programming. In a 384×192 pixel part of the display (the status bar at the top of the screen is not usable) you can: – set all pixels individually in any RGB color – query the RGB codes of each pixel – output ASCII strings in three sizes and RGB colors That’s all. Doesn’t sound like much, and it is. However, you could make something out of it by implementing advanced drawing functions yourself. Although the Python programs are limited to 300 lines of 255 characters per source code, all self-created Python programs can in turn be imported as modules into other programs, so that there is practically (except for the memory of the GTR) no real size limit. Pleasing is at least the performance of the Python interpreterwhich applies to calculations as well as the graphic output. The latter is faster by a factor of 60-80 than the (however also agonizingly slow) graphics output of the built-in Casio BASIC. Drawing a function graph through a Python program using casioplot is (at least) as fast as using the built-in GRAPH module.
Programming the GTR
The Python interpreter is called via its own app tile from the main menu. From there, you have access to a folder structure where you can create and save your own Python programs. A simple development environment with editor – at least with colored syntax highlighting – and [RUN] button allow you to create and run Python programs.
That doesn’t sound so bad, but in practical handling it is an imposition! Entering source code is extremely tedious and cumbersome. Because Python is “case sensitive” – upper and lower case are distinguished – the input becomes even more tedious, because e.g. the [+] key is responsible for the plus sign, the opening square bracket, the small X and the capital X. Switching between the individual key assignments using [Shift] and [Alpha] is incredibly annoying and error-prone. In addition, the colon – often needed in Python – is not on the keyboard and therefore has to be picked out of the character catalog each time.
Last but not least, the system font, which needs getting used to anyway and is somewhat serif-heavy, is simply too large for entering source texts. Just 21 characters fit into one line, which is definitely too few. At this point at the latest, one would have wished that there was a way to at least change the font size.
Interestingly, the casioplot module offers the possibility to output strings in three different font sizes. In the (well readable) variant “medium” at least 32 characters fit into one line, with “small” there are 48 (but then also quite small and on the GTR display only badly readable) characters. ConclusionThe implemented Python interpreter can be used quite well – especially with the possibilities of casioplot – but developing programs with the built-in editor directly on the GTR is a pain and not recommended. Fortunately, the Casio FX-CG 50 is recognized as a mass storage device when connected to a computer via USB cable – regardless of the operating system used! Separate special software tied to individual operating systems is not required for this. So you can develop Python programs can be developed externally on the PC and tested there with a Python interpreter before they are transferred as source code file to the GTR and used there. Of course, this does not apply when using the casioplot module. However, this could be changed with relatively little effort by an own casioplot module for the PC, e.g. based on Tkinter, so that one would have a Casio Python-compatible development environment on the computer and only transfer the finished program to the GTR. With it one could then work quite passably.
Three examples
The Python shell as a calculator The Python shell is an integral and important part of every Python interpreter. Within a “terminal window” Python code can be entered line by line and executed directly. The Casio implementation of MicroPython also has such a shell. This is extremely handy for testing the smallest code snippets. A nice side effect is that you can also make good use of the Python shell as a calculator. This is appealing because Python is one of the (few) programming languages that allow integer operations with arbitrary precision – the only limit is the main memory of the respective device. On the Casio CG-50, the limit is about 500 digits according to my experiments. So it is possible to calculate about 345 can be calculated exactly and at lightning speed. The result has 489 digits: 373391848 … 0356481 (I leave out the other 473 digits here). Unfortunately, the operation of the shell is not as comfortable as it is known from the normal Python shell, where e.g. by means of the cursor keys previous inputs can be retrieved to the current line, modified if necessary and executed again. The Casio Python shell forgets everything! Each line has to be re-entered manually. This is annoying. Factorial for large numbers
What could be more obvious than calculating factorials, if you have a system that (theoretically) can handle arbitrarily large natural numbers. As is well known, 69! is the end of the line for most pocket calculators. 70! is a 101-digit natural number and there all normal calculators capitulate, because with exponential representation the mantissa would be three-digit – there is no room for that.
But no problem with the numerical possibilities of Python. Although you cannot access the GTR functions and simply type 70! in the shell (this leads to a syntax error because the exclamation mark is not a defined Python symbol), you can write a (very simple) Python program that calculates the factorial of a number to be entered by the user.
After a few tries, the result is clear: 253! can just be calculated (and again: lightning fast), at 254! the GTR reaches its memory limit and returns an error message instead of the result. By the way, the result has 500 digits – the first 14 can be seen in the screenshot. The complete source code of the program can be found further up on this page. Graphics programming
I’ve already explained the basics of the very limited Python graphics programming on the Casio CG-50 above. As an example, I wrote a program that draws a function graph including a coordinate system. The function term is f(x) = -0,3-x²+2, I chose the drawing window to match. You can see that the built-in function plotter was not used here,
that a complete axis labeling as well as a colored axis cross are available. Also, I drew the graph colorfully – it consists of nothing but randomly colored pixels. For comparison, here is the same graph – this time drawn with the built-in function plotter. In both cases, the drawing speed feels identical.
Usefulness for teaching
As much as I appreciate the Python programming language – the Python interpreter in the Casio CG-50 is ultimately nothing more than a nice gimmick. It’s a playground for those who like to work intensively with a calculator and enjoy doing all sorts of things with a GTR and “tickling” as much as possible out of such a device. The attractiveness of the Python implementation would increase significantly if there were an interface to the built-in GTR functions, so that, for example, equations and systems of equations could be solved within a Python program, graphs and elements of vector geometry could be drawn and included in programs. But even then one must honestly say: For the mathematics lessons the Python interpreter in the Casio CG-50 is no added value. A sensible application in computer science lessons I can not recognize either. Since the GTR is only introduced in the upper school, it would also only affect the computer science lessons in the upper school. In view of the curriculum requirements and the Central Abitur, there is hardly any room for such a project. And even a “GTR programming club” is not very attractive to me, because creating programs with the GTR is simply a torture. But if you use an external editor on the PC for program development, then you basically don’t need the GTR, you can do all the programming on the PC. To create an executable Python program (Python script), we need a file. The special thing about this file is the file extension. Here for Python then “.py” is used. It does not matter which operating system we are working with. In the example, the editor “notepad” available in the operating system is used under Windows. The simplest variant is to click on Start and then just start typing. As soon as we have typed the first letters of “editor” we already get the suggestion for the default editor. Select this editor. And now we can type our Python program directly in the editor. In our text editor we type
print('Hello world')
When saving, pay attention to the file extension “.py”! As file name I use for our first program “hallowelt.py”. I save my Python program in the folder “python-kurs.de” under “C:”. Now our folder should have this content: Folder with Python program
To start the Python program
Start Python under Windows
To start the Python program we need a DOS console. We call this under Windows by clicking on the start button again and simply typing “cmd” there. We can then use the suggested DOS console. Start cmd under Windows If the path in the operating system has been stored correctly during the installation of Python, we can start Python directly in the DOS console. For testing you can start Python without our written program. Just type “python” directly in the DOS console. If this works, we can start our Python program “hallowelt.py”. To do this, we have to specify the path and the filename after the program call.
python c:\python-kurs.de\hallowelt.py
By executing the program we now get the output in the console of “Hello World”. If we want to save ourselves the long path name to type in, we can change to the directory once using the DOS statements cd
and then run the program without path names. Just have a look at the following screenshot. Here at the beginning the program is executed with path specification and then we change to the folder “Python-Kurs.de” (looks like an internet address, but can be used as a directory (a bit of advertising and copy protection)). Execute Python program without path
Running Python programs with the Mac OSx
On the Mac we start the terminal. Here we have the peculiarity that the old version of Python is already shipped in the operating system. We can run directly in the terminal python
directly in the terminal and get the version number of Python – in the example this is “Python 2.7.10”. If we have the current Python3 installed, we can install it in terminal with python3
and get the corresponding version number as feedback. Python under Mac OSx To start our program, we enter the path and the file name in the terminal after the start command for Python:
python3 Documents/Python-course.de/hallowelt.py.
The program will then be executed. Run Python program with Mac
Recommend – Social Bookmarks – Thank you
-
- tweet
-
- Share Facebook
- pin it
- Share
-
- share
-
- share
-
- share
Python Program For Simple Calculator.
- Car Not Shifting Gears
- Really Big Synonym
- P90X Chest Shoulders And Triceps
- Good Morning Sunday Breakfast Images
- Agar Skins Top
- Random Snapcode
- Female Pop Art Artists
- Hot Holiday Destinations In March