Lec01 Introduction

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

CSCI2040

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.

Human language Computer

• Computer programming language is more systematic than a natural


language. Harder or easier to learn?
3
High-Level Languages Language Inventors

• 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

• Scripting Language Inventors


• JavaScript, VBScript, PHP, Perl, Python, Ruby,
Shell scripts
• Functional
• Haskell, Lisp, Scala
Java C++
There is no overarching classification scheme for programming James Gosling Bjarne Stroustrup
languages; but Wikipedia keeps a long list classified by “type”.
https://en.wikipedia.org/wiki/List_of_programming_languages_by_type 4
Object-Oriented Languages
• Smalltalk
• C++
• C# (sharp)
• VB
• Java
• Python
• open source (free)
• runs anywhere
• www use, research, data science, AI

5
Code Translation
Compilers, interpreters and assembler are computer
High programs to do translation from one language to another
Level
High Level Language

Closest to natural language, e.g. English


High Level Language Source code is portable, e.g. C++, Pascal, Python, etc.
Compilers / Interpreters

Compilers / interpreters translate high level language


into machine code

Assembly Language
Assembly Language

Assembler More or less human readable, not portable


(hardware dependent), assembler converts
Machine Language assembly language into machine code
Machine Language

More natural language for hardware,


Hardware bits in 0s and 1s, not portable
(hardware dependent, i.e. different hardware
Low understands different machine languages)
Level 6
Compilers vs. Interpreters
• A compiler is a software program (or a set of programs), which
translates source code written in high-level language into a low-level
object code (binary code) in machine language.
• The job is done offline. We say it’s done at compile time.
• This process is called compilation.
• The high-level language is called a compiled language.

Compilation

High-level language Machine language


(Source code) (Object code)
7
Compilers vs. Interpreters
• An interpreter actually does the same job as a compiler except that
the job is done at the moment when the program is run.
• We say it translates code at run time.
• An interpreter works in a line-by-line manner.
• Convert one program statement to machine code and execute it immediately; then
convert and execute the next statement.
• The high-level language that works in this way is called an interpreted
language.

Question:
Compiled languages vs. interpreted
languages – which runs faster in general?

8
Compilers vs. Interpreters

Compiled languages: Interpreted languages:


• C • Perl
• C++ • Python
• Visual Basic • PHP
• Java (to bytecode) • JavaScript
• C# (to bytecode) • VBScript
• Objective-C • Ruby
• Swift • Unix shell scripts
• Go • PowerShell

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.

Guido van Rossum at OSCON 2006

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

Don't believe everything on this slide! Make up your own mind.


16
Python’s Portability
• We say Python is portable or cross-platform.
• This promise can be kept, thanks to Python’s virtualization techniques
using
• Bytecode (a portable binary code format), and
• Python Virtual Machine (PVM), which abstracts away the underlying
OS and hardware.

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).

• The official reference implementation of Python is nicknamed


CPython because it is written in C.

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/

Basis of comparison Python 3 Python 2


Release Date 2008 2000 Don't use
Python 2
Function print print ("hello") print "hello"
anymore!

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.

Unicode In Python 3, default To store Unicode string value,


storing of strings is you require to define them
Unicode. with "u".
https://www.guru99.com/python-2-vs-python-3.html 22
Python Programming and
Execution Environments
Choices of Installation
• You may choose to install
1. The official Python runtime only
• which includes a minimal IDE called "IDLE" and a package manager called "pip"
2. Anaconda (Individual Edition, free)
• which preinstalls hundreds of packages and includes a package/environment manager
called "conda", IDE support (PyCharm), other goodies such as Jupyter Notebook, and a
graphical user interface called Anaconda-Navigator for launching the applications.
3. Miniconda
• which is a minimal free version of Anaconda, includes a package/environment manager
called "conda" and a minimal set of Python packages

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.

• Details are covered during the first tutorial.

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).

• How about installing a "small snake" Miniconda instead?


• A lite version of Anaconda; less than 1/10 of Anaconda's size
https://www.quora.com/Why-should-I-use-anaconda-instead-of-traditional-Python-distributions-for-data-science
28
Miniconda
• Miniconda is a free minimal version of Anaconda.
• It includes only conda, Python, and a few packages including pip, zlib, etc.
• You can install 720+ additional conda packages from the Anaconda repository.

We recommend Miniconda, which is a lite version of


Anaconda. It takes less space but has the essentials of a data
scientist toolset. It is also okay if you prefer Anaconda to
Miniconda, which has more pre-installed packages in it.

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.

• Refer to Tutorial 1 to know more details.

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

• Type the following command to execute the script file:


(base) C:\Users\KingTin>python hello_world.py
Hello, World!

• No need to type exit() in your script. It will terminate naturally

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

Your First Python Program


Let’s start to write the first Python program!

42
Hello, World!
• Prints "Hello, World” to console.
• By tradition, this is everyone's first program.

# Your first Python program


print('Hello, world!')
hello_world.py

• Written in Python, this program is at most two


lines long!
(Victoria's newborn picture)

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()

• __name__ is a built-in variable which evaluates to the name of the


current module. It can be used to check whether the current script is
being run on its own or being imported somewhere.
49
Writing Python in Script Mode
• Use your favorite IDE or code editor to write the whole Python
program.
• Save the source file with .py extension.

# Your first Python program


print('Hello, world!')
hello_world.py

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"

• String # type() function returns the datatype of variable.


print(fuel, type(fuel))
print(speed, type(speed)) True <class 'bool'>
print(miles, type(miles))
167 <class 'int'>
print(location, type(location))
153.5 <class 'float'>
print(car, type(car)) (16.789+12323.45j) <class 'complex'>
Mustang <class 'str'>

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

fruits = ['banana', 'apple', 'mango'] Current fruit: banana


for fruit in fruits: # traversal of List sequence Current fruit: apple
print('Current fruit:', fruit) Current fruit: mango

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

• The keyword def introduces a function definition. It must be followed


by the function name and a parenthesized list of formal parameters.

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++.

world_tour = ["Paris", "New York", "Melbourne", "Swiss"]


print(type(world_tour))
print(world_tour)
print(world_tour[0])
print(world_tour[1])
print(world_tour[-1])

Output: <class 'list'>


['Paris', 'New York', 'Melbourne', 'Swiss']
Paris
New York
Swiss
62
Common Data Structures
• Tuples
• Ordered, immutable sequence of values.
• Why use tuples?
• Tuples are faster than lists and safer. They are write-protected and we cannot
add new items once the declaration is made.
atmosphere = ("Oxygen", "Hydrogen", "Nitrogen")
print(type(atmosphere))
print(atmosphere)

Output: <class 'tuple'>


('Oxygen', 'Hydrogen', 'Nitrogen')

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 update item's value by overriding it.


code_name['jack'] = 1212

# 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

You might also like