It's nothing to difficult and should be a nice way to start. We are going to program a simple calculator that will take 2 numbers from the user and process them.
The program will work like this:
1 Display a welcome message on the first run only
2 Display a list of options for the user to choose from - its a calculator so Add, Subtract, Devide, Multiply
2.1 User will select the appropriate menu function eg press 1 for Add
3 Using the selected function the program will ask for the first number
3.1 User inputs their first number
4 The user is then asked for their second number based on the selected function
4.1 User inputs their first number
5 The program will print the relevent numbers and appropriate function along with the answer
6 The program will then ask the user to select a function again
6.1 if the user enters the number 1-4 back to 3
6.2 if the user enter the number 5 the program will end
So the basis of the program will work around a loop - ask for an input - then using statements process the numbers according to what the user requested. Seems simple.
I think the best way would be to provide the code and then work trough the various parts.
This may not be the simples and easiest way to do what we want - but thats not the point in this case:
## Python Calculator 1.0
## Demonstrating multiple Python Elements
## Tech-101.com
def main():
loop = 1
choice = 0
while loop == 1:
print "Option Menu"
print " "
print "Option 1 = Add"
print "Option 2 = Subtract"
print "Option 3 = Multiply"
print "Option 4 = Devide"
print "Option 5 = Exit!"
print "--------------------"
print " "
user_choice = input ("What would you like to do? Type 1-4: ")
if user_choice == 1:
add1 = input ("First number: ")
add2 = input ("Second number: ")
print add1, "+", add2, "=", add1 + add2
print "--------------------"
print " "
elif user_choice == 2:
sub2 = input("Subtract this: ")
sub1 = input("from this: ")
print sub1, "-", sub2, "=", sub1 - sub2
print "--------------------"
print " "
elif user_choice == 3:
mul1 = input("Multiply this: ")
mul2 = input("with this: ")
print mul1, "*", mul2, "=", mul1 * mul2
print "--------------------"
print " "
elif user_choice == 4:
div1 = input("Divide this: ")
div2 = input("by this: ")
print div1, "/", div2, "=", div1 / div2
print "--------------------"
print " "
elif user_choice == 5:
loop = 0
print "Welcome to the Tech-101 Calculator!"
main()
print "Thanks for Playing!"
1 - Ok so to start with - well to start with we have some comments. The # symbol is used to display comments in Python code allowing you to add descriptions to parts of the code that you don't want to display to the end user.
2 - Next we have def main(). This is a simple function that runs the main elements of the program. A function can be as big or as small as required and is usually used to seperate pieces of code for a specific task.
If you need to perform a task at multiple points in the program - instead of having to produce multiple pieces of code all you need to do is call the process and complete the task required.
Functions can be called at any point within the program and are usually called within a main fucntion. The following is an example:
def main(): print "Hello!" message() print "Have Fun!" def message(): print "Welcome to: " print "Tech-101" main()
So here - we have the main function which will print Hello!. Then it calls the message function which prints Welcome to: Tech-101. Once the message function has completed the main function will continue to print Have Fun!
The calculator has one single function main(). The rest of the processing is completed using if, elifs and loops.
3 - The next line is loop = 1. This is going to be the basis of our program loop. There is also a while statement based on this loop. The while loop will run as long as long as something we have defined stays the same or falls into a specificed range. In this case the main() function will run as long as loop = 1. If loop were to equal 0,2 or any other unit - the main function would end.
Therefore we define at the beginning before calling loop that it does indeed equal 1.
As loop equals 1 we can move on. The next few lines are simple Print statements to make the program look good. It will print the relevant lines one by one.
4 - Next is user_choice = input ("What would you like to do? Type 1-4: "). This statement captures the users choice using the input command. All that is required here is to name the input and it will capture what the user inputs.
The syntax would follow variable = input ("question"). It doesn't matter what goes in the open brackets as this is simply treated like a print if enclosed in question marks.
The variable can also be named anything you require as long as it falls within the rules of python naming conventions. In this case the user will be displayed with the text: "What would you like to do? Type 1-4: ". The user will then type a response which will be stored in user_choice.
5 - Now we have a value held in user_choice we can do something with it. The main basis of this program uses an if or elif statement. The if and else statements work like this - if something equals something then do it otherwise do something else.
To put that into some type of context - take reading a book. The if statement would be > if you have finished reading the page > turn it. The else statement would be else = dont
The syntax for if and else would be as follows:
if variable = amount: process else: process
Notice the important use of indenting. Any text that is a lower indent than the preceding if statement will be held within the if statement. For example:
if today = wednesday: print today is a wednesday
See here wednesday isn't indented the same as print today is a. Therefor if you were to run this if statment the reponse would be: "today is a"...but no wednesday as it is not contained in the statment correctly.
This would also cause a naming error becuse you will not have defined "wednesday" as a process or variable and so python won't know what to do with it!
The correct version would be:
if today = wednesday: print today is a print wednesday
In this case we have a few if statements. Therefor after using the first if statment each statement after this would be an elif until you reach the final statement where you can end on an else if you want or an elif.
In this case python will move down each statement testing the users input against the rule. Once it finds a rule the variable fits it will process it according to that rule.
So if the user chooses 2 - it will ignore the first if statement as it doesn't equal 1 and will not look to see what to do with the variable. The input will however match the second statement. Therefor python will process the input according to the rule.
6 - The rules within the if/elif statements are nothing more than simple maths and further input processes. To use some context the user in this case has entered 2. So the first point of call is the first input statement. The same as before python will request the user input a number. Once the user does it will ask for a second number. After they enter a number for the second time - the maths comes into play.
The if statement for "2" is subtract. So the users 2 number are held within sub1 and sub2. All that happens on the line:
print sub1, "-", sub2, "=", sub1 - sub2is that python will print sub1. Here we have a single print statement and each different element we want to print is seperated by commas. This will therefor print everything on one line.
Notice sub1 isn't in speech marks? Therefor it will print the value of sub1 and not the word sub1.
For example if the user entered a 8 for their first number (stored in sub1) and 5 for their second number (stored in sub 2) followed by the line print sub1 - python will print the number 5. The minus sign initially is in speach marks.
So python has printed 8 - 5 =
Now the - sign isn't in speach marks and the sub1 - sub2 aren't separated by commas so it will be processed as a group - and printed.
This will give us the line in total: 8 - 5 = 3
Quite simple once you understand that the " " will transform a function such as subtraction into a word and how each element is separated.
So now what? Well the whole thing will repeat. The number has matched an if statement and will continue to match the rest. It won't match any - it will hit the end of the indentation and will continue back up to the "while" statement. Why? Because loop still equals 1!
If we added the line loop == 0 after giving the result of the if statement the program would end and the line print "Thanks for Playing!" would appear at the end as it appears after the main function.
To exit the program the user will press 5. Notice this matches the final elif statement which simply says loop no longer equals 1 - it equals 0. After doing that python will then no longer proceed to the top as the while statement no longer matched and it will end.
I would encourage you now to type the program out - don't copy and paste! as this will allow you to work on indentation and take in each line at a time.
It should be simple after looking over as it is allof of inputting and printing - with very little else happening besides the magic loop.
There are a couple of other areas to point out here with the if and elif statements. The input will take any valid unit/key. Therefore the user could try and subtract 6 from D...not exactly perfect.
This would look at error catching to make sure the use works in the confines of the system. We could make things simple and try using an else statement or further if statements. Eg if catchment = input() <1 OR >5 print "Error!!". This means the program will know how to handle user errors etc. It would also incorporate less than (<) and greater than (>) along with the OR statement. I'm sure if you have understood the programming above those new elements will be simple enough.
Why not try and edit the code to add this statement using the correct layout and syntax?
This has been your first real look into Python besides the Hey World! printing we did. Its a big step but take it slowly and it will become obvious.





Sign In
Create Account












