Python Basics

This section provides a brief overview of:

  • Data types in python
  • Comparison operators
  • Variables
  • Conditional statements - If and While loops

Data Types

In this section I am going to focus on integer, floating points, Boolean data types and associated arithmetic operations. 5 is an example of an integer data type whereas 5.0, 6.2 are examples of floating point data types. Note that python also has a string data type which is not covered in this tutorial.

All standard arithmetic operators are defined in Python.

In [1]:
3 + 2
Out[1]:
5
In [2]:
3 - 1
Out[2]:
2
In [3]:
3 / 2
Out[3]:
1.5
In [4]:
3 // 2 # Integer division
Out[4]:
1
In [5]:
3 ** 2 # 3 to the power of 2
Out[5]:
9
In [6]:
3 % 2 # This is the remainder operator
Out[6]:
1
In [7]:
float(5) # Returns a floating point number
Out[7]:
5.0
In [8]:
int(5.6) # Returns an integer
Out[8]:
5

Try the following mathematical operations. Are you getting the answer you are expecting?

In [9]:
(1/49)*49
Out[9]:
0.9999999999999999
In [10]:
0.1 + 0.1 + 0.1 == 0.3
Out[10]:
False

This is because, floating points are represented as binary fractions. For example, 0.25 is represented as 0.01 $\left( 0 \times \frac{1}{2} + 1 \times \frac{1}{4}\right)$. Decimal number 0.1 cannot be accurately represented as binary fractions which results in the above issues.

Comments

Python treats every line as a statement to be executed except the line beginning with a #. # indicates the line contains comments to the right of # sign which are not to be executed. Take the time to write good comments.

In [11]:
# This is a comment	
x = 10 # We assign variable x value 10. This is a poor comment.
x = 10 # The initial solution is 10. This is a good comment.

Comparison Operators

Python has the following comparison operators on all relevant data types:

  • == equal to
  • != not equal to
  • < less than
  • <= less than or equal to
  • > greater than
  • >= greater than or equal to

Boolean is another data type which can take two values – true or false. Python comparisons can be combined using the and, or keyword.

In [12]:
3 == 2
Out[12]:
False
In [13]:
3 != 2
Out[13]:
True
In [14]:
(5 > 3) and (2 < 1)
Out[14]:
False
In [15]:
(5 > 3) or (2 < 1)
Out[15]:
True
In [16]:
not(3 == 2)
Out[16]:
True

Variables

In Python, there is no need to declare variables before assigning them. Variables are references to object. Variable type depends on object type.

In [17]:
x = 5 # Assigns 5 to an integer variable x
print(x)
5
In [18]:
type(x)
Out[18]:
int
In [19]:
y = 5.2 # Assigns 5.2 to a floating point variable y
print("y = ", y)
y =  5.2
In [20]:
type(y)
Out[20]:
float

You can assign multiple variables in a single line.

In [21]:
a, b = 10, 22.3
print(a)
print(b)
10
22.3
In [22]:
x + y
Out[22]:
10.2
In [23]:
float(x) # converts to floating point
Out[23]:
5.0
In [24]:
int(y) # converts to integer
Out[24]:
5
In [25]:
type(x) #prints the variable type
Out[25]:
int

When you run the command x = 5, you are creating a variable x which is a reference to an integer object 5. Variable x is a reference to the memory location containing integer object 5.

In [26]:
x = 5
y = 5

When you run the above command you are creating two references to the memory location containing integer object 5.

Variable and References

In [27]:
x = x + 5

Once you update x as shown above, the variable references changes.

Variable and References

Some rules on variable names.

  • Variable name must start with letter or _ .
  • The remainder of the variable name can be combination of letters, numbers, and underscores.
  • Variable names are case sensitive. Therefore, Velocity is different from velocity.
  • Do not use reserve keywords such as and not if else class while import try.
  • Get into the habit of using descriptive variable names.
  • Avoid using lower case letter l (el), uppercase letter O, upper case letter I (eye) as single character variable name.

Naming conventions are provided at PEP 8 Python Style Guide.

Conditional Statements

If loops can be used to execute codes based on conditions.

Note that indentations are important for defining code blocks. Normal indentation is one tab or four whitespaces. The code will not compile properly and give errors if it is not indented properly. Watch out for the colons.

In [28]:
x = 10
y = 20
if x < y:
    print(x, "is smaller")
else:
    print(y, "is smaller")
10 is smaller

You can check as many logical conditions as needed using if, elif, and else.

In [29]:
x = 10
print(x)
if x > 5:
    print("x is larger than 5")
elif x < 5:
    print("x is smaller than 5")
else:
    print("x is equal to 5")
10
x is larger than 5

You can nest if loops.

In [30]:
x = 5
y = 15
z = 25
if x < y:
    if x < z:
        print(x, "is the smallest")
    else:
        print(z, "is the smallest")
else:
    if y < z:
        print(y, "is the smallest")
    else:
        print(z, "is the smallest")
5 is the smallest

While loops execute a section of code until a logical condition is met. The following code prints 1 through 10.

In [31]:
y=0
while y <= x:
    print(y)
    y=y+1
0
1
2
3
4
5

We can combine logical conditions using and, not.

In [32]:
count = 0
total = 0
while count <= 10 and count % 2 == 0:
    total = total + count
    count = count + 1
print(total)
0

We can combine if and while loops also.

In [33]:
count = 0
total = 0
while count <= 10:
    if count%2 == 0:
        total = total + count
    count = count + 1
print(total)
30

The break statement allows you to exit a loop if an additional constraint is satisfied.

In [34]:
count = 1
total = 0
while count <= 10:
    if count % 5 == 0:
        break
    total = total + count
    count = count + 1
print(total)
10

The continue statement returns the control to the beginning of the while loop.

In [35]:
count = 0
total = 0
while count < 10:
    count = count + 1
    if count % 2 == 0:
        continue
    total = total + count
print(total)
25