0% found this document useful (0 votes)
2 views39 pages

Conditional Looping, Functions, File Manipulation

The document provides an overview of Python programming concepts focusing on conditional looping, functions, and file manipulation. It explains the use of conditional statements (if, elif, else), looping constructs (for and while loops), and the definition and usage of functions, including passing arguments and return values. Additionally, it covers common file operations such as opening, reading, writing, and checking for file existence.

Uploaded by

mukisasamuel2020
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)
2 views39 pages

Conditional Looping, Functions, File Manipulation

The document provides an overview of Python programming concepts focusing on conditional looping, functions, and file manipulation. It explains the use of conditional statements (if, elif, else), looping constructs (for and while loops), and the definition and usage of functions, including passing arguments and return values. Additionally, it covers common file operations such as opening, reading, writing, and checking for file existence.

Uploaded by

mukisasamuel2020
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/ 39

10/5/23

CONDITIONAL LOOPING, FUNCTIONS


& FILE MANIPULATION

INTRODUCTION TO PYTHON &


VIRTUAL ENVIRONMENT
WHAT ARE WE GOING TO LEARN TODAY?

ØConditional Looping
ØFunctions
ØFile Manipulation
ØHands On

1
10/5/23

CONDITIONAL
LOOPING

WHAT ARE CONDITIONAL AND


LOOPING STATEMENTS?
• A statement that directs the flow • A looping statement is a
of execution based on a condition. statement or a set of statements
Conditional statements in Python that runs indefinitely until a
are denoted by the keywords if, terminating condition is met.
elif, and else.

2
10/5/23

CONDITIONAL STATEMENTS

• The if statement checks a condition


and executes a block of code if it is
true, and another block of code if it is
false.
• If more than one condition must be
checked, the else if statement can
be used in conjunction with the if
statement.

IF STATEMENT

We use operators
from the previous
chapter as
conditions in the
statement.

The two codes in this example mean:


“If a is less than b, print out the message that says
so.”

3
10/5/23

ELIF (ELSE IF) STATEMENT

Here, the two codes in this example mean:


“If a is less than b, print out the message that says
so. Else, if a is equal to b, print out the message that
says ‘a is equal to b’.”

ELSE STATEMENT

Here, the code means:


“If a is less than b, print out a message that says so.
Else, if a is equal to b, print out the message that says
so. Otherwise, print out a message that says a is
greater than b.”

4
10/5/23

IF…ELSE STATEMENT IN ONE LINE

The if…else statement doesn’t have


to be written in multiple lines of code.
You can just put them all in one line.

CONDITIONALS AND LOGICAL OPERATORS

We use logical operators (and, or,


not) if we want to specify more
than one condition.

10

5
10/5/23

CONDITIONALS AND LOGICAL OPERATORS

We use logical operators (and, or,


not) if we want to specify more
than one condition.

11

NESTED CONDITIONALS

Just like other Python commands, we can


put another if…else statement inside one
if…else statement.

12

6
10/5/23

LOOPING STATEMENTS

for loop while loop


• Executes for a predetermined • Executes for an indefinite
number of times. number of iterations
• The looping is done in two ways:
• They could execute indefinitely
• Using a fixed number: Define if the condition is met.
the number of times the loop
should repeat, using the
range() function
• Using items: Based on the
number of items present in a
list, dictionary, tuple, etc.

13

FOR LOOPS

Consider a list containing


the names of three
magicians. We are going
to print the names of the
magicians.

Here, we tell Python that “For every


magician in the list of magicians, print
the magician’s name.”

14

7
10/5/23

FOR LOOPS

We use the for loop to


print out the same
message using different
magicians’ names.

15

FOR LOOPS

Let’s add another


message for each
magician.

16

8
10/5/23

FOR LOOPS

It is important to pay close attention


to indentations when working with
for loops.

Try to spot the difference between


this code and the code in the
previous slide.

17

FOR LOOPS

What happens when you


forget to indent?

18

9
10/5/23

FOR LOOPS

We can use for


loops to add
elements to a list.
This helps us to
save time when
adding elements.

This way, we don’t have to repeat the


same code over and over again just
to add elements to the list.

19

FOR LOOPS

We’re looping through the


Same goes with key-value pairs of the
dictionary to display the
dictionaries. following message.

20

10
10/5/23

FOR LOOPS

When we use a for loop


on a string, the string is
broken down into
characters and displayed
in the manner as shown.

21

WHILE LOOPS

while loops are


indefinite loops that
executes the
statement as long
as the condition is
We first assign the value 1 to a variable called true.
x.

Next, we print out the value of x as it increases


by 1 during each iteration.

All this is done while x is less than 6.

22

11
10/5/23

WHILE LOOPS

Here is an example. Suppose we run an online shopping business. We have


some users who have registered on the website but are yet to be confirmed.
How are we going to move these users from a list of unconfirmed users to
another list once their registration is confirmed?

23

WHILE LOOPS

Using a while loop and the


.pop() method, we can move the
users to a new list once their
registration is confirmed.

As you can see in the final


two lines of output, the first
list is now empty, and the
second list now contains
values from the first list.

24

12
10/5/23

COMBINING LOOPS AND CONDITIONALS

We can use both


conditional
statements and loops
in one block of code.

In this block of code, we have a dictionary and a list. In the


loop, we are going to print a greeting to each user from the
dictionary. Then we check to see if the names in the list matches
with any key in the dictionary. When it does, the code will print
an extra message.

25

BREAK STATEMENT

When we include
the line break in
our loop, the
looping will stop.

We tell Python to stop the loop


once i is equal to 3.

26

13
10/5/23

CONTINUE STATEMENT

When we include a
continue statement in our
loop, Python will stop the
current iteration and
continue with the next. In
other words, Python will
skip the current iteration.

When i is equal to 3, Python


will skip the command to
print out that value, which is
3, and continue with the rest
of the iteration.

27

FUNCTIONS

28

14
10/5/23

WHAT ARE FUNCTIONS?


• A function is a collection of
related statements that
accomplishes a specific task.
• Functions aid in the division of
our program into smaller,
modular chunks. As our program
grows in size, functions help to
keep it organised and
In this example, the function is called manageable.
squared. It will take in a value, x, and
returns the value that has been • It also avoids repetition and
incremented by calculating its makes the code reusable as it
exponentiation by 2. can be called multiple times.

29

TYPES OF FUNCTIONS

1. Built-in functions: Functions that are


built into Python. Example: print(),
and len().
2. User-defined functions: Functions
that are defined by the users
themselves. We will look at
examples later on.

30

15
10/5/23

DEFINING A FUNCTION

This is an example of a
user-defined function.

We create a function
called greet_user()
that simply prints out a
greeting when called.

31

PASSING INFORMATION TO A FUNCTION

We pass arguments
into a function by
using a parameter.

32

16
10/5/23

WHAT’S IN A FUNCTION?

This is the name of the


function. This is a parameter.

} This is the body


of the function.

This is an argument.

33

PASSING ARGUMENTS

Python matches each argument


in the function call with a
parameter in the function
definition. This is called
“positional arguments”.

34

17
10/5/23

PASSING ARGUMENTS

Order matters in positional arguments. Can


you see what’s wrong with the output?

35

PASSING ARGUMENTS

We are going to fix the mistake by


using keyword arguments.

36

18
10/5/23

PASSING ARGUMENTS

This way, you can reverse the order of the arguments, as long as you
specify which parameter each associates to.

As
Notice
you that
can see,
we’ve
we’ve
reversed
reversed
the order,
the order,
but
butbecause
becausewewe
specify
specify
which
whichargument
argument
associates to which parameter, we get the
correct output.

37

DEFAULT VALUES

This is called a default value.

When we have default values, we don’t


have to specify this argument when we
call the function, unless you want to
change ‘dog’ to another animal.

38

19
10/5/23

Because positional arguments, keyword arguments and default


values can all be used together, you can see that there are
multiple ways to call the function.

As an example, try running the following code.

39

RETURN VALUES

Returning a
simple value

40

20
10/5/23

RETURN VALUES

Making an argument optional


Here, the middle_name
argument is optional. We provide
an empty default value unless
the user provides a value.

41

RETURN VALUES

Using a function with a while loop

Try running this code and see


what happens when you
provide your name.

42

21
10/5/23

FUNCTIONS AND LISTS

We can use
functions on lists
to save time

43

FUNCTIONS AND LISTS

This is how it is done without using functions

Consider a company that creates 3D


printed models of designs submitted by
users. Designs to be printed are stored in
a list, and they’re moved to a separate
list once they are printed.

44

22
10/5/23

FUNCTIONS AND LISTS

Functions provide a shorter and


quicker way to do the job.

45

FUNCTIONS AND LISTS

We can just simply


call the function on
the list.

46

23
10/5/23

FUNCTIONS AND LISTS

Let’s try to apply the


function we just
created on a
different list.

47

PASSING AN ARBITRARY NUMBER OF ARGUMENTS

Sometimes we don’t know ahead of time how many


arguments we want to pass in the function. In this case,
we add an asterisk (*) in front of the parameter name
to make an empty tuple and collect whatever values
the user provides as arguments.

48

24
10/5/23

PASSING AN ARBITRARY NUMBER OF ARGUMENTS

Let’s try running the function from the previous slide.

Thanks to the
arbitrary argument
we created earlier, we
can pass as many
arguments we want in
our function.

49

PASSING AN ARBITRARY NUMBER OF ARGUMENTS

We can mix both positional and arbitrary arguments in our function.

In this function, any values


provided to the parameter
“size” is considered as a
positional argument,
whereas any values
passed to the “toppings”
parameter are arbitrary
arguments.

50

25
10/5/23

PASSING AN ARBITRARY NUMBER OF ARGUMENTS

If we’re going to add more arguments, it is better to add double


asterisks in front of the parameter name when defining the
function.

51

FILE
MANIPULATION

52

26
10/5/23

COMMON FILE MANIPULATION OPERATIONS IN PYTHON

1.Opening a File:
file = open ('cuba.txt','r') # Opens ‘cuba.txt' in read mode
2.Reading from a File: content = file.read() # Reads the entire content of the file
3.Writing to a File: file.write ("This is lisa.")
4.Closing a File: file.close()

5.Appending to a File:
6.Checking if a File Exists:
7.Renaming and Deleting Files:
8.Working with Binary Files:

Note: Understand how to work with files (text files, CSV files, binary files, etc.)

20XX PRESENTATION TITLE 53

53

COMMON FILE MANIPULATION OPERATIONS IN PYTHON

1.Opening a File:
2.Reading from a File:
3.Writing to a File:
4.Closing a File: with open('example.txt', 'a') as file:
file.write("This is a new line.")
5.Appending to a File:
import os
6.Checking if a File Exists: if os.path.exists('example.txt'):
7.Renaming and Deleting Files: print("The file exists.")
else:
print("The file does not exist.")
8.Working with Binary Files:

20XX PRESENTATION TITLE 54

54

27
10/5/23

COMMON FILE MANIPULATION OPERATIONS IN PYTHON

1.Opening a File:
2.Reading from a File:
3.Writing to a File:
4.Closing a File:
5.Appending to a File:
6.Checking if a File Exists: import os
os.rename('old_file.txt', 'new_file.txt') # Renames a file
7.Renaming and Deleting Files: os.remove('file_to_delete.txt') # Deletes a file

8.Working with Binary Files:


with open('binary_file.bin', 'wb') as file:
file.write(b'01010110')

20XX PRESENTATION TITLE 55

55

FILE MANIPULATION IN
PYTHON (SELF STUDY)

56

28
10/5/23

READING AN ENTIRE FILE

• Make sure the file is in the same working directory as your IDE.

The with keyword will close the file


The open() function will ‘open’ the file that once access to it is no longer
we’re going to access. Python will look for the needed.
file that is provided as the argument for this
function in the same working directory.
Python will then assign the object returned by
the function to file_object.

57

Reading an entire file

This is what you


get when you
run the code.

Our .txt file contains 3 lines of


numbers for pi. When we run
the print() function, we can see
the contents of our file.

58

29
10/5/23

READING AN ENTIRE FILE

The read() function often returns an extra line of (empty) string at the end of the
output. To prevent this from happening, you can add the .rstrip() method at the end
of contents in the print() function.

59

Reading an entire file


But what if the file that you want to read is located in a
different path from your working directory?

Let’s try to move our file to a


different location. Here, the
file is located in the
Documents folder of our
computer. To read the file into
Python, we have to include
the full address of the
You can specify the path using
location of the file.
variable assignment.

60

30
10/5/23

READING LINE BY LINE

The .txt file may contain


multiple lines of contents.
We can read in these lines
using a for loop.

61

MAKING A LIST OF LINES FROM A FILE

Another way to do
this is by using
.readlines()
method on the file
object.

62

31
10/5/23

WORKING WITH A FILE’S CONTENTS

Once the file is in the


memory, we can do
whatever we want with its
contents. In this case, let’s
combine the lines into one
continuous string of digits.

63

WORKING WITH A FILE’S CONTENTS

Let’s remove the extra


whitespace between
the digits by using the
.strip() method
instead of .rstrip().

64

32
10/5/23

WHAT ABOUT LARGE FILES?

This time, we will read


in a .txt file that
contains the string of pi
up to 1,000,000 decimal
places.

65

WHAT ABOUT LARGE FILES?

It is said that since pi has an indefinite


number of digits, your birthday might
appear in pi.

But what about the first 1,000,000


digits of pi? Does your birthday appear
in it?

66

33
10/5/23

WRITING TO A FILE

Writing to an empty file We can export our data into a


.txt file using Python.

We add an argument, ‘w’, which


stands for ‘write’. We are going
to write in the string into the file
Writing multiple lines object called “programming.txt”.

This is how you write


multiple lines of strings
into the file.

Open the file


(programming.txt)
to see the results!

67

WRITING TO A FILE

What if you want to add more We use the ‘a’ argument


lines to the file even after inside the open() function to
you’ve finished writing it? append more lines to the file.

68

34
10/5/23

ANALYZING TEXT

Now that you have


read in a text file
into Python, you
can analyze the
text using Python.

In this block of code,


we are counting the
words inside a text
file.

69

WORKING WITH MULTIPLE FILES

Let’s count the words contained First, we are going to create a


inside multiple files! function so that we can run the code
multiple times.

If the file is
unavailable in the
working directory, an
error message will be
printed out.

If the file is
available in the
working directory,
count the number
of words.

70

35
10/5/23

WORKING WITH MULTIPLE FILES

We are now going to use the function on a


list of file names.

We don’t have the


‘siddartha.txt’ file in our
working directory. Thus,
this message is printed
out.

71

STORING DATA

The most general way to store


data is through a JSON file.

JSON (JavaScript Object Notation)


files can be used in many
programming languages.

We will use a Python


module called json.
In these two blocks of
code, we write a list of
numbers into a json file.
We then read the file
back into Python.

72

36
10/5/23

HANDS ON

73

CONDITIONAL LOOPING
1. Imagine an alien was just shot down in a game. Create a variable called
alien_color and assign it a value of ‘green’, ‘yellow’, or ‘red’. Write an if
statement to test whether the alien’s color is green. If it is, print a message that
the player just earned 5 points. If it isn’t, print a statement that the player just
earned 10 points.
2. Think of at least three kinds of your favorite pizza. Store these pizza names in a
list, and then use a for loop to print the name of each pizza.
3. Make a list called sandwich_orders and fill it with the names of various
sandwiches. Then make an empty list called finished_sandwiches. Loop
through the list of sandwich orders and print a message for each order. As each
sandwich is made, move it to the list of finished sandwiches. After all the
sandwiches have been made, print a message listing each sandwich that was
made.

74

37
10/5/23

FUNCTIONS

1. Write a function called favorite_book() that accepts one parameter, title.


The function should print a message, such as One of my favorite books is
Alice in Wonderland. Call the function, making sure to include a book title as
an argument in the function call.
2. Write a function called make_shirt() that accepts a size and the text of a
message that should be printed on the shirt. The function should print a sentence
summarizing the size of the shirt and the message printed on it. Call the function
once using positional arguments to make a shirt. Call the function a second time
using keyword arguments.
3. Make a list containing a series of short text messages. Pass the list to a function
called show_messages(), which prints each text message.

75

FILE MANIPULATION

1. Open a blank file in your text editor and write a few lines
summarising what you’ve learned about Python so far. Start
each line with the phrase:
In Python you can…
Save the file as learning_python.txt in the same directory as
your exercises from this chapter. Write a program that reads the
file and prints what you wrote three times. Print the contents
once by reading in the entire file, once by looping over the file
object, and once by storing the lines in a list and then working
with them outside the with block.

76

38
10/5/23

FILE MANIPULATION (CONT)

2. Write a program that prompts the user for their name. When
they respond, write their name to a file called guest.txt.
3. Write a program that prompts for the user’s favorite number.
Use json.dump() to store this number in a file. Write a
separate program that reads in this value and prints the
message, “I know your favorite number! It’s ____.”

77

THANK YOU

78

39

You might also like