0% found this document useful (0 votes)
13 views27 pages

Lecture 2 - Python Programming

Uploaded by

modisahil67
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)
13 views27 pages

Lecture 2 - Python Programming

Uploaded by

modisahil67
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/ 27

Python

Programming
COMP 8347
Usama Mir
[email protected]

1
 Topics:
 If statements
 Loops
Python  Exception handling

Basics 


Functions
File Input/Output
 Modules

2
Control Flow

 Conditional branching
 if statements
 Looping
 while
 for … in
 Exception handling
 Function or method call

3
if Statements
 suite: a block of code, i.e. a
sequence of one or more
statements
 Syntax:
if bool_expression1:
suite1 • No parenthesis or braces
elif bool_expression2: • : Use indentation for block
structure
suite2 if a < 10:
… print(“few”)
elif bool_expressionN: elif a < 25:
print(“some”)
suiteN
else:
else: print(“many”)
else_suite
4
 Clear starting condition

Loops =  Clear finishing condition

What is it?
 Some statement that leads the loops
from its start to the end

5
Loops: Python vs. Java

 Python:
 while loops
 for loops …. for i in range (5)
 Java:
 while loops
 do .. while
 for loops (int i = 0…..)

6
while Statements

 Used to execute a suite 0 or more times


 number of times depends on while loop’s Boolean expression.
 Syntax:
while bool_expression:
suite
 Example:
x, sum = 0,0
while x < 10:
sum += x
x += 2
print(sum, x) #What is final value of sum and x

Answer: sum=20, x=10


7
for … in Statements

 Syntax:
for variable in iterable:
suite
 Example: fruits = [‘apple’, ‘pear’, ‘plum’, ‘peach’]
for item in fruits:
print(item)
 Alternatively
for i in range(len(fruits)):
print(fruits[i])

8
for … in Statements - Enumerate

Output

9
Break and Continue

Iter# num num>20? Num%2==0? print(num)


0 11 n n 11
1 8 n y
2 3 n n 3
3 25 y
10
Exception Handling
 Functions or methods indicate errors or other
important events by raising exceptions.
 Syntax (simplified):
try:
try_suite
except exception1 as variable1:
exception_suite1

except exceptionN as variableN
finally:
# cleanup
 variable part is optional
11
Exception Handling – Example 1
Example:
s = input('Enter number: ')
try:
n = float(s)
print(n, ' is valid. ')
except ValueError as err:
print(err)

• If user enters ‘8.6’ output is: 8.6 is valid


• If user enters ‘abc’, output is:
ValueError: could not convert string to float:
‘abc'
12
Exception Handling – Example 1 – Scenario
 Part 1
 Create a list with the following values 5, 10, 30, 40, 9.9
 Run a for loop till the size of the list
 Take a variable item and store each index of the list as a power of two.
E.g., 1st value in item is 0, then 1, then 4, then 9, and so on
 Print the index and the item. This program will give error for the index
values which are out of the above list’s range
 Part 2
 For the above program, use try and except statements to print the index
error when the index is out of bound/range. Your output should look like
this:

13
Exception Handling – Example 2 – Part 1

14
Exception Handling – Example 2 – Part 2

15
Functions

 Function definition:
A block of reusable
code that is used
to perform a
single action

Ex. A code without

a function →

16
Functions – Example 1

 Same code implemented with a function

17
Functions – Example 2

# function with two arguments


def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)

# function call with two values


add_numbers(5, 4)

# Output: Sum: 9

18
Functions – Example 3 – With Variable Arguments

19
Functions – Class Exercise

Write a function named max that accepts two


integer values as arguments and returns the value
that is the greater of the two. For example, if 7 and
12 are passed as arguments to the function, the
function should return 12. Use the function in a
program that prompts the user to enter two integer
values. The program should display the value that
is the greater of the two.

20
Functions – Class Exercise – Sample Solution

21
File Input/Output

 Open a file
 f = open(filename, mode)
 mode is optional; possible values:
 ‘w’ = write
 ‘r’ = read (default)
 ‘a’ = append
 ‘rb’(‘wb’) = read (write) in binary
 Example:
 f = open(“text.txt”)
22
File Methods
 Read data from a file
print(f.read())

 Writing data on a file


 f = open(“test.txt”, ‘w’)
 f.write(“Hello Python”)

 f.read(n): reads at most n bytes from f


 f.readline(): reads only one line
 f.readlines(): reads all the lines to the end of file
and return them as a list
 f.close(): closes a file and free up the resources

23
Use strip() Function

 Python’s strip( ) function is used to remove unwanted


characters from a string.
Ex.

str5 = ‘++++++Python Tutorial****** $$$$$’


print (“\n Given string is = “, str5)
str6 = str5. strip ( ‘ $*+’ )
print (” Stripping the ‘+’, ‘*’ and ‘$’ symbols on both sides of the string is = “, str6)
Output:
Given string is = ++++++Python Tutorial****** $$$$$
Stripping the ‘+’, ‘*’ and ‘$’ symbols on both sides of the string is = Python Tutorial

24
Modules

 Modules: Contain additional functions and custom data


types.
 Ex. import calendar
 Other examples:
 import os
 import math
 import datetime

25
Module Example – Calendar

26
References

 Slides from Dr. Arunita and Dr. Saja


 https://www.softwaretestinghelp.com/pyth
on/input-output-python-files/
 https://www.tutorialspoint.com/difference
-between-for-loop-and-while-loop-in-
python
 Programming in Python 3 A complete
introduction to the python language (2nd
Ed) by Mark Summerfield. Addison Wesley
2010.
 https://www.w3schools.com/python/
 https://www.tutorialsteacher.com/python/
error-types-in-python
 https://www.geeksforgeeks.org/python-
functions/
 https://www.geeksforgeeks.org/python-
calendar-module/ 27

You might also like