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.
x = 5
type(x)Out [1] int
x = 3.14
type(x)Out [2] float
x = True
type(x)Out [3] bool
x = "CSC243"
type(x)Out [4] str
There are two main object types:
-
Scalar, cannot be decomposed:
int,float,bool, andNoneType(seen later) -
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.
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
first_number = 2.87E3
print(first_number)2870.0
second_number = 5.0
print(second_number)5.0
their_sum = first_number + second_number
print(their_sum)2875.0
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:
a = (8>3)
print(a)True
b = (2>3)
print(b)False
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(**).
x = 12.1
y = 4z = x + y
print(z)16.1
z = x - y
print(z)8.1
z = x*y
print(z)48.4
z = x/y
print(z)3.025
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 ofa//b -
modulo
%: returns the remainder for the division ofa/b. Note that it returns an integer which is at least0and at mostb-1. The modulo operator%does NOT return the decimal part of said division.
Let's try them out.
x = 12 #x is set to an intz = x//y
print(z)3
y = 5
z = x % y # x&y is the remainder of x/y
print(z)2
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.
print(z == y)False
print(z < y)True
print(z <= y)True
print(z > y)False
print(z != y) #not equal checkTrue
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.
x = True
y = Falsez = x and y
print(z)False
z = x or y
print(z)True
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:
x = 1
y = 2
z = ((7//2 + 3%2)*2 + y)/2 - 0.5*(x+1)**2
print(z)3.0
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:
-2*3/5+4*5Out [34] 18.8
is interpreted as:
(((-2)*3)/5) +(4*5)Out [35] 18.8
The following expression:
x>=1 and x<10 or x>=20 and x<20Out [36] True
is interpreted as:
((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:
first_string = 'Welcome to your first programming class:' #delimitation by ''
print(first_string)Welcome to your first programming class:
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:
my_string = first_string + second_string
print(my_string)Welcome to your first programming class:CSC243
my_string = first_string + " " + second_string
print(my_string)Welcome to your first programming class: CSC243
my_string = second_string*5
print(my_string)CSC243CSC243CSC243CSC243CSC243
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:
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.
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
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:
string_with_quotations = "\"This string contains double quotations\""
print(string_with_quotations)"This string contains double quotations"
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:
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.
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:
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.
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:
var1 = "Lebanese"
var2 = 'American'
var3 = "University"
print(var1, var2, var3)Lebanese American University
print(var1, var2, var3, sep = "\t")Lebanese American University
print(var1, var2, var3, sep = "*****")Lebanese*****American*****University
print(var1, var2, var3, sep = "-.-.-.-")Lebanese-.-.-.-American-.-.-.-University
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.
print("first")
print("second")
print("third")
print("fourth")first second third fourth
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:
x = 15.5
y = int(x)
print(y)15
x = "97"
y = int(x)
print(y)97
x = "-15.3"
y = float(x)
print(y)-15.3
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,
height = input("Please enter your height (in cms): ")Please enter your height (in cms): 175
print(height)175
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.
converted_height = int(height)
type(converted_height)Out [67] int
height = int(height)type(height)Out [69] int
Alternatively, we could convert the input immediately and using a single line:
height = int(input("Please enter your height (in cms): "))Please enter your height (in cms): 175
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.
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:
import mathNext, 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:
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:
from math import sqrtNow, we don't need to math. anymore to use it:
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