First example program

Here is the source code for the arithmetic.py example I showed in the last set of lecture notes.

a = 1
b = 2
sum = a + b
print("Sum is " + str(sum))

A Python program is a list of statements in the Python language, one statement per line.

The first statement you see in this program is an assignment statement.

a = 1

The purpose of an assignment statement is to assign a value to a variable. This particular assignment statement creates a variable named a and assigns the value 1 to it.

The assignment statement

sum = a + b

does a calculation using the values of the variables a and b. The calculation adds the values of these two variables together and assigns the result of the addition to a new variable, sum.

After doing a calculation, we may want to display the result of the calculation for the user to see. To do this, we use the Python print() command.

print("Sum is" + str(sum))

This particular print command constructs some text to be printed by using the Python string concatenation operator, +. Here we are combining some literal text, "Sum is ", with some text that results from applying the string conversion function str() to the variable sum.

Another way to achieve the same effect is to use this form of the print command:

print("Sum is",sum)

More about arithmetic in Python

Python offers a set of seven different operators for doing arithmetic.

SymbolOperation
+Addition
-Subtraction
*Multiplication
/Division
**Exponentiation
%Modulus
//Floor division

The first four of these operators correspond to the standard arithmetic operators that you know.

The exponentiation operator is used to compute powers, including non-integer powers. For example, to compute the square root of 2 you would do

x = 2**0.5

The last two operators are used to implement an alternative form of division, known as integer division. When you use the ordinary division operator with two integer arguments, the result will be a non-integral amount in some cases. For example, the statement

x = 17/5

results in the variable x having the value 3.4. The floor operator // when applied to two integers produces an integer quotient that drops the decimal part. For example, the statement

x = 17/5

results in x having the integer value 3. The modulus operator, %, returns the remainder that results in an integer division. For example, the statement

y = 17%5

results in the variable y having the value 2, which is the remainder that results when we divide 5 into 17.