0% found this document useful (0 votes)
3 views28 pages

OS Lab - Week 8

Uploaded by

Alex Siryani
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
3 views28 pages

OS Lab - Week 8

Uploaded by

Alex Siryani
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 28

OS Lab - Python

Week 7
01
STRING METHODS
A Helping hand.
split() method
This method is used to divide any string data based on any particular separator or delimiter.

Example:

text = "Jack James"

print(text.split())
# Prints: [‘Jack’, ‘James’]

print(text.split('a'))
# Prints: ['J', 'ck J', 'mes']
replace() method
The .replace() method is used to replace the occurrence of the first argument with the second argument
within the string.

The first argument is the old substring to be replaced, and the second argument is the new substring that will
replace every occurence of the first one within the string.

Example:

fruit = "Strawberry"

print(fruit.replace('r', 'R'))
# Prints: StRawbeRRy
join() method
The string method .join() concatenates a list of strings together to create a new string joined with the
desired delimiter.

The .join() method is run on the delimiter and the array of strings to be concatenated together is passed in as
an argument.

Example:

x = "-".join(["Linux", "is", "awesome"])

print(x)
# Prints: Linux-is-awesome
count() method
count() method is used to count how many times a particular string appears in a text.

Example:

string= 'Python is a powerful programming language. It is very simple to use.’

print(string.count(“is”))
# Prints: 2
startswith() method
The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False.

Example:

text = "Python is easy to learn."

result = text.startswith('Python')

print(result)
# Prints: True
endswith() method
The endswith() method returns True if a string ends with the specified suffix. If not, it returns False.

Example:

text = "Python is easy to learn."

result = text.endswith('to learn.')

print(result)
# Prints: True
isalnum() method
The isalnum() method returns True if all characters in the string are alphanumeric (either alphabets or
numbers). If not, it returns False.

Example:

string = "P4ssw0rd"

print(string.isalnum())
# Prints: True
isalpha() method
The isalpha() method returns True if all characters in the string are alphabets. If not, it returns False.

Example:

name = "Jack"

print(name.isalpha())
# Prints: True
isdecimal() method
The isdecimal() method returns True if all characters in a string are decimal characters. If not, it returns False.

Example:

s = "28212"

print(name.isdecimal())
# Prints: True
02
FUNCTIONS & MODULES
A Helping hand.
Functions
Functions are simply pre-written codes that perform a certain task. For an analogy, think of the mathematical
functions available in MS Excel. To add numbers, we can use the sum() function and type sum(A1:A5) instead
of typing A1+A2+A3+A4+A5.

For example:

def greet_user():
print “Hello there”

#Calling the function


greet_user()

This example shows the simplest structure of a function. The line at uses the keyword def to inform Python
that you’re defining a function. This is the function definition, which tells Python the name of the function
and, if applicable, what kind of information the function needs to do its job. The parentheses hold that
information. In this case, the name of the function is greet_user(), and it needs no information to do its job, so
its parentheses are empty. (Even so, the parentheses are required.) Finally, the definition ends in a colon.

When you want to use this function, you call it. A function call tells Python to execute the code in the function.
Functions
Passing Information to a Function

Modified slightly, the function greet_user() can not only tell the user Hello! but also greet them by name. For
the function to do this, you enter username in the parentheses of the function’s definition at def greet_user().
By adding username here you allow the function to accept any value of username you specify. The function
now expects you to provide a value for username each time you call it. When you call greet_user(), you can
pass it a name, such as 'jesse', inside the parentheses.

def greet_user(username):
print “Hello there” + username
#Calling the function
greet_user(‘Jack’)

Arguments and Parameters

In the preceding greet_user() function, we defined greet_user() to require a value for the variable username.
Once we called the function and gave it the information (a person’s name), it printed the right greeting. The
variable username in the definition of greet_user() is an example of a parameter, a piece of information the
function needs to do its job.
Functions
Passing Arguments

Because a function definition can have multiple parameters, a function call may need multiple arguments. You
can pass arguments to your functions in a number of ways. You can use positional arguments, which need to
be in the same order the parameters were written; keyword arguments, where each argument consists of a
variable name and a value; and lists and dictionaries of values. Let’s look at each of these in turn.

When you call a function, Python must match each argument in the function call with a parameter in the
function definition. The simplest way to do this is based on the order of the arguments provided. Values
matched up this way are called positional arguments.

def describe_car(car_brand, car_color):


print("I have a %s ." % (car_brand))
print("My %s's color is %s." % (car_brand, car_color.title()))
#Calling the function
describe_car(“bmw”, “black”)
Functions
Keyword Arguments

A keyword argument is a name-value pair that you pass to a function. You directly associate the name and
the value within the argument, so when you pass the argument to the function, there’s no confusion. Keyword
arguments free you from having to worry about correctly ordering your arguments in the function call, and
they clarify the role of each value in the function call.

def describe_car(car_brand, car_color):


print("I have a %s ." % (car_brand))
print("My %s's color is %s." % (car_brand, car_color.title()))

#Calling the function


describe_car(car_brand=’bmw’, car_color=’black’)

The function describe_car() hasn’t changed. But when we call the function, we explicitly tell Python which
parameter each argument should be matched with. The order of keyword arguments doesn’t matter because
Python knows where each value should go.
Functions
Default Values

When writing a function, you can define a default value for each parameter. If an argument for a parameter is
provided in the function call, Python uses the argument value. If not, it uses the parameter’s default value. So
when you define a default value for a parameter, you can exclude the corresponding argument you’d usually
write in the function call. Using default values can simplify your function calls and clarify the ways in which
your functions are typically used.

def describe_car(car_brand, car_color=’black’):


print("I have a %s ." % (car_brand))
print("My %s's color is %s." % (car_brand, car_color.title()))

#Calling the function


describe_car(car_brand=’bmw’)
# OR
describe_car(‘bmw’)
Functions
Return Values

A function doesn’t always have to display its output directly. Instead, it can process some data and then return
a value or set of values. The value the function returns is called a return value. The return statement takes a
value from inside a function and sends it back to the line that called the function. Return values allow you to
move much of your program’s grunt work into functions, which can simplify the body of your program.

def get_formatted_name(first_name, last_name):


full_name = f"{first_name} {last_name}"
return full_name

#calling the function and store the return value into a variable
actor = get_formatted_name(‘jack’, ‘black’)
print (actor)

When you call a function that returns a value, you need to provide a variable that the return value can be
assigned to.
Functions
Making an Argument Optional

Sometimes it makes sense to make an argument optional so that people using the function can choose to
provide extra information only if they want to. You can use default values to make an argument optional.

def get_formatted_name(first_name, last_name, middle_name=''):


if middle_name:
full_name ="%s %s %s" % (first_name, last_name, middle_name)
else:
full_name ="%s %s" % (first_name, last_name)
return full_name.title()

actor = get_formatted_name('jack', 'black')


print(actor)
Modules
Python comes with a large number of built-in functions. These functions are saved in files known as modules.
To use the built-in codes in Python modules, we have to import them into our programs first. We do that by
using the import keyword. There are two ways to do it.

The first way is to import the entire module by writing import moduleName.

For instance, to import the random module, we write import random. To use the randrange() function in the
random module, we write random.randrange(1, 10).

If you find it too troublesome to write random each time you use the function, you can import the
module by writing import random as r (where r is any name of your choice). Now to use the randrange()
function, you simply write r.randrange(1, 10).

The second way to import modules is to import specific functions from the module by writing from
moduleName import name1[, name2[, ... nameN]].

For instance, to import the randrange() function from the random module, we write from random import
randrange. If we want to import more than one functions, we separate them with a comma. To import the
randrange() and randint() functions, we write from random import randrange, randint. To use the
Modules
Creating our Own Module

Besides importing built-in modules, we can also create our own modules. This is very useful if you have some
functions that you want to reuse in other programming projects in future. Creating a module is simple. Simply
save the file with a .py extension and put it in the same folder as the Python file that you are going to import
it from.

Installing Modules

With Python, you can build just about anything, from simple scripts to full applications. The Python language,
however, doesn’t come pre-installed with all of the fancy features you might want (or require). When you
need particular functionality, you can look toward Python packages. A package structures Python modules,
which contain pre-written code that other developers have created for you. Modules are handy when you are
looking for specific functionality.

You can use pip3, Python’s package manager, to install and manage Python packages.

Example: pip3 install scrapy OR python3 -m pip install scrapy


Questions?
03
WORKING WITH FILES
Reading and storing data.
Reading From Files
Learning to work with files and save data will make your programs easier for people to use. Users will be able
to choose what data to enter and when to enter it. People can run your program, do some work, and then
close the program and pick up where they left off later.

An incredible amount of data is available in text files. Text files can contain weather data, traffic data,
socioeconomic data, literary works, and more. Reading from a file is particularly useful in data analysis
applications, but it’s also applicable to any situation in which you want to analyze or modify information
stored in a file.

When you want to work with the information in a text file, the first step is to read the file into memory.
You can read the entire contents of a file, or you can work through the file one line at a time.

Reading an Entire File

To begin, we need a file with a few lines of text in it.

with open(‘my_file.txt.’) as file_object:


contents = file_object.read()
print (contents)
Reading From Files
The first line of this program has a lot going on. Let’s start by looking at the open() function. To do any work
with a file, even just printing its contents, you first need to open the file to access it. The open() function
needs one argument: the name of the file you want to open. Python looks for this file in the directory where
the program that’s currently being executed is stored.

The keyword with closes the file once access to it is no longer needed. Notice how we call open() in this
program but not close(). You could open and close the file by calling open() and close(), but if a bug in your
program prevents the close() method from being executed, the file may never close. This may seem trivial,
but improperly closed files can cause data to be lost or corrupted. And if you call close() too early in your
program, you’ll find yourself trying to work with a closed file (a file you can’t access), which leads to more
errors.

Reading Line by Line

When you’re reading a file, you’ll often want to examine each line of the file. You might be looking for certain
information in the file, or you might want to modify the text in the file in some way. You can use a for loop on
the file object to examine each line from a file one at a time:

filename = “myfile.txt”
Writing To A File
One of the simplest ways to save data is to write it to a file. When you write text to a file, the output will still
be available after you close the terminal containing your program’s output. You can examine output after a
program finishes running, and you can share the output files with others as well. You can also write programs
that read the text back into memory and work with it again later.

Writing to an Empty File

To write text to a file, you need to call open() with a second argument telling Python that you want to write to
the file.

filename = “my_file.txt”
with open(filename, ‘w’) as file_object:
file_object.write(“Am adding a new line”)

The call to open() in this example has two arguments. The first argument is still the name of the file we want
to open. The second argument, 'w', tells Python that we want to open the file in write mode. You can open a
file in read mode ('r'), write mode ('w'), append mode ('a'), or a mode that allows you to read and
write to the file ('r+'). If you omit the mode argument, Python opens the file in read-only mode by
default.
Writing To A File
Writing Multiple Lines

The write() function doesn’t add any newlines to the text you write. Even by running write() twice, the text will
be squished next to each other. We can solve this by appending a \n to the end of the string we are adding.

Appending to a File

If you want to add content to a file instead of writing over existing content, you can open the file in append
mode. When you open a file in append mode, Python doesn’t erase the contents of the file before returning
the file object. Any lines you write to the file will be added at the end of the file. If the file doesn’t exist yet,
Python will create an empty file for you.

filename = “my_file.txt”
with open(filename, ‘a’) as file_object:
file_object.write(“Am adding a new line”)
Questions?

You might also like