01-Introduction

ipynb45 kBPython · 115 cellsSlides of chapter 0

01 - Introduction to Python

Jupyter notebooks

This is a space where text and code come together to form a coherent document. Throughout the course, we will make use of Jupyter notebooks for illustration purposes and for experimentation.

Objects and Types

In a Python program, elements are 'objects'. Each object has a specific data-type.

Python guesses the data-type from the object initialization. Let's create a variable x that stores the integer 5 and experiment with it.

In [1]
x = 5
type(x)
Out [1] int
In [2]
x = 3.14
type(x)
Out [2] float
In [3]
x = True
type(x)
Out [3] bool
In [4]
x = "CSC243"
type(x)
Out [4] str

There are two main object types:

  1. Scalar, cannot be decomposed: int, float, bool, and NoneType (seen later)

  2. Non-Scalar, have internal structure: string, list, tuple, dict (last 3 seen later)

The int type

The int type is used to represent integers and has unlimited precision (bounded by memory restrictions of course). Example integers include:

  • negative numbers such as: -5, -71, etc.
  • non-negative numbers such as: 0, 12, 93801, etc.
In [5]
n = 313131000849184902084082114801
m = -n*n
print(m)
-98051023692812235870096431307055990841549671033408543269601

The float type

The float is used to represent real numbers, up to a certain precision (float stands for floating point number).

Note here that scientific notation can be used to express floats: 2870 = 2.87 * 1000 = 2.87E3

In [6]
first_number = 2.87E3
print(first_number)
2870.0
In [7]
second_number = 5.0
print(second_number)
5.0
In [8]
their_sum = first_number + second_number
print(their_sum)
2875.0
In [9]
print(their_sum*2)
5750.0

The binary representation of floats uses 64 bits, hence 8 bytes of memory: 1 bit is for the sign, 52 bits are the significant part (a.k.a the mantissa), 11 remaining bits to represent the exponent.

The bool type

Used to represent Boolean/logical values: True and False. In Python, True and False are keywords (i.e., cannot be used as variable names).

Boolean values originate from logical tests, such as the below code:

In [10]
a = (8>3)
print(a)
True
In [11]
b = (2>3)
print(b)
False
In [12]
c = not b
print(c)
True

Arithmetic Operators

The arithmetic operators for the int and float types include the following: Addition (+), Subtraction (-), Multiplication (*), Division(/), Power(**).

In [13]
x = 12.1
y = 4
In [14]
z = x + y
print(z)
16.1
In [15]
z = x - y
print(z)
8.1
In [16]
z = x*y
print(z)
48.4
In [17]
z = x/y
print(z)
3.025
In [18]
z = x**y
print(z)
21435.888099999996

Except for division /, if both x and y are of type int, the result is an int. In all other cases, the result is a float.

All above are binary arithmetic operators: they take in two operands. There exists the unary operator minus -: -x is the negative of x.

There are also operators specific to the int data-type:

  • integer division //: keeps the integer part of the division of a//b

  • modulo %: returns the remainder for the division of a/b. Note that it returns an integer which is at least 0 and at most b-1. The modulo operator % does NOT return the decimal part of said division.

Let's try them out.

In [19]
x = 12 #x is set to an int
In [20]
z = x//y
print(z)
3
In [21]
y = 5
z = x % y # x&y is the remainder of x/y
print(z)
2
In [22]
y = 3 
z = x % y 
print(z)
0

Relational Operators

Relational operators are binary operators that evaluate the relationship between two inputs, and output a truth value (i.e., bool). For example, the < operator evalues if a number is less than another. The == operator checks if two operands are the same. The != operator checks if two operands are different.

Below are the possibilites.

In [23]
print(z == y)
False
In [24]
print(z < y)
True
In [25]
print(z <= y)
True
In [26]
print(z > y)
False
In [27]
print(z != y) #not equal check
True

Logical (bool) Operators

Logical operators accept booleans only as their inputs and -- like relational operators -- return a boolean. The general format is: x operator y --> z; where x, y, and z are all boolean.

In [28]
x = True
y = False
In [29]
z = x and y
print(z)
False
In [30]
z = x or y
print(z)
True
In [31]
z = not y
print(z)
True

Expressions

An expression is made up of operators, values and/or variables. An expression can combine more than one operator to form something advanced.

Examples:

In [32]
x = 1
y = 2
z = ((7//2 + 3%2)*2 + y)/2 - 0.5*(x+1)**2
print(z)
3.0
In [33]
not ((x + 2>0) and (x+2) <= 10) or (x==50)
Out [33] False

Order of precedance

In Python, some operators take precedence over others (i.e., they get executed before others).

In general, a good way to remember the precedence of operators is to memorize the PEMDAS acronym. PEMDAS stands for Parenthesis, Exponentiation, Multiplication, Division, Addition, Subtraction. Accordingly, precedence is in this order.

In Python, PEMDAS is followed by 'Relational operators', not, and, and finally the or operator.

Some examples below:

The following expression:

In [34]
-2*3/5+4*5
Out [34] 18.8

is interpreted as:

In [35]
(((-2)*3)/5) +(4*5)
Out [35] 18.8

The following expression:

In [36]
x>=1 and x<10 or x>=20 and x<20
Out [36] True

is interpreted as:

In [37]
((x>=1) and ( x<10)) or ((x>=20) and(x<20))
Out [37] True

The str data-type

A string is a sequence of characters delimited by either a singles quotations ' or double quotations ". For instance, the below are strings:

In [38]
first_string = 'Welcome to your first programming class:' #delimitation by ''
print(first_string)
Welcome to your first programming class:
In [39]
second_string =  "CSC243" #delimiation by ""
print(second_string)
type(second_string)
CSC243
Out [39] str

Concatenation and repetition

Strings can be concatenated (put next to each other), repeated, and their length examined. Consider the following code snippets:

In [40]
my_string = first_string + second_string
print(my_string)
Welcome to your first programming class:CSC243
In [41]
my_string = first_string + " " + second_string
print(my_string)
Welcome to your first programming class: CSC243
In [42]
my_string = second_string*5
print(my_string)
CSC243CSC243CSC243CSC243CSC243
In [43]
x = len(my_string)
print(x)
30

Accessing the characters in a string (using [] )

We can access a specific character in a string using the access operator []. For instance, we can get the first characater by typing in:

In [44]
st = "LAU"

first_character = st[0]
middle_character = st[1]
last_character = st[-1]

print(first_character, middle_character, last_character)
L A U

Output to the console, using print()

As we have already seen, to output to the console the contents of variables we make use of the built-in Python function print(). For example, we have in the below a variable called y with contents equal to the float 5.0.

In [45]
y = 5.0
print(y)
5.0

The print() function takes as input a variable name as in the above, and outputs the value as a string. Alterntively, print() can take in as input a string, and output a string. For example

In [46]
print("This string will be printed")
This string will be printed

Note how the quotations in the string were not displayed; just the actual sequence of characters. If we want our string to contain quotations, we need to make use of the special backslash character \ and follow it with single or double quotations. Here, we have:

In [47]
string_with_quotations = "\"This string contains double quotations\"" 
print(string_with_quotations)
"This string contains double quotations"
In [48]
string_with_quotations = "\'This string contains single quotations\'" 
print(string_with_quotations)
'This string contains single quotations'

There are other special characters, called escape sequences, that are especially useful for formatting a string to our taste. For example, if we want to go to a newline, we use the \n escape sequence. To insert a tab, we use the \t escape sequence.

Some examples:

In [49]
my_string = "This is line one.\nThis is line two." #notice the effect of the space between \n and This
print(my_string)
This is line one.
This is line two.
In [50]
my_string = "This\tsentence\tis\ton\ta\tsingle\tline."
print(my_string)
This	sentence	is	on	a	single	line.

The built-in print() function can also take multiples inputs. The result will be printed using the default seperator (a white-space ) and default line-ending character (a newline \n). For example, if we have 3 variables with different contents:

In [51]
var1 = "The speed is equal to"
var2 = 56.1
var3 = "meters per second."
print(var1, var2, var3)
The speed is equal to 56.1 meters per second.
In [52]
x = 1.0
y = 2.3
print("The variable x =", x, "and y =", 2.3)
print("The variable x = " + str(x) + " and y = " + str( 2.3))
The variable x = 1.0 and y = 2.3
The variable x = 1.0 and y = 2.3

Notice how var2, x, and y -- whose contents are float -- were converted to str and inserted in their proper order.

Also, note how a space is separating the contents of var1, var2, and var3. We can change the default separator to any other string by specifying the separator parameter as in the below:

In [53]
var1 = "Lebanese"
var2 = 'American'
var3 = "University"
print(var1, var2, var3)
Lebanese American University
In [54]
print(var1, var2, var3, sep = "\t")
Lebanese	American	University
In [55]
print(var1, var2, var3, sep = "*****")
Lebanese*****American*****University
In [56]
print(var1, var2, var3, sep = "-.-.-.-")
Lebanese-.-.-.-American-.-.-.-University
In [57]
print(var1, var2, var3, sep = " | ")
Lebanese | American | University

Finally, we can specify the end parameter for print as well. By default, it is set to \n and consecutive prints will be each displayed on a new line.

In [58]
print("first")
print("second")
print("third")
print("fourth")
first
second
third
fourth
In [59]
print("first", end="\t")
print("second", end="\n")
print("third", end="\t")
print("fourth")
print("fifth", end="")
print("\tsixth")
first	second
third	fourth
fifth	sixth

Data-type conversion (Casting)

The int() function converts to an integer, whenever possible. The float() function converts to a decimal number, whenever possible. The str() function converts to a string.

Examples:

In [60]
x = 15.5
y = int(x)
print(y)
15
In [61]
x = "97"
y = int(x)
print(y)
97
In [62]
x = "-15.3"
y = float(x)
print(y)
-15.3
In [63]
x = 97.8
y = str(x)
print(y)
print(y + y)
97.8
97.897.8

Input from the keyboard

The built-in input function displays a message to the user, who will input something. Then, the input is stored in a variable as a string. For instance,

In [64]
height = input("Please enter your height (in cms): ")
Please enter your height (in cms): 175
In [65]
print(height)
175
In [66]
type(height)
Out [66] str

The variable height stores the value as a string. Hence, it must be converted to an integer using the int() function.

In [67]
converted_height = int(height)
type(converted_height)
Out [67] int
In [68]
height = int(height)
In [69]
type(height)
Out [69] int

Alternatively, we could convert the input immediately and using a single line:

In [70]
height = int(input("Please enter your height (in cms): "))
Please enter your height (in cms): 175
In [71]
type(height)
Out [71] int

The conversion to integer is necessary here since we might need to perform calculations using the input value later.

Our first program: Swapping two values

This first program will illustrate input from the keyboard, variables, escape characters, casting, and output.

In [72]
a = input("Enter the first integer: ")
a = int(a)
b = input("Enter the second integer: ")
b = int(b)
## perform swapping, need a temporary variable
temp = a
a = b
b = temp
print("\n")
print("The first integer is now:", a)
print("The second integer is now:", b)
print("\nThis concludes our first code.")
Enter the first integer: 3
Enter the second integer: 7


The first integer is now: 7
The second integer is now: 3

This concludes our first code.

Importing modules

Often times, there are functions that we might need to import from modules. Such examples include mathematical functions like cos, sin, exp, etc. Other examples include modules that allow for plotting.

In the below code, we will examine the math module. First, we import it:

In [73]
import math

Next, say we need to use square-root function sqrt. We must specify to Python that it is being retrieved from the math module by using the member access . operators; as in the below:

In [74]
x = float(input("Enter an integer: "))
y = math.sqrt(x)
print("The square-root of", x, "is", y)
Enter an integer: 16
The square-root of 16.0 is 4.0

Alternatively, we can import just the sqrt method by typing in:

In [75]
from math import sqrt

Now, we don't need to math. anymore to use it:

In [76]
x = float(input("Enter an integer: "))
y = sqrt(x)
print("The square-root of", x,"is", y)
Enter an integer: 25
The square-root of 25.0 is 5.0
In [77]