Database Reference
In-Depth Information
4. Let's declare a variable,
a
, and assign it the value of
7
, and we will declare anoth-
er variable,
b
, and assign it the value of
13
. Type the following code in the
Python editor:
a = 7
b = 13
5. Then, we will declare a new variable,
s
, which will have the sum of
a
and
b
; you
might have guessed how to write it:
a = 7
b = 13
s = a + b
6. This will sum
a
and
b
and save the answer in the
s
integer. We are not done still;
we need to print this result. The
print
command allows us to print values and
strings. Note that we have to convert
s
to a string if we are planning to concaten-
ate it with a string. For this, we use the
str
command as follows:
a = 7
b = 13
s = a + b
print "The sum is " + str(s)
7. Before we save this file, we will add one last line. Python scripts execute fast, and
you will barely be able to see the output before the script is terminated. So, we
add a line to pause the script by asking the user to press any key. The input com-
mand asks the user for a value and stores it in a variable. It also pauses the script
until a user takes an action. Go ahead and add the input statement as you can see
in the following code segment:
a = 7
b = 13
s = a + b
print "The sum is " + str(s)
input ("Press any key to continue..")
8. We are now ready to save the file. From the
File
menu, click on
Save
and then
browse to
c:\gdb
. Create a new folder called
scripts
, where we will be stor-
ing our scripts. Name the file
sum.py
; your file should look like the following
screenshot: