Python Lab 2nd Stage
By: Sarah N. Almeer 1
Python Lab 2nd Stage
Introduction
Python is an easy to learn, powerful programming language. It has efficient high-
level data structures and a simple but effective approach to object-oriented
programming. Python’s elegant syntax and dynamic typing, together with its
interpreted nature, make it an ideal language for scripting and rapid application
development in many areas on most platforms.
What is Python?
Python is a popular programming language. It was created by Guido van Rossum,
and released in 1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software
development.
By: Sarah N. Almeer 2
Python Lab 2nd Stage
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc.)
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a
functional way.
Good to know
The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated with
anything other than security updates, is still quite popular.
In this tutorial Python will be written in a text editor. It is possible to write
Python in an Integrated Development Environment, such as Thonny,
Pycharm , Netbeans or Eclipse which are particularly useful when managing
larger collections of Python files.
Python Syntax compared to other programming languages
Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose.
By: Sarah N. Almeer 3
Python Lab 2nd Stage
Execute Python Syntax
As we learned in the previous page, Python syntax can be executed by writing
directly in the Command Line:
>>> print("Hello, World!")
Hello, World!
Python Variables
In Python, variables are created when you assign a value to it:
Example
x=5
y = "Hello, World!"
Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
Example
#This is a comment.
print("Hello, World!")
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments can be placed at the end of a line, and Python will ignore the rest
of the line
By: Sarah N. Almeer 4
Python Lab 2nd Stage
Example
print("Hello, World!") #This is a comment
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even
change type after they have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
By: Sarah N. Almeer 5
Python Lab 2nd Stage
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type
You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?
String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a
By: Sarah N. Almeer 6
Python Lab 2nd Stage
Exercise?
What is a correct way to declare a Python variable?
var x = 5
#x = 5
$x = 5
x=5
Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different
variables)
A variable name cannot be any of the Python keywords.
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
By: Sarah N. Almeer 7
Python Lab 2nd Stage
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Python - Output Variables
Output Variables
The Python print() function is often used to output variables.
Example
x = "Python is awesome"
print(x)
By: Sarah N. Almeer 8
Python Lab 2nd Stage
In the print() function, you output multiple variables, separated by a comma:
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Notice the space character after "Python " and "is ", without them the result would
be "Pythonisawesome".
For numbers, the + character works as a mathematical operator:
Example
x=5
y = 10
print(x + y)
In the print() function, when you try to combine a string and a number with
the + operator, Python will give you an error:
Example
x=5
y = "John"
print(x + y)
The best way to output multiple variables in the print() function is to separate
them with commas, which even support different data types:
Example
By: Sarah N. Almeer 9
Python Lab 2nd Stage
x=5
y = "John"
print(x, y)
Exercise?
Consider the following code:
print('Hello', 'World')
What will be the printed result?
Hello, World
Hello World
HelloWorld
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different
things.
Python has the following data types built-in by default, in these categories:
Text Type: Str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: Dict
Set Types: set, frozenset
Boolean Type: Bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
By: Sarah N. Almeer 10
Python Lab 2nd Stage
Getting the Data Type
You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x:
x=5
print(type(x))
Setting the Data Type
In Python, the data type is set when you assign a value to a variable
Example Data Type
x = "Hello World" str
x = 20 Int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
By: Sarah N. Almeer 11
Python Lab 2nd Stage
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
By: Sarah N. Almeer 12
Python Lab 2nd Stage
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor
functions:
Example Data Type
x = str("Hello World") Str
x = int(20) Int
x = float(20.5) Float
x = complex(1j) Complex
x = list(("apple", "banana", "cherry")) List
x = tuple(("apple", "banana", "cherry")) Tuple
x = range(6) Range
x = dict(name="John", age=36) Dict
By: Sarah N. Almeer 13
Python Lab 2nd Stage
x = set(("apple", "banana", "cherry")) Set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Exercise?
If x = 5, what is a correct syntax for printing the data type of the variable x?
print(dtype(x))
print(type(x))
print(x.dtype())
By: Sarah N. Almeer 14
Python Lab 2nd Stage
Python Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example
Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Example
By: Sarah N. Almeer 15
Python Lab 2nd Stage
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')
Python Booleans
Booleans represent one of two values: True or False.
When you compare two values, the expression is evaluated and Python returns
the Boolean answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
When you run a condition in an if statement, Python returns True or False:
Example
Print a message based on whether the condition is True or False:
a = 200
b = 33
if b > a:
By: Sarah N. Almeer 16
Python Lab 2nd Stage
print("b is greater than a")
else:
print("b is not greater than a")
Append Items
To add an item to the end of the list, use the append() method:
Example
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Remove Specified Item
The remove() method removes the specified item.
Example
Remove "banana"
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Example
Remove the first occurrence of "banana":
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)
The del keyword also removes the specified index:
Example
Remove the first item:
By: Sarah N. Almeer 17
Python Lab 2nd Stage
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
The del keyword can also delete the list completely.
Example
Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist
Clear the List
The clear() method empties the list.
The list still remains, but it has no content.
Example
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Loop Through a List
You can loop through the list items by using a for loop:
Example
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
By: Sarah N. Almeer 18
Python Lab 2nd Stage
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements"
and loops.
An "if statement" is written by using the if keyword.
Example
a = 33
b = 200
if b > a:
print("b is greater than a")
Python Loops
Python has two primitive loop commands:
while loops
for loops
The while Loop
With the while loop we can execute a set of statements as long as a condition is
true.
Example
Print i as long as i is less than 6:
By: Sarah N. Almeer 19
Python Lab 2nd Stage
i=1
while i < 6:
print(i)
i += 1
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more
like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
By: Sarah N. Almeer 20
Python Lab 2nd Stage
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
By: Sarah N. Almeer 21
Python Lab 2nd Stage
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x–y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
By: Sarah N. Almeer 22
Python Lab 2nd Stage
Python Comparison Operators
Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal x >= y
to
<= Less than or equal to x <= y
By: Sarah N. Almeer 23
Python Lab 2nd Stage
Python Logical Operators
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true
Logical operators are used to combine conditional statements
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they
are actually the same object, with the same memory location:
Operator Description Example
is Returns True if both variables are the same x is y
object
By: Sarah N. Almeer 24
Python Lab 2nd Stage
is not Returns True if both variables are not the same x is not y
object
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name Description Example
& AND Sets each bit to 1 if both bits are 1 x&y
| OR Sets each bit to 1 if one of two bits is 1 x|y
^ XOR Sets each bit to 1 if only one of two bits is 1 x^y
~ NOT Inverts all the bits ~x
<< Zero fill Shift left by pushing zeros in from the right and x << 2
left shift let the leftmost bits fall off
>> Signed Shift right by pushing copies of the leftmost bit in x >> 2
right shift from the left, and let the rightmost bits fall off
By: Sarah N. Almeer 25
Python Lab 2nd Stage
Example
Multiplication * has higher precedence than addition +, and therefor
multiplications are evaluated before additions:
print(100 + 5 * 3)
The precedence order is described in the table below, starting with the highest
precedence at the top:
Operator Description
() Parentheses
** Exponentiation
+x -x ~x Unary plus, unary minus, and bitwise NOT
* / // % Multiplication, division, floor division, and modulus
+ - Addition and subtraction
<< >> Bitwise left and right shifts
By: Sarah N. Almeer 26
Python Lab 2nd Stage
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is Comparisons, identity, and membership operators
not in not in
not Logical NOT
and AND
or OR
If two operators have the same precedence, the expression is evaluated from left
to right.
Example
Addition + and subtraction - has the same precedence, and therefor we evaluate the
expression from left to right:
print(5 + 4 - 7 + 3)
By: Sarah N. Almeer 27
Python Lab 2nd Stage
Exercise?
What will be the result of the following syntax:
x=5
x += 3
print(x)
3
5
8
By: Sarah N. Almeer 28