0% found this document useful (0 votes)
5 views83 pages

Lecture 06-07 - Fundamental of Programming - Python

The document provides an overview of Python programming, covering its history, popularity, and applications. It includes practical guidance on getting started with Python, using Google Colab, and writing basic scripts involving variables, loops, and conditions. Additionally, it introduces various data types and control statements in Python, along with exercises for hands-on learning.

Uploaded by

Zach Chow
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)
5 views83 pages

Lecture 06-07 - Fundamental of Programming - Python

The document provides an overview of Python programming, covering its history, popularity, and applications. It includes practical guidance on getting started with Python, using Google Colab, and writing basic scripts involving variables, loops, and conditions. Additionally, it introduces various data types and control statements in Python, along with exercises for hands-on learning.

Uploaded by

Zach Chow
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/ 83

Fundamentals of

Programming
Lecture Python Programming
Today we will learn
• Why learn Python?
• History of Python
• Reasons why developers learn Python?
• Python applications
• Getting started with writing Python scripts
• Installing Python
• Working with Google Colab
• Writing your first Python code
• Working with Variables
• Taking inputs
• String Slicing and Indexing
• Loops and Conditions
• Nested Loops
• More data types
Why learn Python?
Learning Python in 2023

https://www.geeksforgeeks.org/top-10-programming-languages-to-learn/
Python Ranks 1st in PYPL List!

https://pypl.github.io/PYPL.html
Who created Python?

Guido van Rossum


Interpreter transforms or interprets a high- Dutch programmer
level programming code into code that can
be understood by the machine (machine
code) or into an intermediate language that
can be easily executed as well.
Why the name Python?
• It was named as Python because the person who essentially created
Python was a big fan of this show
Why Python is so popular?
WHY?
• PYTHON has a number of built-in features that make
it easier to write concise code.
Python scripts are simple - E.g., Python has a number of built-in data types,
such as lists, dictionaries, and sets, which can be
used to store and organize data without having
• Python code is 3.5 times smaller than to define them explicitly.
• It also has a dynamic typing system, which means
JAVA/C++ codes owing to Python’s that you don't have to declare the type of a variable
built in datatypes and dynamic typing when you create it.
• Python has a number of built-in functions that can be
used to perform common tasks, such as reading and
writing files, processing strings, and working with
dates and times. This can save you time and effort
when writing code.
• Python has a number of built-in modules that can be
used to add additional functionality to your
programs. This can also save you time and effort
when writing code.
• Python is a very flexible language, and it can be used
to write programs for a wide variety of tasks. This
means that you can often use the same code for
multiple projects, which can also save you time and
effort.
Compare Python with Other Programming
Languages – Memes out there!

Switching from
C++ to Python is
the same feeling
as depicted in this
meme
Python Programming
• Python program is stored in python script files: python_filename.py
• Python online notebooks are stored with python_filename.ipynb
• Python doesn’t use curly braces or any other symbol for programming
blocks for loops and conditions.
• Instead indentation is used in the form of spaces of tabs
For e.g.

if a==2:
print(“Hello”)
https://www.youtube.com/watch?v=Y8Tko2YC5hA
Let’s get
started …
Options:
1. Use Python via
Anaconda
(https://www.anaco
nda.com/) or
2. Visual Studio Code
Editor
1. Download the Visual Studio Code
• Go to https://code.visualstudio.com/
1. Download the Visual Studio Code
• Go to https://code.visualstudio.com/

…..
2. Install Necessary Extensions
Search “Jupyter”
Search “Python”

Best resource of how to get started with Python in VS Code:


https://code.visualstudio.com/docs/python/python-tutorial
Google Co-lab
• For this workshop, we will use Google Co-lab
• Colab, or "Colaboratory", allows you to write and execute Python in
your browser, with
• Zero configuration required
• Access to GPUs free of charge
• Easy sharing
• Write and execute code in Python
• Document your code that supports mathematical equations

What co-lab
• Create/Upload/Share notebooks
• Import/Save notebooks from/to Google Drive

offers you? • Import/Publish notebooks from GitHub


• Import external datasets e.g. from Kaggle
• Integrate PyTorch, TensorFlow, Keras, OpenCV
• Free Cloud service with free GPU
Google
• Step 1: Open the following URL in your browser:
https://colab.research.google.com

• Your browser would display the following screen (assuming that you
are logged into your Google Drive / Gmail)
Google
• Click on the New notebook link at the bottom of the screen. A new
notebook would open up as shown in the screen below.
Google
• This is the screen you will see after you have opened a ‘new
notebook’
Google
• By default, the notebook uses the naming convention
UntitledXX.ipynb. To rename the notebook, click on this name and
type in the desired name in the edit box as shown here:
Google
• Let's try to enter trivial Python code in the code window and execute
it.
• You may enter the following two Python statements in the code
window:

import time
print(time.ctime())
Google - Executing the Code
• To execute the code, click on the arrow on the left side of the code
window.
Google - Executing the Code
• After a while, you will see the output underneath the code window,
as shown here:

• You can clear the output anytime by clicking the icon on the left side
of the output display.
Google - Adding More Cells
• To add more code to your notebook, select the “+ Code” option under
the menu. Alternatively, just hover the mouse at the bottom center of
the Code cell. When the CODE and TEXT buttons appear, click on the
CODE to add a new cell.
Google - Running all cells together
• Click Runtime > Run all
Google - Moving cells up and down
• You an click the two arrow buttons to move the cells up and down
Google - Deleting cells
Google - Saving your work
• Colab allows you to save your work to your Google Drive. To save your
notebook, select the following menu options:
Google - Sharing your Notebook
• To share the notebook that you have created with other co-
developers, you may share the copy that you have made in your
Google Drive.
Let’s get started with the Code
• Type the following in your Google Co-lab notebook

print("Hello everyone!") print('Hello everyone!')

• Now try this:


Print('Hello everyone!')

• Which one(s) work?


Exercise – 5 minutes
• Go to https://colab.research.google.com/
• Start a new notebook
• Try all the print commands from the previous slide
• Which one(s) work and which one(s) don’t?
• What is the reason?
print("Hello everyone!")

print('Hello everyone!')

Print('Hello everyone!')
Variables
• A Variable is a container for a value
• Much like what we used to do in traditional maths
• We could input any value in x
Types of Variables in Python
• str (strings)
• int (signed integers),
• float (floating point),
• bool (Boolean),
• NoneType
• NoneType is a special type with a single value
• The value is called None

More datatypes will be introduced later


Variables
• Not limited to numbers, but also words, booleans (True or False)
Variables – Strings (str)
Variables – Strings (str)
• Choose a unique name (true for all variable types)

• String datatype is a series of characters (like a name, number, etc.)

title = "Python workshop”


print(title)

• Combining our string variable with another string

title = "Python workshop”


print(“Welcome at the ”+title)
Variables – Strings (str)
• Combining or Concatenating strings
• Strings can be concatenated using the “+” operator
Check the data type of Variable
• Use the ‘type()’ function
Variables – Integers (Int)
• int data type
• int = integer = whole number

• No need of quotes Datatype:


Variables
• Concatenate strings and integers requires one extra step

string integer
Variables
• We can only concatenate when data types are same
• Convert age to string using str()
Variables – Floating Point (float)
• Float data type = floating point number or decimal number
• For e.g. 20.5, 240.503,etc.

• Concatenate float with string


Variables – Boolean (bool)
• Boolean (True or False)

• You can find the data type using type() command


Length of a Variable
• Length using len()
Index of a Variable

Index starts at 0, so Z is index ‘0’ here.


Exercise – 5 minutes
Try
• name=”bilal” (you can put your name here)
• print(name.upper())
• print(name.lower())
• print(name.capitalize())
• print(name.isdigit())
• print(name.isalpha())
• print(name.count(“a”))
• print(name.replace(“a”,”i”))
• print(name*3)
Changing data types
Let’s make the code interactive - User inputs

name = input('what is your name?')


age = input('How old are you?')

print('Hi there '+name)


print('You are '+age+' years old')
Exercise – 5 minutes
• Make a code that takes input from a diner about what they would like
to have for dinner?
The waiter needs to ask ”what would you like to have in your dinner?” the
answer needs to be stored in a variable called “main_course”.

• The waiter then asks “would you like to have any drink along?”. The
answer needs to be stored in “drink” variable.

• After the user input, the waiter should print the order that was given
by the diner.
Math functions in Python
• We can import functions from
modules (for e.g. math is a module)
import math • Think of a module as a book,
pi=3.14 consisting of new functions
x=3
y=4
print(math.ceil(pi))
print(math.floor(pi))
print(math.pow(pi,2))
print(max(x,y))
print(min(x,y))
String slicing – using Indexing[]
name = "Charles Kuen Kao"
• Slicing: creating a first_name = name[0:7] # Python always
substring out of a string. counts from starting number to "End # -
1"
This can be achieved by print(first_name)
using indexing []
or slice() first_name = name[:12] #If colon's left
side is empty, it means "from begining/0"
• For indexing, index O/P:
print(first_name)
needs to be specified Charles
Charles Kuen
as: [start: stop: last_name = name[13:16]
Kao
print(last_name)
step] Kuen Kao
last_name = name[8:] #If colon's right
side is empty, it means "till end"

print(last_name)
name = "Charles Kuen Kao"

String Slicing – Using Indexing[]


Start Stop Step

funky_name = name[0:13:1]
print(funky_name)
O/P:
funky_name = name[0:13:2] Charles Kuen
CalsKe
print(funky_name)
CalsKe a
oaK neuK selrahC
funky_name = name[::2]
print(funky_name)

reversed_name = name[::-1]
print(reversed_name)
String Slicing using slice()
• Website1 = http://google.com
• Website2 = http://gmail.com
• Apply same slicing method to both website1 and website2 variables
to extract the website name only “google” and “gmail”
website_name = "http://google.com"
slice = slice(7,-4)
print(website_name[slice])
Logical Conditions
• Python supports the usual logical conditions from mathematics:
• These conditions can be used in several ways, most commonly in "if
statements" and loops.
Condition Logical Operator
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
Logical operators
OPERATOR DESCRIPTION SYNTAX

Logical AND: True if both


and x and y
the operands are true

Logical OR: True if either of


or x or y
the operands is true

Logical NOT: True if


not not x
operand is false
Conditions and Loops
• if statement
• if statement
• else statement
• elif statement
• Nested
• Switch case
• While loop
• for loop
IF Statement
IF statement
• A piece of code that will execute if the condition is true or satisfied
IF Statement
age = int(input("What is your age?"))
if age >= 18:
print("you're an adult")
else:
print("you're a child")

See indentation
IF and ELIF (Else If)
• You can add more than 1 elif statements
if age >= 18:
print("you're an adult")
elif age < 0:
print("you are not born yet!")
else:
print("you're a child")
IF and ELIF – Changing the order …
• The IF condition always work in order
What would be a good strategy?
Exercise – 10 minutes
• Create a python code to take input of temperature from the user.
• If temperature is >= 0 and <= 30, print “Temperature is good today.
Go out!”. If temperature is <0 or temperature >30, then print “the
temperature is bad today, please do not go out!”
While Loop
While loop
• A statement that will execute its block of code, as long as its condition
remains true

name = ""

while len(name) == 0:
name=(input("what is your name?"))

print("Hello "+name)

This loop will keep repeating until true


FOR Loop
FOR loop
• A statement or block of code that will repeat for a limited number of
times
• While loop could go to infinite times
• For loop is always limited

for i in range(10):
print(i)
FOR Loop with Steps
FOR Loop with Strings
For Loop – Example
Python code for creating a new year countdown from 10 seconds. After
the countdown, the code should print “Happy New Year!”.

import time
for seconds in range(10,0,-1):
print(seconds)
time.sleep(1) # causes the program to pause for one second
print("Happy new year!")
Exercise – 5 minutes
• Write a Python code to print numbers from 1 to 10. when the number
becomes 3, print “3 means hatrick!”. The code should print other
numbers in sequence as normal.
• Hint: Use for loop and IF condition together
for i in range(1,10+1,1):
print(i)
if i==3:
print("3 means hatrick!")

OR
for num in range(1, 11):
if num == 3:
print("3 means hatrick!")
else:
print(num)
Nested Loops
• A loop inside a loop is called a nested loop
Loop Control Statements
• Change a loop execution from its normal sequence
• Break: used to terminate the loop entirely
• Continue: Skips to the next iteration of the loop
• Pass: does nothing, acts as a placeholder
Loop Control Statements

phone_number = "+852-5123-4566"
type(phone_number)

for i in phone_number:
if i=="+" or i=="-":
continue
print(i, end="")

O/P:
85251234566
Loop Control Statements – Exercise – 5
minutes
• Try the code:
for i in range(1,20):
if i==13:
break
print(i)

• Now , in the same code, replace “break” with “pass” and ”continue”.
• What is the difference?
… More data types

You might also like