There are several ways to do this, but I only know two of them:
The first way to do it is to choose before if want to subtract, add, multiply or use division and them just go there. That would maybe work in Python 2, but not in Python 3. Because in Python two there are ways to go to another part of the script, but not in Python 3, or at least not a real documented way.
That's why I use the second method:
To have three variables:
a
b
c
It's important to have them under each other, otherwies you would only be able to put in one digit numbers.
Ofcourse, this method have some bad parts to. You'll have to press enter afrter every number you put in:
55
<Enter>
+
<Enter>
55
<Enter>
110
But let's move on.
after a b and c you have to put input () so you can put a number in there:
a = input()
b = input()
c = input()
Now when we have the variables equals whatever we want, we need to make them interact mathematically. How do we do that? Well, we have to tell Python that when "b" = +,-,*,/ it should either +,-,*,/ depending on what you puted in.
So we do that by using the "if statement". We need to tell python if, for example, "b" = + it should add "a" and "c" togehter:
if b >= "+" :
print(int(a) + int(c))
Okay, let me explain the code for you.
Line 1: This line basically tells Python if b = "+" it should do whatever is under it. We use the "" to say that + is a string and not a normal number.
Line 2: First of, make sure you have four spaces after a "if statement". Otherwise Python will give you errors. Okay now to the actual code. "Print" outputs whatever is in the (). In this case it should output a + c. As you can see we use int() before them. All int() does is it defines whatever is in the () is a number and not a letter.
Do this whit all of the other mathematic characters. But be aware, Python doesn't do integer division by default, so you naeed to tell python that a and c are decimals or otherwise it won't divide.
Also, after the if commando, use elif, otherwise it won't work.
Here is my code:
As you can see I didn't have division because for what I will use my Pycualtor I won't need it.
Also at the end of the code you can see k=input("Press <Enter> to exit"). I use so my Pyculator won't close right after I wrote my number. If you are on Linux you don't need this.
And here is the result:
Hard to see I know.
Hope you learned something, and please develope the Pyculator even more. Send update to NerdyAlos@gmail.com! Thank you!


No comments:
Post a Comment