By: Lord Nikon
February 9, 2006
Well, after reading some basic Python tutorials, I have enough knowledge for my first tutorial.
First of all, download Python 2.4. After downloading and installing, go to Start>>All Programs>>Python 2.4>>IDLE [Python GUI].
The new window that shows up is the window that our programs will be ran in. Click File>>New Window, and in this new window we will write our calculator code that I will explain it in a minute:
OP = raw_input('Operation: ')
First = raw_input('First number: ')
Second = raw_input('Second number: ')
if OP == "+":
Answer = int(First) + int(Second)
elif OP == "-":
Answer = int(First) - int(Second)
elif OP == "*":
Answer = int(First) * int(Second)
elif OP == "/":
Answer = int(First) / int(Second)
else:
print "Error"
print 'The answer is %s thank you for using! First Number: %s Second Number: %s Operator: %s' % (Answer, First, Second, OP)
Ok, the first part OP = raw_input('Operation: ') will assign the value someone types in to the variable OP so you can type +,-,* and / for the operator sign.
In the second part: First = raw_input('First number: ') and Second = raw_input('Second number: ')
This is the same as the first part, the only difference between the two are the variable names.
Third part:
if OP == "+":
Answer = int(First) + int(Second)
elif OP == "-":
Answer = int(First) - int(Second)
elif OP == "*":
Answer = int(First) * int(Second)
elif OP == "/":
Answer = int(First) / int(Second)
else:
print "Error"
print 'The answer is %s thank you for using! First Number: %s Second Number: %s Operator: %s' % (Answer, First, Second, OP)
First of all, it determines what the OP was. If the operator was *, then the answer variable would be int(First) * int(Second). Pretty easy as you can see. It's a common if statement. If the sign isn't any of the specified, the program will print an error.
Last Part:
print 'The answer is %s thank you for using! First Numer: %s Second Number: %s Operator: %s' % (Answer, First, Second, OP)
I know you might be a little confused, but it's quite simple. First of all it will print OP, Answer, First, and Second in the same string. However, notice the %s in the string all of those will be replaced by variables specified after the print command:
% (Answer, First, Second, OP)
which means the first instance of %s will be replaced by Answer the second instance will be replaced by First etc..
Go ahead and run the program. If all went well you should get results like this:
Operation: /
First number: 108
Second number: 9
The answer is 12 thank you for using! First number: 108 Second number: 9 Operator: /
>>>
Note it will show up in the Python GUI the first window that showed up when we started.
So wasn't that fun. Python is a harder language to use than VB, but it has some advantages to it like Regex and internet programming which I believe makes it much easier for lots of things.
|