0% found this document useful (0 votes)
7 views73 pages

Python Programming Basics Guide

This document serves as an introductory guide to Python programming, covering essential topics such as Python fundamentals, control flow, data structures (lists, dictionaries, sets), functions, and exception handling. It outlines the differences between Python 2.x and 3.x, provides installation instructions, and explains basic syntax, variable usage, and data types. Additionally, it includes examples and exercises to reinforce learning concepts.
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)
7 views73 pages

Python Programming Basics Guide

This document serves as an introductory guide to Python programming, covering essential topics such as Python fundamentals, control flow, data structures (lists, dictionaries, sets), functions, and exception handling. It outlines the differences between Python 2.x and 3.x, provides installation instructions, and explains basic syntax, variable usage, and data types. Additionally, it includes examples and exercises to reinforce learning concepts.
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

Python

Programming For Dummy


Topic
1) Getting Started
2) Python Fundamentals
3) Control Flow
4) List
5) Dictionary
6) Set
7) Loop with else
8) Function
9) Exception Handling
10) Modules
11) File I/O
12) Managing Packages

PHILIPPE. HENG PYTHON BASIC 2


Introduction
What is Python Python Versions

Python is a high level, general- Python has two major versions: 2x


purpose, interpreted and 3x.
programming language.

Python 2.x was released in 2000. The


1. High Level : easy to learn latest version is 2.7 released in 2010.
It isn’t recommended for use in new
2. General : Web, Big Data, Data projects.
Science ML AI, Testing Tool,
Automatic Tasks… Python 3.x was released in 2008.
Basically, Python 3 isn’t compatible
3. Interpreted vs. Compiled with Python 2. And you should use
language ? the latest versions of Python 3 for
your new projects.

PHILIPPE. HENG PYTHON BASIC 3


Install Python

Download: Verify:
[Link]

PHILIPPE. HENG PYTHON BASIC 4


Python Syntax
Whitespace and indentation

Python, however, uses whitespace and


indentation to construct the code structure.
#!/usr/bin/env python
# define main function to print out something
def main():
i=1
max = 10
while (i < max):
print(i)
i=i+1
# call function main
main()
PHILIPPE. HENG PYTHON BASIC 5
Python Syntax

Continuation Statement

Python uses a newline character to separate


statements. It places each statement on one
line. if (a == True) and (b == False) and \
(c == True):
print("Continuation of statements")
However, a long statement can span multiple
lines by using the backslash (\) character.

PHILIPPE. HENG PYTHON BASIC 6


Python Syntax

Identifiers

PHILIPPE. HENG PYTHON BASIC 7


Python Syntax

String literals

s = 'This is a string'
print(s)
s = "Another string using double quotes"
print(s)
s = ''' string can span
multiple line '''
print(s)

PHILIPPE. HENG PYTHON BASIC 8


Python Variables

In Python, a variable is a label that you can assign a value to it. And a variable is always associated with a value.
For example:

message = 'Hello, World!’


print(message)

message = 'Good Bye!’


print(message)

PHILIPPE. HENG PYTHON BASIC 9


Python String

The bad news is that Python doesn’t support constants.


To work around this, you use all capital letters to name a variable to indicate that the variable should be treated as a constant.
For example:

FILE_SIZE_LIMIT = 2000

PHILIPPE. HENG PRESENTATION TITLE 10


Python String

If a string contains a single quote, you should place it in double-quotes like this:

message = "It's a string"

And when a string contains double quotes, you can use the single quotes:

message = '"Beautiful is better than ugly.". Said Tim Peters'

message = 'It\'s also a valid string'

message = r'C:\python\bin'

PHILIPPE. HENG PYTHON BASIC 11


Python String

Creating multiline strings

help_message = '''
Usage: mysql command
-h hostname
-d database name
-u username
-p password
'''

print(help_message)

PHILIPPE. HENG PYTHON BASIC 12


Python String

Using variables in Python strings with the f-strings

name = 'John’ greeting = 'Good '


message = f'Hi {name}’ time = 'Afternoon'
print(message)
greeting = greeting + time + '!’
print(greeting)
Concatenating Python strings
name = "Jonh"
print(message * 3)
greeting = 'Good ' 'Morning!'
print(greeting)

PHILIPPE. HENG PYTHON BASIC 13


Python String

Accessing string elements

str = "Python String “


print(len(str))
print(str[0]) # P
print(str[1]) # y

print(str[-1]) # g
print(str[-2]) # n

# string[start:end]
print(str[0:2]) # Py

print(str[:-2])

PHILIPPE. HENG PYTHON BASIC 14


Python String

Looping Through a String :

for x in "banana":
print(x)

Check String :

txt = "The best things in life are free!"


print("free" in txt)
print("expensive" not in txt)

PHILIPPE. HENG PYTHON BASIC 15


Python String
String Format

age = 36 quantity = 3
txt = "My name is John, I am " + age itemno = 567
print(txt) price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print([Link](quantity, itemno, price))
age = 36
txt = "My name is John, and I am {}" quantity = 3
print([Link](age)) itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces
of item {1}."
print([Link](quantity, itemno, price))

PHILIPPE. HENG PYTHON BASIC 16


Python String

Python strings are immutable, It means that you cannot change the string. For example, you’ll get an error if you
update one or more characters in a string:

str = "Python String"


str[0] = ’J’ # will return exception error

str = "Python String"


new_str = 'J' + str[1:]
print(new_str)

PHILIPPE. HENG PYTHON BASIC 17


Python Number

The integers are numbers such as -1, 0, 1, 2, 3, .. and they have type int.

>>> 20 + 10
30
>>> 20 - 10
10
>>> 20 * 10
200
>>> 20 / 10 #will return float
2.0

PHILIPPE. HENG PYTHON BASIC 18


Python Number

Any number with a decimal point is a floating-point number. The term float means that the decimal point can
appear at any position in a number.

>>> 0.5 + 0.5


1.0
>>> 0.5 - 0.5
0.0
>>> 0.5 / 0.5
1.0
>>> 0.5 * 0.5
0.25

>>> 0.1 + 0.2


0.30000000000000004

PHILIPPE. HENG PYTHON BASIC 19


Python Boolean

The Boolean data type has two values: True and False.

>>> 'a' < 'b’ >>> bool('Hi')


True True
>>> 'a' > 'b’ >>> bool('')
False False

>>> 'a' < 'b' >>> bool(100)


True True
>>> 'a' > 'b' >>> bool(0)
False False

PHILIPPE. HENG PYTHON BASIC 20


Python type conversion

To get an input from users, you use the input() function. For example:

value = input('Enter a value:')


print(value)

Note : the input() function returns a string, not an integer.

PHILIPPE. HENG PYTHON BASIC 21


Python type conversion

To get an input from users, you use the input() function. For example:

price = input('Enter the price ($):') price = input('Enter the price ($):')
tax = input('Enter the tax rate (%):') tax = input('Enter the tax rate (%):')

net_price = price * tax / 100 net_price = int(price) * int(tax_ / 100

print(f'The net price is ${net_price}') print(f'The net price is ${net_price}')

PHILIPPE. HENG PYTHON BASIC 22


Python type conversion

Other type conversion functions

Besides the int(str) functions, Python support other type conversion functions. The following shows the most
important ones for now:

• float(str) – convert a string to a floating-point number.


• bool(val) – convert a value to a boolean value, either True or False.
• str(val) – return the string representation of a value.

PHILIPPE. HENG PYTHON BASIC 23


Python Operators

Python divides the operators in the following groups:

❖ Arithmetic operators
❖ Assignment operators
❖ Comparison operators
❖ Logical operators
❖ Identity operators
❖ Membership operators
❖ Bitwise operators

PHILIPPE. HENG PYTHON BASIC 24


Python Operators

Python Arithmetic Operators :

PHILIPPE. HENG PYTHON BASIC 25


Python Lab
Ex 1 : Write a program allow user to input
- their own name
- Score of Math , Physic , History, Khmer
- Calculate Total of those scores and average
- Display to console as below :
Student Name : Jonh Scott
Total Score : xx and avg : [Link]

Ex 2 : You've finished eating at a restaurant, and received this bill:

PHILIPPE. HENG PYTHON BASIC 26


Python Operators

Comparison operators :

PHILIPPE. HENG PYTHON BASIC 27


Python Operators

Logical operators :

PHILIPPE. HENG PYTHON BASIC 28


Python Operators

Assignment operators :

PHILIPPE. HENG PYTHON BASIC 29


Python Operators

Membership operators :

PHILIPPE. HENG PYTHON BASIC 30


Python Operators

Identity Operators :

PHILIPPE. HENG PYTHON BASIC 31


Python Control Flow

You use the if statement to execute a block of code based on a specified condition.
The syntax of the if statement is as follows:

if condition:
body of if

age = input('Enter your age:’) age = input('Enter your age:’)


if int(age) >= 18: if int(age) >= 18:
print("You're eligible to vote.") print("You're eligible to vote.")
print("Let's go and vote.") print("Let's go and vote.")

PHILIPPE. HENG PYTHON BASIC 32


Python Control Flow

The following shows the syntax of the if...else statement:

if condition:
body of if
else:
body of else

age = input('Enter your age:')


if int(age) >= 18:
print("You're eligible to vote.")
else:
print("You're not eligible to vote.")

PHILIPPE. HENG PYTHON BASIC 33


Python Control Flow

Short if else ? :

# condition ? value_if_true : value_if_false


age = input('Enter your age:')

ticket_price = 20 if int(age) >= 18 else 5


print(f"The ticket price is {ticket_price}")

PHILIPPE. HENG PYTHON BASIC 34


Python Control Flow

Here is the syntax if the if...elif...else statement:

# condition ? value_if_true : value_if_false


age = input('Enter your age:’)

if int(age) >= 32:


print(“Volka")
elif int(age) >= 18 :
print(“Beer”)
else:
print(“Milk”)

PHILIPPE. HENG PYTHON BASIC 35


Python Control Flow

Python for Loop with Range


The following illustrates the syntax of a for loop:

for index in range(n): for index in range(5):


statement print(index)

#range(start, stop) for index in range(5):


#range(start, stop, step) print(index + 1)

for index in range(1, 6):


print(index)

for index in range(0, 11, 2):


print(index)
PHILIPPE. HENG PYTHON BASIC 36
Python Control Flow

Python for Loop with Range (revers):

for indx in reversed(range(5)):


print(indx)

for index in range(10,0,-1) :


print(indx)

PHILIPPE. HENG PYTHON BASIC 37


Python Control Flow
While Loop :

n = 10

# initialize sum and counter


sum = 0
i=1

while i <= n:
sum = sum + i
i = i+1 # update counter

# print the sum


print("The sum is", sum)

PHILIPPE. HENG PYTHON BASIC 38


Python Control Flow
Loop with Break :

for index in range(n):


# more code here
if condition:
break

Loop with Continue :

for index in range(n):


# more code here
if condition:
continue

PHILIPPE. HENG PYTHON BASIC 39


Python Control Flow
Pass statement :

counter = 1
max = 10
if counter <= max:
counter += 1
else:
pass

The pass statement is a statement that does nothing.


It’s just a placeholder for the code that you’ll write in the future.

PHILIPPE. HENG PYTHON BASIC 40


Python List
• A list is an ordered collection of items.
• Use square bracket notation [] to access a list element by its index. The first element has an index 0.
• Use a negative index to access a list element from the end of a list. The last element has an index -1.

todo_list = ['Learn Python List','How to manage List elements’]


numbers = [1, 3, 2, 7, 9, 4]
print(numbers[1])
print(numbers[-1])

numbers = [1, 3, 2, 7, 9, 4]
for num in numbers :
print(num)

PHILIPPE. HENG PYTHON BASIC 41


Python List

• Use list[index] = new_value to modify an element from a list.


• Use append(value) to add a new element to the end of a list.
• Use insert(indx, value) to add a new element at a position in a list .
• Use pop() to remove last element from a list and return that element. But we also can pop(indx)
• Use remove() to remove an element from a list.

PHILIPPE. HENG PYTHON BASIC 42


Python List Sort & Slice
guests = ['James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer']
[Link]()
[Link](reverse=True)

// sub_list = list[begin: end: step]


guests = ['James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer']
guests_slice = guests[1:4]
print(guests_slice)

guests_slice = guests[:3] // ['James', 'Mary', 'John',]

PHILIPPE. HENG PYTHON BASIC 43


Python Tuples
A tuple is a list that cannot change.
Python refers to a value that cannot change as immutable. So by definition,
a tuple is an immutable list.

rgb = ('red', 'green', 'blue’)


Print(rbg[0])

rgb = ('red', 'green', 'blue’)


rgb[0] = 'black’

numbers = (3)
print(type(numbers))

numbers = (3,)
print(type(numbers))

PHILIPPE. HENG PYTHON BASIC 44


Python Set
A Python set is an unordered list of immutable elements. It means:
• Elements in a set are unordered.
• Elements in a set are unique. A set doesn’t allow duplicate elements.
• Elements in a set cannot be changed.
• To define a set in Python, you use the curly brace {}.

skills = {‘Oracle’,’MySQL', ‘PostgreSQL’}


print(skills)
empty_set = set()

PHILIPPE. HENG PYTHON BASIC 45


Python Set

numbers = [1,2,3,4,3]
unique = set(number)
print(unique) ## doesn’t allow duplicate elements

numbers = [1,2,3,4,3]
unique = set(number)
[Link](9)
[Link](2)
len(unique)

PHILIPPE. HENG PYTHON BASIC 46


Python Set
// union // intersection
one = {1,2,3,4} one = {1,2,3,4}
two = {3,4,5,6} two = {3,4,5,6}

print(one | two) print(one & two)

// difference // symmetric difference


one = {1,2,3,4}
two = {3,4,5,6} one = {'Python', 'Java', 'C++’}
two = {'Java', 'C++’ ,'C#' }
print(one - two) // {1, 2} print(one ^ two) // {'Python', , 'C#' }

PHILIPPE. HENG PYTHON BASIC 47


Python issubset() vs. issuperset()
numbers = {1, 2, 3, 4, 5}
scores = {1, 2, 3}

print([Link](numbers))
print(scores <= numbers)

numbers = {1, 2, 3, 4, 5}
scores = {1, 2, 3}

print([Link](scores))
print(numbers >= scores)

PHILIPPE. HENG PYTHON BASIC 48


Python Dictionary
• A value in the key-value pair can be a number, a string, a list, a tuple, or even another dictionary.
In fact, you can use a value of any valid type in Python as the value in the key-value pair.
• A key in the key-value pair must be immutable. In other words, the key cannot be changed, for
example, a number, a string, a tuple, etc.

empty_dict = {}
person = { print(person[‘first_name’])
'first_name': 'John', print(person[‘age’])
'last_name': 'Doe',
'age': 25, print([person[‘phone’]) // error 
'favorite_colors': ['blue', 'green'], print([Link](phone’))
'active': True
}

PHILIPPE. HENG PYTHON BASIC 49


Python Dictionary
• Adding new key-value pairs • Modifying values

person = { person = {
'first_name': 'John', 'first_name': 'John',
'last_name': 'Doe', 'last_name': 'Doe',
'age': 25, 'age': 25,
'favorite_colors': ['blue', 'green'], 'favorite_colors': ['blue', 'green'],
'active': True 'active': True
} }
person[‘phone’] = ‘+855 80505000’ person[‘age’] = 50
print(person) print(person)

PHILIPPE. HENG PYTHON BASIC 50


Python Dictionary
• Removing key-value pairs

person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 25,
'favorite_colors': ['blue', 'green'],
'active': True
}
del person['active’]
print(person)

PHILIPPE. HENG PYTHON BASIC 51


Python dictionary comprehension
stocks = {
'AAPL': 121, stocks = {
'AMZN': 3380, 'AAPL': 121,
'MSFT': 219, 'AMZN': 3380,
'BIIB': 280, 'MSFT': 219,
'QDEL': 266, 'BIIB': 280,
'LVGO': 144 'QDEL': 266,
} 'LVGO': 144
}
new_stocks = {} new_stocks = {symbol: price * 1.02 for (symbol, price) in
for symbol, price in [Link](): [Link]()}
new_stocks[symbol] = price*1.02
print(new_stocks)
print(new_stocks)

PHILIPPE. HENG PYTHON BASIC 52


Python dictionary comprehension
stocks = {
'AAPL': 121, stocks = {
'AMZN': 3380, 'AAPL': 121,
'MSFT': 219, 'AMZN': 3380,
'BIIB': 280, 'MSFT': 219,
'QDEL': 266, 'BIIB': 280,
'LVGO': 144 'QDEL': 266,
} 'LVGO': 144
}
selected_stocks = {}
for symbol, price in [Link](): filter_stocks = {s: p for (s, p) in [Link]() if p > 200}
if price > 200:
selected_stocks[symbol] = price print(filter_stocks)

print(selected_stocks)

PHILIPPE. HENG PYTHON BASIC 53


Python Function
• A function is a named code block that performs a job or returns a value.

Defining a Python function

#init function
def sayHello():
""" Display a greeting to users """
print(‘Hi Jonh’)

#call function
sayHello()

PHILIPPE. HENG PYTHON BASIC 54


Python Function
Passing information to Python functions
• Suppose that you want to greet users by their names. To do it, you need to specify a name in
parentheses of the function definition as follows:

#init function
def sayHello(name):
""" Display a greeting to users """
print(f"Hi {name}")

#call function
sayHello(‘smitt’)

PHILIPPE. HENG PYTHON BASIC 55


Python Function
Returning a value

#init function
def sayHello(name):
return f"Hi {name}“

#call function
x = sayHello('John’)
print(x)

PHILIPPE. HENG PYTHON BASIC 56


Python Function
Keyword Arguments

#init function
def greet(firstname, lastname) :
print(f’Hi {firstname} {lastname”}’)

#call function
greet(firstname=“john”, lastname=“scott”)
greet(firstname=“jonh,”,”scott”)

PHILIPPE. HENG PYTHON BASIC 57


Python Function
Recursive Functions

def sum(n):
def sum(n):
total = 0
if n > 0:
for index in range(n+1):
return n + sum(n-1)
total += index
return 0
return total
# call function
# call function
result = sum(10)
result = sum(10)
print(result)
print(result)

PHILIPPE. HENG PYTHON BASIC 58


Python Function
Recursive Functions

def count_down(start):
""" Count down from a number """
print(start)

next = start - 1
if next > 0:
count_down(next)
else :
print("Done")

# call function
count_down(3)

PHILIPPE. HENG PYTHON BASIC 59


Python Function
*Args and **Kwargs in Python

def multiplyThreeNumbers(num1, num2, num3):


return num1*num2*num3

print("product:",multiplyThreeNumbers(1, 2, 3))

def multiplyNumbers(*numbers):
product=1
for n in numbers:
product*=n
return product

print("product:",multiplyNumbers(4,4,4,4,4,4))

PHILIPPE. HENG PYTHON BASIC 60


Python Function
*Args and **Kwargs in Python

def whatTechTheyUse(**kwargs):
result = []
for key, value in [Link]():
[Link]("{} uses {}".format(key, value))
return result

print(whatTechTheyUse(Google='Angular', Facebook='react', Microsoft='.NET'))

PHILIPPE. HENG PYTHON BASIC 61


Python Function
Lambda and Anonymous Function in Python

PHILIPPE. HENG PYTHON BASIC 62


Python Function
Lambda and Anonymous Function in Python

# Regular function
def sum(num1, num2):
return (num1 + num2)

# Equivalent lambda function


sum_lambda = lambda num1, num2 : num1 + num2

print (sum(5,4)) #9
print(sum_lambda(5, 4)) #9

PHILIPPE. HENG PYTHON BASIC 63


Python Exceptions
Even though when your code has valid syntax, it may cause an error
during execution.

In Python, errors that occur during the execution are called exceptions.
The causes of exceptions mainly come from the environment where the
code executes. For example:
• Reading a file that doesn’t exist.
• Connecting to a remote server that is offline.
• Bad user inputs.

k = 5//0 # raises divide by zero exception.


print(k)

PHILIPPE. HENG PYTHON BASIC 64


Python Exceptions
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except Exception as err:
print("Oops!", err.__class__, "occurred.")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')

PHILIPPE. HENG PYTHON BASIC 65


Python Exceptions
Catching specific exceptions

try:
print('Enter the net sales for')
previous = float(input('- Prior period:'))
current = float(input('- Current period:'))

# calculate the change in percentage


change = (current - previous) * 100 / previous
if change > 0:
result = f'Sales increase {abs(change)}%'
else:
result = f'Sales decrease {abs(change)}%'
print(result)
except ValueError:
print('Error! Please enter a number for net sales.')

PHILIPPE. HENG PYTHON BASIC 66


Python Exceptions
Handling multiple exceptions

try:
print('Enter the net sales for')
previous = float(input('- Prior period:'))
current = float(input('- Current period:’))

change = (current - previous) * 100 / previous


if change > 0:
result = f'Sales increase {abs(change)}%'
else:
result = f'Sales decrease {abs(change)}%'
print(result)
except ValueError:
print('Error! Please enter a number for net sales.')
except ZeroDivisionError:
print('Error! The prior net sales cannot be zero.')

PHILIPPE. HENG PYTHON BASIC 67


Python Exceptions
Raising Exception

The raise statement allows the programmer to force a specific exception to occur. The sole
argument in raise indicates the exception to be raised. This must be either an exception
instance or an exception class (a class that derives from Exception).

# Program to depict Raising Exception

try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not

PHILIPPE. HENG PYTHON BASIC 68


Python FileIO
Open () method

>>> f = open("[Link]") # open file in current directory


>>> f = open("C:/Python38/[Link]") # specifying full path
>>> f = open("[Link]", mode='r', encoding='utf-8')

PHILIPPE. HENG PYTHON BASIC 69


Python FileIO
Read function

try:
f = open("[Link]", encoding = 'utf-8')
# perform file operations
print([Link]())
finally:
[Link]()

with open('dog_breeds.txt', 'r') as reader:


# Further file processing goes here
print([Link]())

PHILIPPE. HENG PYTHON BASIC 70


Python FileIO
Readlines function
#read line by line
with open('[Link]', 'r') as reader:
line = [Link]()
print(line)

f = open('dog_breeds.txt’)
list(f)

with open('[Link]', 'r') as reader:


# Read and print the entire file line by line
for line in reader:
print(line, end='')

PHILIPPE. HENG PYTHON BASIC 71


Python FileIO
Readlines function
#read line by line
with open('[Link]', 'r') as reader:
for line in [Link]():
print(line, end='')

with open('[Link]', 'r') as reader:


# Read and print the entire file line by line
line = [Link]()
while line != '': # The EOF char is an empty string
print(line)
line = [Link]()

PHILIPPE. HENG PYTHON BASIC 72


Python FileIO
Write function

with open('[Link]', ‘w') as the_file:


the_file.write('Hello\n’)

PHILIPPE. HENG PYTHON BASIC 73

You might also like