Unit 2
Unit 2
Functions
A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
OUTPUT: Hello from a function
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
OUTPUT: Emil Refsnes
Tobias Refsnes
Linus RefsnesTry it Yourself »
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information
that are passed into a function.
Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
OUTPUT: I am from Sweden
I am from India
I am from Norway
I am from Brazil
my_function(fruits)
OUTPUT: apple
banana
cherry
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
OUTPUT: 15
25
45
Example
def myfunction():
pass
OUTPUT:NO ERROR
1. Write a program to define a function with multiple return values.
def name():
return "John","Armin"
output: Sum: 5
Sum: 10
Sum: 15
Strings
Arrays
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
output:e
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
output:13
Check String
character is present in a string, we can use the keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
output; True
Use it in an if statement:
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
output: Yes, 'free' is present.
Slicing Strings
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
output: llo
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
output: Hello
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
output: llo, World!
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
Modify Strings
Upper Case
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
output: HELLO, WORLD!
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
output: hello, world!
Remove Whitespace
Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
output: Hello, World!
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
output: Jello, World!
Split String
Example
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
output: ['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
output: HelloWorld
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
output: Hello World
tring Format
As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
output: txt = "My name is John, I am " + age
TypeError: must be str, not int
But we can combine strings and numbers by using f-strings or
the format() method!
Example
Create an f-string:
age = 36
txt = f"My name is John, I am {age}"
print(txt)
output: My name is John, I am 36
Placeholders and Modifiers
A placeholder can contain variables, operations, functions, and modifiers to
format the value.
Example
Add a placeholder for the price variable:
price = 59
txt = f"The price is {price} dollars"
print(txt)
output: The price is 59 dollars
1. Write a program to find the length of the string without using any library
functions.
string=input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)
output: Enter string:lalunaik
Length of the string is:
8
2. Write a program to check if the substring is present in a given string or
not.
tring=input("Enter string:")
sub_str=input("Enter word:")
if(string.find(sub_str)==1):
print("Substring not found in string!")
else:
print("Substring in string!")
output: Enter string:lalu
Enter word:lalu
Substring in string!
Lists
List
Lists are used to store multiple items in a single variable.
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
output: ['apple', 'banana', 'cherry', 'apple', 'cherry']
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
output: 3
Example
String,int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
output: ['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False]
Access Items
List items are indexed and you can access them by referring to the index
number:
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
output: cherry
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
output: ['cherry', 'orange', 'kiwi']
Example
This example returns the items from the beginning to, but NOT including, "kiwi":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
output: ['apple', 'banana', 'cherry', 'orange']
Example
This example returns the items from "cherry" to the end:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
output: ['cherry', 'orange', 'kiwi', 'melon', 'mango']
Example
This example returns the items from "orange" (-4) to, but NOT including
"mango" (-1):
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
output: ['orange', 'kiwi', 'melon']
Append Items
To add an item to the end of the list, use the append() method:
ExampleGet your own Python Server
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
output: ['apple', 'banana', 'cherry', 'orange']
Insert Items
To insert a list item at a specified index, use the insert() method.
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
output: ['apple', 'orange', 'banana', 'cherry']
ExampleGet
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
output: ['apple', 'cherry']
ExampleGet
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
output: apple
banana
cherry
Loop Through the Index Numbers
You can also loop through the list items by referring to their index number.
Example
Print all items by referring to their index number:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
output: apple
banana
cherry
Example
Print all items, using a while loop to go through all the index numbers
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
output: apple
banana
cherry
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
output: ['apple', 'banana', 'cherry']
Example
Join two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
total = 0
# creating a list
list1 = [11, 5, 17, 18, 23]
# Iterate each element in list
# and add them in variable total
for ele in range(0, len(list1)):
total = total + list1[ele]
# printing total value
print("Sum of all elements in given list: ", total)
output: Sum of all elements in given list: 74
ii. Insertion
# creating a list
#inserts an item at a specific index in a list.
fruit = ["banana","cherry","grape"]
fruit.insert(1,"apple")
print(fruit)
iii. slicing
my_list = [1, 2, 3, 4, 5]
print(my_list[:])
output: [1, 2, 3, 4, 5]
my_list = [1, 2, 3, 4, 5]
print(my_list[2:])
output: [3, 4, 5]
my_list = [1, 2, 3, 4, 5]
print(my_list[:2])
output: [1, 2]
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
output: [3, 4]
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value