INTRODUCTION TO PYTHON
CS328 –PROGRAMMING LANGUAGES
DR. MANUEL LUIS C. DELOS SANTOS
About python
Development started in the 1980’s by Guido van Rossum.
Only became popular in the last 25 years or so.
Python is a general-purpose language.
Interpreted, very-high-level programming language. Considered to be higher
level than C++ or Java.
Supports a multitude of programming paradigms.
o OOP, functional, procedural, logic, structured, etc.
Very comprehensive standard library including numeric modules, cryptographic
services, OS interfaces, networking modules, GUI support, development tools, etc.
Notable features
Easy to learn.
Supports quick development.
Cross-platform.
Open Source.
Extensible.
Embeddable.
Useful for a wide variety of applications.
Getting started
Before you can begin, you need to have an environment to run Python programs (and write Python
programs).
In this class, we are going to use Python3 on linprog as our environment - all programming
assignments will be graded in this environment.
o On linprog, command ‘python3’ can run Python programs or give an interactive Python environment. The
Python version is 3.12.3.
If you choose another Python environment or IDE as your development and testing environment,
you must setup your python environment with Python 3.12.3 to avoid version related problems.
o On all platforms, you can install a Linux virtual machine and Python 3.12.3 to emulate linprog.
o If you are going to have your own development environment other than linprog, please do it now (Do not put
this off until your first assignment is due!).
Getting started
Besides the environment to run Python program, you also need a tool to write
Python programs.
o Any program that allows you to create text files can do the job.
Notepad++ on window; Editor on Mac; Vim, Emacs, Pico on Linux machines.
By this time, you should already have your favorite text editor or IDE.
There are also IDEs for Python available such as Pycharm that you can try.
As long as you can create and test Python programs, whatever you use to do it is
OK. But it is important that your final submissions are tested on linprog using
the ‘python3’ command before they are submitted.
Python Interpreter
The standard implementation of Python is interpreted.
The interpreter translates Python code into bytecode, and this bytecode is executed by
the Python VM (similar to Java).
Main differences between interpreted languages and compiled language:
o The timing when the source code is converted into the executable format: interpreted - during
execution .vs. compiled – before execution.
o How the source code is converted: interpreted - done every time the code is executed .vs. compiled
– done once.
Interpreted languages incur significant (time) overheads in program execution, but are
more flexible and programmer friendly.
o Example: If there is an error in execution, Python will tell you which line causes the error.
Python Interpreter
Two modes:
o Normal mode: Python files (.py) are provided to the interpreter for execution.
o Interactive mode: read-eval-print loop (REPL) executes statements piecewise.
Python Interpreter – Normal mode
Let us write the first Python program.
Create a file called [Link] with the following content
print(“Hello World!”)
Try command (in the linprog terminal) and see the output:
<linprog3:706> python3 [Link]
Python Interpreter – Normal mode
You can also include a #! string in the beginning of the .py file to make it an executable (to run
directly). Change [Link] with the following content, and add the execution permission to the
file
#!/usr/bin/env python3
print(“Hello World!”)
Or
#!/usr/bin/python3
print(“Hello World!”)
After that, try and see the output:
<linprog3:706> chmod +x [Link]
<linprog3:706> ./[Link]
Note: the she-bang line (#!/usr/bin/env python3) is system-dependent! It basically specifies the
path to python3, which can be install in different path in different systems. The example works on
linprog, but may not work on other systems.
Python Interpreter – Interactive Mode
$ python3
Let’s accomplish the same task >>> print ("Hello, World!“)
(and more) in interactive mode. Hello, World!
>>> hellostring = "Hello, World!"
Some options: >>> hellostring
'Hello, World!'
-c : executes single command. >>> 2*5
10
-O: use basic optimizations. >>> hellostring + “ “ + hellostring
‘Hello, World! Hello, World!'
-d: debugging info >>> for i in range(0,3):
print ("Hello, World!“)
Use exit() or quit() to get out of Hello, World!
Hello, World!
Python. Hello, World!
>>> exit()
$
Comments
Single-line comments use ‘#’ #
for i in range(0,3):
print (i)
Multi-line comments are enclosed def myfunc():
with three double quotes (“””). """Here is a comment about the
o Typically, multi-line comments are meant myfunc function. Type anything
for documentation. here. """
print ("In a function!“)
Comments should express
information that cannot be expressed
in code – do not restate code.
Python typing
Python is a strongly, dynamically typed language
Strong Typing
o Prevents mixing operations between mismatched types.
o Explicit conversions required to mix types.
o Example: 2 + ”four"
Dynamic Typing
o All type checking at runtime.
o No need to declare a variable or give it a type before use.
o See examples/lect1/[Link] and examples/lect1/[Link] to see difference between
static and dynamic typing.
Numeric Types
int, float and complex
Constructors: int(), float(), and complex()
int(), float(), support the typical numeric operations
Mixed arithmetic is supported, with the “narrower” type widened to that of the
other. The same rule is used for mixed comparisons.
For more information: [Link]
Numeric Types
int: equivalent to C++’s long $python
>>> 3 + 2
float: equivalent to C++’s doubles. 5
>>> 18 % 5
complex: complex numbers. 3
Supported operations include >>> abs(-7)
7
o constructors (i.e. int(3)), >>> float(9)
o arithmetic, 9.0
o negation, >>> int(5.3)
5
o modulus, >>> complex(1,2)
o absolute value, (1+2j)
>>> 2 ** 8
o exponentiation, etc
256
Sequence Data Types
All sequence data types support arrays of objects but with varying
limitations, each item has a particular index.
The most commonly used sequence data types are strings, lists, and tuples.
o Others sequence data types include Unicode strings, bytearrays, buffers, and ranged
objects.
o The ranged data type finds common use in the construction of enumeration-controlled loops.
o The others are used less commonly.
Sequence Types - Strings
Created by simply enclosing characters in either single- or double-quotes. It’s
enough to simply assign the string to a variable.
o aString = ‘strxng’ or aString = “strxng”
There are a tremendous amount of built-in string methods.
o str[i:j] is a substring from index i to index j (not included)
Strings in Python are immutable.
o How to change the ‘x’ to ‘i’ in aString above?
Sequence Types - Strings
Strings are immutable.
o aString = ‘strxng’
o How to change the ‘x’ to ‘i’ in aString above? aString[3] = ‘i’?
aString = aString[0:3] + ‘x’ + aString[4:6]
Strings
• Python supports several escape sequences such as ‘\t’, ‘\n’, etc.
• Placing ‘r’ before a string will yield its raw value (no escape sequence).
• Two string literals beside one another are automatically concatenated
together.
print(“\tHello\n”)
print(r“\tHello\n”)
print(“Python is ” “so cool.”)
Sequence Types – Unicode Strings
Unicode strings store and
manipulate Unicode data
myunicodestr1 = u"Hi Class!"
‘u’ create a normal string myunicodestr2 = u"Hi\u0020Class!"
print (myunicodestr1, myunicodestr2)
Use Unicode-Escape encoding newunicode = u'\xe4\xf6\xfc'
for special characters. print(newunicode)
newstr = [Link]('utf-8')
raw mode, use ‘ur’ as a prefix. print(newstr)
print([Link]('utf-8'))
.encode() method translates to
a regular string
Sequence Types – Lists
Lists are an incredibly useful mylist = [42, 'apple', u'unicode apple', 5234656]
compound data type print(mylist)
Lists can be initialized by the mylist[2] = 'banana'
constructor, or with a bracket print(mylist)
structure containing 0 or more mylist[3] = [['item1', 'item2'], ['item3', 'item4']]
elements. print (mylist)
print([Link]())
Lists are mutable – it is
mynewlist = [x*2 for x in range(0,5)]
possible to change their
print(mynewlist)
contents. They contain the
additional mutable
mylist = [4,1,3,2]
operations.
print(mylist)
Lists are nestable. Feel free to [Link]()
create lists of lists of lists… print(mylist)
Sequence Data Types
str: string, represented as a
sequence of 8-bit characters
mylist = ["spam", "eggs", "toast"] # List of strings!
unicode: stores an abstract print("eggs" in mylist)
sequence of code points. print(len(mylist))
list: a compound, mutable data mynewlist = ["coffee", "tea"]
type that can hold items of print(mylist + mynewlist)
varying types. mytuple = tuple(mynewlist)
tuple: a compound, immutable print(mytuple)
data type that can hold items of print([Link]("tea"))
varying types. Comma separated mylonglist = ['spam', 'eggs', 'toast', 'coffee', 'tea']
items surrounded by parentheses. print(mylonglist[2:4])
a few more – we’ll cover them
later.
COMMON SEQUENCE OPERATIONS
Operation Result
x in s True if an item of sis equal to x, else False.
x not in s False if an item of sis equal to x, elseTrue.
s+t The concatenation of s and t.
s * n, n * s n shallow copies of s concatenated.
s[i] ith item of s,origin 0.
s[i:j] Slice of s from i to j.
s[i:j:k] Slice of s from i to j with step k.
len(s) Length of s.
min(s) Smallest item of s.
max(s) Largest item of s.
[Link](x) Index of the first occurrence of x in s.
[Link](x) Total number of occurrences of x in s.
COMMON SEQUENCE OPERATIONS
Mutable sequence types further support the following operations.
Operation Result
s[i] = x Item i of sis replaced by x.
s[i:j] = t Slice of s from i to j is replaced by the
contents of t.
del s[i:j] Same as s[i:j] = [].
s[i:j:k] = t The elements of s[i:j:k] are replaced by those
of t.
del s[i:j:k] Removes the elements of s[i:j:k] from the list.
[Link](x) Add x to the end of s.
COMMON SEQUENCE OPERATIONS
Mutable sequence types further support the following operations.
[Link](x) Appends the contents of x to s.
[Link](x) Return number of i’s for which s[i] == x.
[Link](x[, i[, j]]) Return smallest k suchthat s[k] == x and
i <= k < j.
[Link](i, x) Insert x at position i.
[Link]([i]) Same as x = s[i]; del s[i]; return x.
[Link](x) Same as del s[[Link](x)].
[Link]() Reverses the items of s in place.
[Link]([cmp[, key[, reverse]]]) Sort the items of s in place.
Set
set: an unordered basket = ['apple', 'orange', 'apple', 'pear',
collection of unique objects 'orange']
frozenset: an immutable fruit = set(basket)
version of set print(fruit)
Some common print('orange' in fruit)
operations:
print('crabgrass' in fruit)
o Membership - obj in set
a = set('abracadabra')
o Union (|)
b = set('alacazam')
o Intersection (&)
print(a)
o Difference(-)
print(a - b)
print(a | b)
print(a & b)
Dict
dict: hash tables, maps a gradebook = dict()
set of keys to arbitrary gradebook['Susan Student'] = 87.0
print(gradebook)
objects.
gradebook['Peter Pupil'] = 94.0
print([Link]())
print([Link]())
print(gradebook.__contains__('Tina Tenderfoot'))
gradebook['Tina Tenderfoot'] = 99.9
print(gradebook.__contains__('Tina Tenderfoot'))
print(gradebook)
gradebook['Tina Tenderfoot'] = [99.9, 95.7]
print(gradebook)
Keyboard Input
Input in Python is done with the input() function. It can take a string prompt as a
parameter and returns a string. If we need to store the input as a different type,
we would have to cast it.
Eg:
X = int(intput(“enter a number: “))
Parallel Assignment
Parallel assignment specifies multiple assignments in one statement
o a, b = 100, 200
o x, y = a, b
o x, y, z = a, b, c
x, y, z, = a, b, c is semantically equivalent to
tmp = (a, b, c)
x = tmp[0]
y = tmp [1]
z = tmp[2]
Exercise: Swap the values of x, y.
Logical Expressions and Operators
Values: True, False
o Any non-zero is True; zero is False
Comparison operators are the same as those in C++
o >, >=, <, <=, ==, !=
Logical operators use words:
o and (&& in C++), or (|| in C++), and not (! In C++)
Examples:
o (100 > 200 ) or ((300 == 200) and not (400 == 20))
o not (100 > 200)
Control flow – while loop
While loops have the following general structure. i=1
While (i < 4):
while expression: print(i)
statements i=i+1
Flag = True
Here, statements refers to one or more lines of While flag and i < 6:
Python code. print(flag, i)
The conditional expression may be any i=i+1
expression, where any non-zero value is true. ----
Output:
The loop iterates while the expression is true. 1
Note: All the statements indented by the same 2
amount after a programming construct are 3
True4
considered to be part of a single block of
True5
code.
Whitespace in Python
Other languages such as C++, java
use {} or () to identify blocks of # here’s a comment
code. Whitespace does not matter in for i in range(0,3):
those languages print (i)
def myfunc():
"""here’s a comment about the
myfunc function"""
Python uses indentation to denote print ("In a function!“)
code blocks – same code blocks
MUST have the same indentation --
whitespace is significant in Python.
o See lect1/[Link] for example
Control flow - if
The if statement has the following
general form: a = 100
b=0
if a:
if expression: print(‘a is True’)
if not b:
statements print(‘b is False)
if a and b:
print(‘a and b is True’)
If the boolean expression evaluates if a or b:
print(‘a or b is True’)
to True, the statements are executed.
Otherwise, they are skipped entirely.
Control flow - if
You can also pair an else with an if
statement.
a,b,c = 10, 0, 5
if expression: if a > b:
statements if a > c :
else: print(‘a is the greatest’)
else
statements print(‘c is the greatest’)
print(‘a is True’)
The elif keyword can be used to elif b > c:
specify an else if statement. print(‘b is the greatest’)
Else:
Furthermore, if statements may be print(‘c is the greatest’)
nested within each other.
Control flow – for loop
The for loop has the following general form.
for var in sequence:
statements
o If a sequence contains an expression list, it is evaluated first.
o Then, the first item in the sequence is assigned to the iterating variable var.
o Next, the statements are executed.
o Each item in the sequence is assigned to var, and the statements are executed
until the entire sequence is exhausted.
o For loops may be nested with other control flow tools such as while loops and if
statements.
Control flow – for loop
Python has a handy function for creating a range of integers, typically used in for
loops.
This function is range()
It creates a sequence of integers, either statically or as they are needed
(depending on the length)
For I in range(0, 100):
print(i)
Control Flow Manipulating Statements
There are four statements provided for manipulating loop structures.
These are break, continue, pass, and else.
break: terminates the current loop.
continue: immediately begin the next iteration of the loop.
pass: do nothing. Use when a statement is required syntactically.
else: represents a set of statements that should execute when a loop terminates.
Let’s Write a Python Program
The program is from Project Euler (by Sharanya).
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be 1, 2, 3, 5, 8, 13, 21, 34,
55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed a
user inputted value N, find the sum of the even-valued terms.
END OF PRESENTATION
Thank you!