Lec01 Introduction
Lec01 Introduction
Introduction to
Python
Lecture 1: Introduction
2022-23 Term 2
By Dr. King Tin Lam
1
Outline
• Background
• Computer Programming
• Programming Languages
• What’s Python
• Python Programming and Execution Environments
• Your First Python Program
• A Quick Overview of Python Programming
2
Computer Programming
• Realize the algorithms designed.
• Talking to the computer, you need to learn its language!
Add 2 Confused!
to 3
Modern computers
“talk” in 0 and 1 only.
• Procedural or Structural
• C, COBOL, Ada, Pascal, Basic
• Object-Oriented (OO)
COBOL: Pascal: C Language:
• C++, Java, C#, VB.NET Grace Murray Niklaus Wirth Dennis Ritchie
Hopper
5
Code Translation
Compilers, interpreters and assembler are computer
High programs to do translation from one language to another
Level
High Level Language
Assembly Language
Assembly Language
Compilation
Question:
Compiled languages vs. interpreted
languages – which runs faster in general?
8
Compilers vs. Interpreters
9
Tiobe Index (as of July 2022)
• Python is now the world’s number one in popularity.
Source: https://www.tiobe.com/tiobe-index/
Python
10
11
The Python
Programming
Language
History, Python Versions, Why Python?
Python Development
What is Python
• Python is an interpreted, high-level, general-purpose programming
language.
• Created by Guido van Rossum at National Research
Institute for Mathematics and Computer Science
in Netherlands and first released in 1991.
• Why was it called “Python”?
• He doesn't particularly like snakes that kill animals
for food by winding their long bodies around them
and crushing them.
12
Python: The Origin of Its Name
• The language was named after Monty Python’s Flying Circus – a BBC
TV sketch comedy series broadcasted from 1969 to 1974.
13
Development History
• Python was conceived in the late 1980s as a successor to the ABC language.
Python 2.0, released in 2000, introduced features like list
comprehensions and a garbage collection system with reference counting.
• Python 3.0, released in 2008, was a major revision of the language that is
not completely backward-compatible, and much Python 2 code does not
run unmodified on Python 3.
• The Python 2 language was officially discontinued in 2020 (first planned for
2015), and "Python 2.7.18 is the last Python 2.7 release and therefore the
last Python 2 release." No more security patches or other improvements
will be released for it. With Python 2's end-of-life, only Python 3.5.x and
later are supported.
14
Python’s Design Goals
• Python's design philosophy emphasizes code readability with its notable
use of significant whitespace.
• Its language constructs and object-oriented approach aim to
help programmers write clear, logical code for small and large-scale
projects.
• Python is dynamically typed and garbage-collected.
• It supports multiple programming paradigms, including structured
(particularly, procedural), object-oriented, and functional programming.
• Python is often described as a "batteries included" language due to its
comprehensive standard library.
15
Python’s Pros and Cons
Pros Cons
• Simple, short, easy to learn • Slow (compared to C/C++)
• Architecture neutral • High memory consumption
• Object-oriented
• Garbage-collecting
• Multithreaded
• Extensible
17
Python’s Portability
• Python compiler converts
Python Program Python program into bytecode
which is platform independent.
Python Compiler
Platform
• Python bytecode is then
Python Bytecode Independent interpreted by the Python
code
Interpreter or compiled on the
fly by the JIT (Just-in-Time)
PVM PVM PVM
compiler to hardware-specific
Interpreted or
machine code.
compiled just
in time
• PVM = Python Virtual Machine
Machine
Code
Machine
Code
Machine
Code
(It is actually a system program
for code translation.)
18
Python Implementations
• Python is a language (specification).
• A language specification can have different implementations (i.e. how
the bytecode compiler and the PVM are built).
19
Python Implementations
• Alternative implementations include:
• IronPython (Python running on .NET)
• Jython (Python running on the Java Virtual Machine)
• PyPy (A fast python implementation with a JIT compiler)
• Pyjion (with a JIT derived from Microsoft's CoreCLR)
• Stackless Python (Branch of CPython supporting microthreads)
• MicroPython (Python running on micro controllers)
20
Python 2 is sunsetting!
The sunset date has passed; it was January
Python 2 vs. Python 3 1st, 2020. No more support for it.
https://www.python.org/doc/sunset-python-2/
Division of Integers Whenever two integers When two integers are divided,
Always use
are divided, you get a you always provide integer Python3!
float value value.
24
For Anaconda or Miniconda, its NumPy package
(installed via conda) is based on Intel's Math
Choices of Installation Kernel library (MKL) and runs a bit faster.
• Each option has its own advantages and limitations; it may depend on how
familiar you are with programming.
• Option 1 is the simplest and perhaps good for totally new beginners to
concentrate on learning programming. Latest Python version: 3.10
• Option 2 is suitable for those who want to explore more features.
• It includes a GUI called Anaconda-Navigator which may appear more friendly for
beginners. But the software is bulky and requires 5 to 6 GB.
• Latest Python version: 3.9
• Option 3 requires about 400 MB only; a good tradeoff between features
and space. Recommended for most users.
• Latest Python version: 3.9
• You can install Anaconda-Navigator manually afterwards.
25
Basic Python Installation
• To install Python, the simplest steps are:
• Go to https://www.python.org
• Go to "Downloads” and click the button to download the latest version for
your OS.
• Run the installer.
26
Anaconda
• Anaconda is a distribution of Python and R programming languages
for data science and machine learning tasks.
• Individual Edition is free and open-source.
27
Anaconda or Official Python?
• Pros of Anaconda:
• Faster than vanilla Python: they bundle Intel MKL (Math Kernel Library) and
this does make most (NumPy) computations faster.
• You can easily do a local user install, no need to ask permission from your
admin in many cases.
• Cons of Anaconda:
• Perhaps too bloated (taking up several GBs of disk space).
29
Virtual Environment
• Different Python projects may have dependencies on the same
package but in different versions.
• They should be contained in their own isolated, virtual environments
to avoid affecting each other.
• With Virtualenv or conda, you can install Python packages locally in a
virtual environment instead of globally which could break system
tools or other projects.
30
What's Conda and Why Conda
• Conda is an open-source package management system and
environment management system.
• Conda quickly installs, runs and updates packages and their dependencies.
• Conda easily creates, saves, loads and switches between environments on
your computer.
• It can manage packages written not only in Python but other languages too.
• Conda can be used to create isolated virtual environments.
• Useful when you need Python 3.9 and legacy Python 3.5 on the same PC.
• So, each software project can have its own set of dependencies, regardless of
the dependencies in another project.
31
Running Miniconda
• Click "Anaconda Prompt (miniconda3)" from Windows Start Menu.
• You will directly enter the base Python shell environment.
• Typing "conda" shows the
3
command list.
1
32
Running Miniconda
• Type "python -V" or "python --version" to check the Python version.
• Type "python" or "python3" to enter the Python shell (interpreter).
• In the shell, you can type and run Python statements.
33
Running Miniconda
• Or open a command prompt (press Win + R, type "cmd", enter)
• Type "conda activate base" to enter the base environment.
• Type "python" to enter the Python shell.
34
Launching Python (from Command Line)
• To launch an interactive Python shell, type
python or python3
35
REPL - Python Interactive Shell
• You will enter an REPL (Read-Eval-Print-Loop) – an interactive Python
shell environment with the prompt ">>>".
• In this environment, you can write Python code.
• To exit the REPL environment, type exit().
(base) C:\Users\KingTin>python
Python 3.9.1 (default, Dec 11 2020, 09:29:25) [MSC v.1916 64 bit (AMD64)] ::
Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World!")
Hello World!
>>> exit()
(base) C:\Users\KingTin>
36
Running a Python Script
• Besides coding in an REPL shell, you can also write all the Python code
in a text file using any text editor or IDE.
print('Hello, world!')
• Give the source file a name with .py extension.
hello_world.py
37
Online Python Compilers
• Some online Python coding platforms are available for use without
the need of installation.
• Examples:
•
URL: https://www.programiz.com/python-programming/online-compiler/
•
URL: https://repl.it/languages/python3
38
Python IDEs
• IDLE – the default IDE for standard Python installation
• PyCharm (CE / Pro) – a professional IDE for Python by JetBrains
• Spyder – the default IDE coming along with Anaconda
• PyDev – a third-party Python editor for Eclipse
• Visual Studio – Microsoft's Full-featured IDE
• VS Code (Win, Mac, Linux) or VS Community Ed. (Win only) both do
• Install the Python extension
• You may also use code editors like Atom, Sublime Text 3, etc.
https://www.guru99.com/python-ide-code-editor.html
39
REPL - Python Interactive Shell
• You will enter an REPL (Read-Eval-Print-Loop) – an interactive Python
shell environment with the prompt ">>>".
• In this environment, you can write Python code like entering
commands in a Unix shell, except that you still need to observe code
indentation requirements properly.
• To exit the REPL environment, type exit().
kingtin$ python
Python 3.7.4 (v3.7.4:e09359112e, Jul 8 2019, 14:54:52)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!
>>> exit()
40
Running a Python Script
• Besides coding in an REPL shell, you can also write all the Python code
in a text file using any IDE or text editor, give the source file a name
with .py extension, and type the following command to execute the
script file:
kingtin$ python hello_world.py
Hello, World!
• You need not type exit() in your script if you don't want to
terminate the program prematurely.
41
No! Start with a
simple one! :P
Write a game? :D
42
Hello, World!
• Prints "Hello, World” to console.
• By tradition, this is everyone's first program.
43
Hello, World!
• Compared with C++ or Java, you would love Python!
// Your first C++ program
// Your first Java program #include <iostream>
public class HelloWorld { using namespace std;
public static void main(String[] args) {
System.out.println("Hello, World"); int main()
} {
} cout << "Hello, World!\n";
HelloWorld.java
return 0;
}
hello_world.cpp
44
Python vs. Java in Code Length
import java.util.Scanner;
class Factorial {
• Same algorithm public static void main(String args[]) {
• Python's almost half shorter! int n, nFact = 1;
System.out.print("Enter an integer: ");
# Compute factorial of n Scanner sc = new Scanner(System.in);
n = int(input("Enter an integer: ")) n = sc.nextInt();
if n <= 1: if (n <= 1)
n_fact = 1 nFact = 1;
else: else {
n_fact = 2 nFact = 2;
for i in range(3, n+1): for (int i = 3; i <= n; i++)
n_fact = n_fact * i nFact = nFact * i;
print("Factorial of", n, "=", n_fact) }
System.out.println("Factorial of " + n
+ " = " + nFact);
sc.close();
}
} 45
Minimized Difference in Coding Styles
• Do you write if (x == y)
{
if (x == y) { ...
... or }
} else { else
... {
} ...
}
• With Python, hopefully this won’t
be a problem.
It's the petty differences in coding style
that can really irritate a programmer.
This comic isn't exaggerating!
http://hackles.org/cgi-bin/archives.pl?request=98 46
Hello, World! And Good Day!
• If you want to print two lines,
print('Hello, world!')
print('Well, good day!')
or
print('Hello, world!\nWell, good day!')
• Note that by default, the print() function will add a new line character
at the end of your provided string.
47
Python Main Function
• Main function is the entry point of any program. But Python
interpreter can just execute the source file code sequentially without
defining the main function.
• If you want a more traditional program look with the main() function,
here it is:
def main():
print("Hello, World!")
if __name__ == '__main__':
main()
48
Python Main Function
• Indeed, any name for the main function would do:
def hello():
print("Hello, World!")
if __name__ == '__main__':
hello()
50
Python Script and Module
• Simply put, a module is a file consisting of Python code. Any Python
file can be referenced as a module.
• A file containing Python code, e.g. hello_world.py, is called a module,
and the module's name is hello_world (without the .py extension).
• For example, you can run the script in either way:
python3 hello_world.py
or
python3 -m hello_world
51
Python Programming Overview
Learn Python in 15 minutes
52
First Thing First
• Indentation does matter in Python!
• Hierarchical indentation at correct levels gives the code a proper
structure.
• Always use 4 spaces per indentation level.
• Don't use tabs or mixing tabs and spaces for indentation
if pwd == 'apple':
print('Logging on ...')
else:
print('Incorrect password.')
print('All done!')
53
Core Data Types
• Python 3 supports the following data types:
• Boolean fuel = True
• Integer speed = 167
miles = 153.5
• Float location = 16.789 + 12323.45j
• Complex car = "Mustang"
54
Conditionals (if, elif, else)
• A conditional statement tests an expression to see whether it is true
or false and it does the operations based on the result.
• Syntax:
if expression:
statement(s)
num = -1
x = 4
if x % 2 == 0: if num > 0:
print("x is even") print("Positive number")
else: elif num == 0:
print("x is odd") print("Zero")
else:
print("Negative number")
55
Loops (while)
• The while statement repeatedly executes target statement(s) as long
as a given condition holds true.
• Syntax: while expression:
statement(s)
The count is: 0
The count is: 1
• Example: The count is: 2
count = 0 The count is: 3
while (count < 9): The count is: 4
print ('The count is:', count) The count is: 5
count = count + 1 The count is: 6
The count is: 7
print ("Good bye!") The count is: 8
Good bye!
56
Loops (while … else)
• Python supports having an else statement associated with a loop
statement.
• With a for loop, the else statement is executed when the loop has exhausted
iterating the list.
• With a while loop, the else statement is executed when the condition
becomes false.
• Example:
count = 0 0 is less than 5
while count < 5: 1 is less than 5
print (count, " is less than 5") 2 is less than 5
count = count + 1 3 is less than 5
else: 4 is less than 5
print (count, " is not less than 5") 5 is not less than 5
57
Loops (for)
• The for statement iterates over items of any sequence like a list.
• Syntax:
for iter_var in sequence:
statements(s) Current letter: P
Current letter: y
Current letter: t
for letter in 'Python': # traversal of a string sequence Current letter: h
print('Current letter:', letter) Current letter: o
Current letter: n
58
Loops (for)
• If you want some counter-based loops, use the range() function:
for x in range(0, 5): x = 0
print("x = %d" % (x)) x = 1
x = 2
x = 3
x = 4
• Alternative syntax:
for var in list(range(5)): 0
print(var) 1
2
3
>>> list(range(5)) 4
[0, 1, 2, 3, 4]
59
Functions
• A function is a self-contained block of one or more statements that
performs a special task when called.
• Syntax: def name_of_function(parameters): function header
statement1
statement2
statement3 function body
...
statementN
60
Functions
• Example:
def rectangle_area(h, w):
return h * w
print(rectangle_area(10, 20))
print(rectangle_area(20, 15))
• Write once, use many times with different input parameters (data).
• Good for software code reuse.
61
Common Data Structures
• Lists
• Ordered, mutable sequence of values, like arrays in C and C++.
63
Common Data Structures
• Dictionary
• Dictionaries are unordered key-value pairs.
• The key and the value can be of different data types.
• Each value has a unique key which acts as an identifier for that value within
the dictionary.
• Defining a dictionary:
my_dictionary = {key_1 : value1, key_2 : value2 , key_3 : value3}
64
Common Data Structures
• Example
code_name = {"jack": 4098, "sape": 4139, "robb": 2323}
print(type(code_name))
print(code_name)
# You can remove items in the dict using the del keyword.
del code_name["sape"]
Output:
print(code_name) <class 'dict'>
{'jack': 4098, 'sape': 4139, 'robb': 2323}
# len() returns the number of {'jack': 1212, 'robb': 2323}
# key-value pairs in dict. 2
len(code_name)
65
Summary
• A program is an implementation (a sequence of instructions) of an
algorithm in a particular language.
• Compilers and interpreters translate high-level code to low-level
(intermediate bytecode or native machine code).
• Python is an interpreted language, and good for rapid prototyping.
• Python is concise and neat in terms of code readability.
• Python 3 is not backward compatible with Python 2.
• Writing and execution of Python code can be done in interactive
mode or script mode.
66