Chapter 3 Simple Commands and Data Structures

This chapters introduces you to the simple commands and the data structures in Python.

3.1 How to Run Python Programs?

You can use this Python sandbox to check the instructions from this section of the tutorial. Press the “List” button to see the list of examples.

Once you are comfortable with writing small programs, use the Python sandbox or the repl.it site to write larger programs. The advantage of these two later sandboxes is that they give you full error messages.

This tutorial uses Python version 3.x.

3.2 Printing on the Screen

Keyword Action
print prints text on screen

In our first exercise, we will use the Python keyword ‘print’ to to print a message on the screen. Type the following code in the Python sandbox and press ‘Run.’

print ("Welcome to the class")

You will see ‘Welcome to the class’ being printed on the output screen at the bottom.

Next, try a multi-line Python program.

print("Welcome")
print("to the class")
print("today")

You will see the texts ‘Welcome,’ ‘to the class’ and ‘today’ being printed in three separate lines. By default, Python’s ‘print’ command prints its output in a separate line. It is possible to change that default option as we will see in the next example.

We should also mention that, in general, a multi-line Python program starts from the top line and runs instruction in each line one by one until reaching the line. It is also possible to change that default flow by using special Python keywords. as we will learn in later sections.

3.2.1 Commas in ‘print’ Statements

If you add a comma at the end of a ‘print’ statement, the output of the following ‘print’ statement is displayed in the same line. Here is an example.

print("Welcome"),
print("to the class")
print("today")

You will see that ‘Welcome to the class’ is printed in one line and ‘today’ in the following line. If another comma is added at the end of the second line, the entire text ‘Welcome to the class today’ will be printed together.

Try -

print("Welcome", "to the class", "today")

When you use commas within the same ‘print’ statement, the entire text will be printed in the same line. Therefore, the output of the above code is identical to the first code at the top of this tutorial. This may seem like doing something simple in a convoluted way. The usefulness of using commas withing the same print statement will be apparent in the fourth section, where we discuss variables.

3.2.2 Comments

As you learned in the last section, Python starts from the top of a multi-line code and executes every line of instruction until it reaches the bottom. However, it is possible to tell Python to ignore certain lines, and to do that add ‘#’ at the front of the line. If the character ‘#’ is placed in the middle of a line, all texts written on the right of ‘#’ are ignored.

Try this command -

#
# All codes and text after # are ignored.
# Therefore, the part [print "Yesterday was Friday"] below
# does not give any output.
#

print("Today is Saturday")  # print("Yesterday was Friday")

You will see that Python only prints ‘Today is Saturday’ and ignores everything else. Since Python ignores all text after the character ‘#,’ the part ‘print “Yesterday was Friday”’ is ignored.

There is only one exception to the rule as shown in the following code.

print("hello # I am not a comment") # I am a comment

If “#” is within the quotes of a valid string, it is not ignored. If you are unfamiliar with the word string, it is the computer science term for a set of characters. We describe string variables in section 5.

3.2.3 Summary of rules

  1. The ‘print’ keyword is used to print information on the screen.

  2. By default, each new ‘print’ statement prints its output in a different line. This behavior can be changed by adding a comma at the end of the statement.

  3. Any statement after ‘#’ is discarded, unless the ‘#’ is within the quotes of a valid string.

3.3 Mathematical Operations

Python can be used as a calculator to do simple mathematical operations. Try -

print(7+3*4)

print((4-3)*(22+7))

print(55%3)

print(2**8)

The mathematical operators ‘+,’‘-,’ ’*‘,’/’ perform addition, subtraction, multiplication and division respectively. Additional operators ’**’ is used for power and ‘%’ is used to get the remainer after a division.

Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
** Power

For more sophisticated mathematical operations, Python contains a separate math library with many useful functions. They are described in a later section.

3.4 Variables

3.4.1 Integer and Float Variables

Let us say you are calculating the tips for a bunch of restaurant bills, and do not like to type the number 0.15 again and again. Python’s variables allow you to save the number for future use. Code here -

tip=0.15

print(77*tip)
print(32.09*tip)
print(14*tip)
print(7.99*tip)

You can change the values of the variables any time in your code. For example, if you want the tip to be 15% for some bills and 12% for another set, you can easily do so. Here is an example.

tip=0.15
print(77*tip)
print(32.09*tip)

tip=0.12
print(14*tip)
print(7.99*tip)

3.4.2 Printing a Variable

Try -

x=1
print(x)
print("x")

The statement ‘x=1’ creates a variable named x and assigns it to 1. When you write a print statement with x within quote, Python prints the text ‘x’ on the screeen. However, if you remove the quote, Python prints the value of the variable x. Make sure x is defined, or otherwise Python will fail or give you an error.

Try -

x=1
print("the value of x is", x, "!!!")

If you remember from the first section, commas are used to print multiple things in the same line. Here we are using comma to print texts and variable in the same line.

Try -

i=1
j=1.0
print("i=", i, "j=", j)

Above code creates two types of variables - integer i and decimal j. They are treated differently in Python.

It is possible to reassign a variable from integer to decimal or back, as shown in the following code.

i=1
j=1.0
print("i=", i, "j=", j)

i=7.77
print("i=", i, "j=", j)

j=2
print("i=", i, "j=", j)
Operator Action
x += 10 x=x+10
x -= 10 x=x-10
x *= 10 x=x*10
x /= 10 x=x/10

3.4.3 Boolean Variables

Keyword Action
and logical ‘and’
or logical ‘or’
not logical ‘not’

Boolean Variables take only two values - True and False. Let us see an example -

#
# Logical(Boolean) variables have values True or False
#

x=7

y= x > 0
print(y)

z= x < 0
print(z)

The code in the second line checks whether x is greater than zero and saves the result True in the variable y. Similarly, z is assigned the value False based on the comparison.

Operator Action
x > y If x>y, True, otherwise False.
x >= y If x>=y, True, otherwise False.
x == y If x equals y, True, otherwise False.
x != y If x equals y, False, otherwise True.
x < y If x < y True, otherwise False.
x <= y If x <= y True, otherwise False.

3.4.4 String Variables

In computer science, the word ‘string’ is used to describe text or other collections of characters. Strings are important in biological data analysis, because DNA and protein sequences are written as them.

Python has a separate string variable as decribed in this section. String variables are different from numerical or boolean variables, because their subparts are often meaningful. For example, a program may need to identify the words from an entire paragraph of text stored as a string variable. Those words are the substrings of the original string.

Python’s representation of string variables helps in there easy manipulation. Let us take a look.

Try -

x='My name is Alice'
print(x)
print(x[0])
print(x[1])
print(x[4:6])

In the above example, x[0] is ‘M,’ x[1] is ‘y’ and x[2] is the space character.

3.4.4.1 Joining two strings

In Python, the operator ‘+’ for strings is redefined to join two strings.

Example -

a="Mac"
b="Donald"
print(a+b)

3.4.4.2 Splitting a string

You can also split a string by using indices to a part of the string.

Code -

x='I am flying from Seattle to San Francisco'
print(x[17:25])

3.5 Python is not Algebra

From time to time, you will write programs that do not make any algebraic sense. Let us give you some examples.

3.5.1 i=i+a

Try -

x=7
print(x)

x=x+10
print(x)

The statement ‘x=x+10’ is not an algebraic equation. In Python, the right hand side is calculated first and then the result is stored in the variable mentiond on the left hand side. Therefore, 11 is stored as the new value of x.

3.5.2 Integer Division

Try -

x=2
y=5
print(x/y)

You see 0 and not a decimal number. Python sees two integers in the computation, and therefore assumes that the result of the division should be converted to an integer.

To get decimal number as the result of division, you either need to make x=2.0 and y=5.0, or you need to use float function described in a later section.

x=2.0
y=5.0
print(x/y)

x=2
y=5
print(float(x)/float(y))

3.5.3 Exchanging numbers

Try -

#
# The following code does not exchange x and y.
#

x=1
y=5
x=y
y=x

print(x,y)

#
# The following code does
#

x=1
y=5
store=x
x=y
y=store

print(x,y)

The above code does not exchange x and y, because it operates line by line.

3.5.4 Addition of strings

Try -

a="Mac"
b="Donald"
print(a+b)

3.6 Lists

Keyword Action
in checks if an element is in a list or dictionary
del deletes an element from a list or dictionary

Try -

a=[1,3,2,0]
print(a[2])
print(a)

The variable ‘a’ is a list (or array). It has 4 entries with indices 0-3.

Try -

a=[1,3,2,0]
b=[2,3,1,7]
print(a+b)

You can use ‘+’ to concatenate two lists.

Try -

a=[1,3,4,9,6,2,0]
b=a[3:7]
print(b)

You can use ‘:’ to get sublist.

Try -

a=[1,3,4,9,6,2,0]
b=a[3:7:2]
print(b)

The above command gives a sublist from 3 to 7, skip 2.

Try -

a=[1,3,4,9,6,2,0]
b=a[::-1]
print(b)

The above command reverses the list.

3.6.1 Keyword ‘in’

a=[3,4,9,1]

print(3) in a
print(100) in a

3.6.2 Keyword - del

The keyword del is used to remove a list element at a known index.

x=['a','b','c','d']
del x[2]
print(x)

Try -

a=[1,3,4,9,6,2,0]
print(a)
del a[2]
print(a)

3.7 Keywords are Special Words

Keyword Action
print prints text on screen
and logical ‘and’
or logical ‘or’
not logical ‘not’
True logical True
False logical False
is tests equality
in checks if an element is in a list or dictionary
del deletes an element from a list or dictionary
if, else, elif conditional statement
while conditinal loop
for loop
continue skips current execution of loop
break quits the loop prematurely
def defines new function
return returns value at the end of function
from, import imports functions from file

3.7.1 Special words cannot be used as names

You cannot name variables (or functions) with these special words.

Bad code -

for = 1
in = 2
print(for + in)

3.8 Built-in Functions

All codes here.

3.8.1 Function - range()

The function range creates a list of integers.

print(range(3))
print(range(1,5))
print(range(1,5,2))

3.8.2 Function - len()

x=range(9,2,-2)
print(len(x))

In the following code, the variable i goes from 0 to 3, because len(a)=4.

a=[0,1,2,3]
print("loop using list indices")
for i in range(len(a)):
        print(i,"a[i]+8=",a[i]+8)

3.8.3 Function - float()

x=1
y=float(x)
print(x,y)

The function float converts an integer to a floating point number.

3.8.4 Function - int()

x=1.7
y=int(x)
print(x,y)

The function int gives the integer part of a floating point number.

3.8.5 Function - str()

x=723
y=str(x)
print(y[0])

The function str convers a number into a string.