0% found this document useful (0 votes)
3 views82 pages

Lec01 Introduction

The document outlines an introductory lecture on computer principles and Python programming, covering the history of computers, the evolution of programming languages, and the significance of Python. It discusses key figures like Charles Babbage and Ada Lovelace, as well as the architecture of computers and the differences between compiled and interpreted languages. The lecture emphasizes Python's design goals, its history, and its growing popularity in programming.

Uploaded by

jialinli865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views82 pages

Lec01 Introduction

The document outlines an introductory lecture on computer principles and Python programming, covering the history of computers, the evolution of programming languages, and the significance of Python. It discusses key figures like Charles Babbage and Ada Lovelace, as well as the architecture of computers and the differences between compiled and interpreted languages. The lecture emphasizes Python's design goals, its history, and its growing popularity in programming.

Uploaded by

jialinli865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

CSCI1550

Computer
Principles and
Python
Programming
Lecture 1: Introduction

2024-25 Term 2
By Dr. King Tin Lam
1
Outline
• Background
• Computers
• Computer Programming
• Programming Languages
• What’s Python
• Python Programming and Execution Environments
• Your First Python Program
• A Quick Overview of Python Programming

2
Computers
History and Trends

3
Difference Engine –
The First Mechanical Computer
• Charles Babbage (1791-1871)
• Widely regarded as the father of computing Charles Babbage

• In 1822, Babbage conceptualized and began developing


the Difference Engine, which is considered the first
automatic computing machine. It could compute several
sets of numbers and making hard copies of the results.
• Made to compute values of polynomial functions based
on the principle of finite differences.
• Working mechanism (a long story) [YouTube videos]:
part 1, part 2, part 3, part 4, part 5 Portion of Babbage’s calculating
machine, Difference Engine
No.1. Credit: Science Museum
Group, UK (No. 2001-575)
4
Difference Engine –
The First Mechanical Computer
• The portion shown here was assembled in 1832 by
Babbage’s engineer, Joseph Clement. It consists of
about 2000 parts and represents one-seventh of the
complete engine.
• Much to Babbage’s dismay, however, the full engine
was never completed because of funding issues.
After his death, around 12 000 parts manufactured
for the model were melted for scrap!

Read more: http://atmosphericmemory.com/discover/library-in-the-air/


5
Analytical Engine –
The First General-Purpose Computer
• Babbage then designed the first general-purpose
computer, the Analytical Engine, in 1837. Trial model of a part of the Analytical
• It is mechanical and designed to be driven by steam. Engine, built by Babbage, as displayed
at London Science Museum

• It contained an Arithmetic Unit (ALU) or “mill”,


basic flow control, punch cards, and memory (a store).
• It is programmable and Turing-complete!
• The memory can hold 1,000 numbers of 40 decimal
digits each (ca. 16.2 kB).
• Unfortunately, again, this computer was never built
while he was alive. His son Henry Babbage built part of
it in 1910. Henry Babbage's Analytical
Engine Mill, built in 1910, in
London Science Museum
6
Timeline of Computer History
• 1100 BC: Abacus • 1947: Transistors
• 1622: Slide rule • Late 1950s: Integrated circuits (ICs)
• 1642: Pascal’s Adder • 1951: UNIVAC
• 1673: Leibniz’s calculator • 1954: Bell Labs TRADIC (transistor-based)
• 1804: Jacquard loom • 1958, IBM 7090 (transistor-based)
• 1830s: Babbage’s computers • 1964: IBM System/360 (based on ICs)
• 1847: Boolean logic • 1971: Microprocessor
• 1880: Hollerith’s electric tabulator • 1975: Altair 8880
• 1930s: Analog computer • 1976-77: Apple I & II
• 1936-41: Zuse’s computers Z1 – Z4 • 1981: IBM PC
• 1944: Harvard Mark I • 1980s, Most computers (VLSI)
• 1945: ENIAC (decimal) Digital • 1993, Intel Pentium PC
• 1946-49: EDVAC (binary) computers
7
Timeline of Computer History
• Appreciate some historic milestones and computer designs:

Activity: Enjoy these videos:


1964 IBM 029 Keypunch Card Punching
https://www.youtube.com/watch?v=YnnGbcM-H8c

The IBM 1401 compiles and runs FORTRAN II


https://www.youtube.com/watch?v=uFQ3sajIdaM

LGR - Strangest Computer Designs of the '70s


https://www.youtube.com/watch?v=Hzyw6W_njls

8
The World's Fastest Computer
(as of Nov 2024)
• El Capitan, Lawrence Livermore National Laboratory, United States
• HPE Cray EX255a, CPU: AMD 4th Gen EPYC 24C 1.8GHz, Accelerator: AMD
Instinct MI300A, Interconnect: Slingshot-11, OS: TOSS
• 11,039,616 cores
• Rpeak = 2,746.4 Pflop/s ≈ 2.7 Exaflop/s
• Rmax = 1,742 Pflop/s ≈ 1.7 Exaflop/s

1 exaflop = 1018 flop

Rpeak: theoretical peak performance Rmax: maximum achieved on https://asc.llnl.gov/exascale/el-capitan


(frequency * number of double HPL benchmark (3rd gen. of
precision FPU * FPU width) Linpack benchmark) 9
What is a Computer?
• A computer is a machine that manipulates data according to a list of
instructions.
• e.g. desktop PCs, laptop PCs, smartphones, tablets, game consoles like Xbox
and Nintendo Switch, …
• What do computers have in common?

10
Computer Organization
• von Neumann Architecture (a.k.a. von Neumann model)
• Logical groupings of the hardware functional units
John von Neumann
Input Unit in the 1940s
CPU
Arithmetic
& Logic Unit Memory Unit Storage Unit
Control
Unit

Output Unit Flow of data


11
von Neumann Architecture
• Functions of each unit: Obtains data from input devices
(keyboard, mouse, microphone,
Input Unit touch panel, network, …)

Refers to main / primary memory


Performs arithmetic CPU or Random Access Memory (RAM) Secondary storage
and logic operations devices (hard
Arithmetic drives, optical
& Logic Unit Memory Unit Storage Unit drives, USB drives,
memory cards …)
Control
Puts the data processed by the
Unit
computer on output devices
(monitor, printer, speaker, haptic
Directs the operations of the Output Unit feedback, network, …)
other units by providing
timing and control signals. Flow of data
Von Neumann Architecture 12
Levels of Machines
• There are several levels in a
computer (the exact number
is open to debate), from the
user level down to the
transistor level.
• Progressing from the top level
downward, the levels become
less abstract as more of the
internal structure of the
computer becomes visible.
Source: Principles of Computer Architecture by M. Murdocca and V. Heuring

13
Memory Hierarchy
• Registers: • Main memory
• Small, fast storage buffers within the CPU • Generally made up of DRAM (dynamic
• Compiler is responsible for managing random access memory)
their use, deciding which values should • Relatively large storage capacity
be kept in the available registers at each compared with caches
point in the program. • Relatively larger access time compared
• Cache: with SRAMs.
• Small, high speed temporary storage • Storing currently needed program
instructions and data only
• Generally made up of SRAM (static
random access memory) • Secondary Stores
• Located on the CPU (Level 1/2/3 cache) • Long access latency (SSDs, hard disks,
• Most-commonly-used data copied to tapes, etc.)
cache for faster access • Store data and programs that are not
• Small amount of cache is sufficient for actively needed
boosting performance (temporal locality)
14
Memory Hierarchy

SRAM is fast but expensive


while DRAM is slower (often (usually 1 CPU cycle)
by a factor of 10) but less
expensive (by a factor of
20). SRAM is usually used
as a hardware cache. SRAM

DRAM

Disk

https://linux2me.wordpress.com/2017/09/15
/linux-introduction-to-memory-management/ 15
Programming
Problem Solving, Algorithms, Computer
Programming, Programming Languages

16
Algorithms
• An algorithm is a finite set of well-
defined, step-by-step instructions or
rules designed to perform a task or
solve a problem.
• An algorithm can be represented by
natural language, flowcharts,
pseudocode, and programming
languages.
• See an example on the right. What is
this algorithm doing?
Image source: https://en.wikipedia.org/wiki/Algorithm
17
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?
18
The First Computer Programmer
• Ada Lovelace (1815-1852), chiefly known for
her work on Charles Babbage's proposed
mechanical general-purpose computer,
the Analytical Engine.
• Her life was only 36 years long, but she was a Augusta Ada King, Countess of Lovelace
pioneer - the first one to recognize that the https://en.wikipedia.org/wiki/Ada_Lovelace

machine had applications beyond pure


calculation - programming. "Hello, world!" in Ada
with Ada.Text_IO; use Ada.Text_IO;
• A programming language named Ada for procedure Hello is
begin
remembrance of her. Put_Line ("Hello, world!");
end Hello;

19
Programming Languages
• A programming language defines a set of instructions in specific
format that can be understood by a computer.
• Two important issues on writing programs:
• Program syntax – Is the grammar of the instructions correct?
• Program logic – Is the program able to solve the problem?

20
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 21
Object-Oriented Languages
• Smalltalk
• C++
• C# (sharp)
• VB
• Java
• Python
• open source (free)
• runs anywhere
• www use, research, data science, AI

22
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 23
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)
24
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?

25
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

26
Tiobe Index (as of July 2024)
• Python is now the world’s number one in popularity.

Python

Source: https://www.tiobe.com/tiobe-index/
27
28

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

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

30
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.
31
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.

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


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

34
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 Machine Machine (It is actually a system program
Code Code Code
for code translation.)

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

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

37
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 38
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

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

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

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

43
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
44
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.

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

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

47
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
48
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.

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

50
Launching Python (from Command Line)
• To launch an interactive Python shell, type
python or python3

51
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>
52
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

53
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

54
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
55
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()
56
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.

57
No! Start with a
simple one! :P

Write a game? :D

Your First Python Program


Let’s start to write the first Python program!

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

59
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

60
Python vs. Java in Code Length
import java.util.Scanner;
class Factorial {
• Same algorithm public static void main(String args[]) {
int n, nFact = 1;
• Python's almost half shorter! 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();
}
} 61
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 62
Hello, World! And Good Day!
• If you want to print two lines,
print('Hello, world!')
print('Well, good day!')
or
without the gap

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.

63
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 divide_by_two(x):
print(x/2)
def main():
divide_by_two(11)
print("Hello, World!")

if __name__ == '__main__':
main()
64
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.
65
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

66
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

67
Python Programming Overview
Learn Python in 15 minutes

68
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!')

69
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'>

70
= Assgin a value to a variable
== Check if two values are equal

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")
71
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
• Example: The count is: 1
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("Goodbye!") The count is: 8
Goodbye!
72
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
73
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

74
Loops (for)
• If you want some counter-based loops, use the range() function:
for x in range(0, 5): x=0
print(f"x = {x}") x=1
x=2
x=3
x=4
• Alternative syntax: list(range(0,5))

for var in list(range(5)): for x in range(0, 5): 0


print(var) print(x) 1
[the same] 2
list(range(0,5))
3
>>> list(range(5)) 4
[0, 1, 2, 3, 4] list

BUT! print(range(0,5))

output: range(0,5) 75
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.

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

77
Common Data Structures a = [1,2,3,4]
a[0] = 9
print(a)

-> a = [9,2,3,4]
• Lists can change the sequence []
can't change in tuples
• Ordered, mutable sequence of values, like arrays in C and C++.

world_tour = ["Paris", "New York", "Melbourne", "Swiss"] string (str)


print(type(world_tour))
print(world_tour)
print(world_tour[0]) 0=index
print(world_tour[1])
print(world_tour[-1]) -2: Melbourne -3: New York -4: Paris

Output: <class 'list'>


['Paris', 'New York', 'Melbourne', 'Swiss']
Paris
New York
Swiss remove ( ) -> the rame thing
del [ ] -> the sequence
not applicable in 78
dictionary
Common Data Structures
• Tuples can't change ()

• 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')

79
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}

d = {"apple':'a round red fruit', 'boy': 'a male child'}


d ['apple']
d ['boy']

80
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. no .remove

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

82

You might also like