0% found this document useful (0 votes)
3 views

02-Python2

The document covers fundamental Python programming concepts, including control flow statements (if, else, elif), loop control statements (for, while), and functions. It also discusses file handling techniques such as opening, reading, writing, and appending files, along with the use of the 'with' statement for resource management. The content is structured to provide a comprehensive overview of basic Python programming skills.

Uploaded by

Nguyễn Lê Vy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

02-Python2

The document covers fundamental Python programming concepts, including control flow statements (if, else, elif), loop control statements (for, while), and functions. It also discusses file handling techniques such as opening, reading, writing, and appending files, along with the use of the 'with' statement for resource management. The content is structured to provide a comprehensive overview of basic Python programming skills.

Uploaded by

Nguyễn Lê Vy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Python Basics 2

Nguyen Ngoc Thao, B.SE


In Charge of Deep Medicine,
Phan Chau Trinh Medical University
[email protected]
0935192556
Content

➢ Control flow statements


➢ Loop control statements
➢ Function
➢ File Handling
➢ Exception Handling
Conditional Control
Statements
○ If statement
○ If… else statement
○ If… elif… else statement
○ Nested If statement
○ Short- hand if & if…else statements
If statement

if condition:
# Statements to execute if condition is true

i = 10

if (i > 15):
print("10 is less than 15")
print("I am Not in if")
If…else statement
if (condition):
# Executes this block if condition is true
else:
# Executes this block if condition is false

i = 20
if (i < 15):
print("i is smaller than 15")
print("in if Block")
else:
print("i is greater than 15")
print("in else Block")
print("not in if and not in else Block")
If… elif… else
Statement
if (condition):
statement
elif (condition):
... statement
else:
statement

i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Nested If Statement
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

i = 10
if (i == 10):
if (i < 15):
print("smaller than 15")
if (i < 12):
print("smaller than 12")
else:
print("greater than 15")
Short- hand if & if…else statements
➔ If there is only one statement to execute, the If & If … else statements can
be put on the same line

if condition: Statement

i = 10
if (i > 15): print("10 is less than 15")

Statement_when True if condition else statement_when False

i = 10
print(True)if (i < 15) else print(False)
Loop Control
Statements
○ for loop statements
○ while loop statements
○ The range() function
○ Loops with break statement
○ Loops with continue statement
○ Loops with else statement
○ Loops with pass statement
for Loop Statements
➔ is used for sequential traversals, i.e. iterate over the items of squensence
like list, string, tuple, etc.
➔ In Python, for loops only implements the collection-based iteration.

for variable_name in sequence


:
statement_1
statement_2
....

l = ["red", "blue", "green"]


for i in l:
print(i)
while Loop Statements
➔ is used to execute a block of statements repeatedly until a given condition
is satisfied.
➔ can fall under the category of indefinite iteration when the number of
times the loop is executed isn’t specified explicitly in advance.

while expression:
statement(s)

count = 0
while (count < 10):
count = count + 1
print(count)
The range() function
➔ is used to specific number of times whereby a set of code in the
for loop is executed.
➔ returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.

range(start_number, last_number,
increment_value)

for x in range(2, 6): for x in range(2, 30, 3):


print(x) print(x)
Loops with break
statement
➔ The break keyword in a for/while loop specifies the loop to be ended
immediately even if the while condition is true or before through all the items in
for loop.

i = 1 colors = ["blue", "green", "red"]


while i < 6: for x in colors:
print(i) print(x)
if i == 3: if x == "green":
break break
i += 1 print(x)
print(i)
Loops with continue
statement
➔ The continue statement in a for/while loop is used to force to execute
the next iteration of the loop while skipping the rest of the code inside
the loop for the current iteration only.

i = 0
while i < 7: for x in range(7):
i += 1 if (x == 4):
if i == 4: continue
continue print(x)
print(i)
➔ Definition syntax:
Function
Ex:
# A function to check
# whether n is even or
odd
def CheckEvenOdd(n):
if (n % 2 == 0):
print("even")
else:
print("odd")

➔ Calling a Python Function by using the name of the function followed by


parenthesis containing parameters of that particular function.
Ex:
# Driver code to call the function
CheckEvenOdd(2)
Types of Arguments
➔ A default argument is a parameter that assumes a default value if
a value is not provided in the function call for that argument.
➔ A keyword argument allows the caller to specify the argument
name with values so that caller does not need to remember the
order of parameters.
Ex:
# a Python function
Ex: def student(firstname, lastname):
# default arguments print(firstname, lastname)
def myFun(x, y=50): # Keyword arguments
print("x: ", x) student(firstname='Van A',
print("y: ", y) lastname='Nguyen')
student(lastname='Nguyen', firstname='Van
A')
File Handling

➔ Opening file
➔ Reading file
➔ Writing to file
➔ Appending file
➔ With statement
Opening file
➔ Using the function open(): File_object=open(filename,
■ Filename: the name of file mode)
■ mode represents the purpose of the opening file with one of the
following values: Ex:
# a file named "sample.txt",
● r: open an existing file for a read operation. will be opened with the
● w: open an existing file for a write operation. reading mode.
● a: open an existing file for append operation. file = open('sample.txt',
● r+: to read and write data into the file. 'r')
The previous data in the file will be overridden. # This will print every line
● w+: to write and read data. It will override existing data. one by one in the file
● a+: to append and read data from the file. It won’t override existing for each in file:
data. print (each)
Reading file
➔ Using the function read(): File_object.read(siz
e)
■ size <=0: returning a string that contains all characters in the file
# read() mode
file = open("sample.txt",
"r")
print (file.read())
■ size>0: return a string that contains a certain number of characters
size
# read() mode character wise
file = open("sample.txt",
"r")
print (file.read(3))
Closing File
➔ Using close() function to close the file and to free the memory space
acquired by that file
➔ used at the time when the file is no longer needed or if it is to be
opened in a different file mode.

File_object.close()
Writing to file
➔ Using the function write()to insert a string in a single line in the text file and the
function writelines()to insert multiple strings in the text file at a once time.
Note: the file is opened in write mode

File_object.write/
writelines(text)

file = open('sample.txt', 'w')


L = [“PCTU \n", "Python Programming \n", "Computer Science \
n"]
S = "Welcome\n"
# Writing a string to file
file.write(S)
# Writing multiple strings at a time
file.writelines(L)
file.close()
Appending File
➔ Using the function write/writelines() to insert the data at
the end of the file, after the existing data.
➔ Note: the file is opened in append mode,

file = open('sample.txt', 'w') # Write mode


S = "Welcome\n"
# Writing a string to file
file.write(S)
file.close()
# Append-adds at last
file = open('sample.txt', 'a') # Append mode
L = [“PCTU \n", "Python Programming \n", "Computer Science \n"]
file.writelines(L)
file.close()
With statement
➔ used in exception handling to make the code cleaner and to ensure
proper acquisition and release of resources.
➔ using with statement replaces calling the function close()

# To write data to a file using with statement


L = [“PCTU \n", "Python Programming \n", "Computer Science \
n"]
# Writing to file
with open("sample.txt", "w") as file1:
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
# Reading from file
with open("sample.txt", "r+") as file1:
# Reading form a file
print(file1.read())

You might also like