You are on page 1of 43

Module 2_Python

Python Lists
• Lists are used to store multiple items in a single
variable.

• Lists are one of 4 built-in data types in Python used to


store collections of data, the other 3 are Tuple, Set, and
Dictionary, all with different qualities and usage.

• Lists are created using square brackets:

• mylist = ["apple", "banana", "cherry"]


The important characteristics of Python lists are as follows:
Lists are ordered.

• A list is not merely a collection of objects. It is an ordered


collection of objects.
Lists can contain any arbitrary objects.
• A list can contain any assortment of objects.
• The elements of a list can all be the same type:

• Or the elements can be of varying types


List elements can be accessed by index.
• Individual elements in a list can be accessed using an
index in square brackets.
Negative List Indexing
• Lists can be nested to arbitrary depth.
• You have seen that an element in a list can be any sort of object.
That includes another list.
• A list can contain sublists, which in turn can contain sublists
themselves, and so on to arbitrary depth.
• Lists are mutable.
• Most of the data types you have encountered so far like
Integer or float objects, for example, are primitive units
that can’t be further broken down.
• These types are immutable, meaning that they can’t be
changed once they have been assigned.

• Modifying a Single List Value


• A single value in a list can be replaced by indexing and
simple assignment:
Lists are dynamic.
• When items are added to a list, it grows as needed:

• Similarly, a list shrinks to accommodate the removal of items:


Getting a List from Another List with
Slices
In a slice, the first integer is the index where the slice starts. The second Integer
is the index where the slice ends.

A slice goes up to, but will not include, the value at the second index. A slice
evaluates to a new list value.
Tuples

• Tuples are used to store multiple items in a single variable.

• Tuple is one of 4 built-in data types in Python used to store


collections of data, the other 3 are List, Set, and Dictionary
, all with different qualities and usage.

• A tuple is a collection which is ordered


and unchangeable.

• Tuples are written with round brackets.

mytuple = ("apple", "banana", "cherry")


• Ordered
When we say that tuples are ordered, it means that the items
have a defined order, and that order will not change.

• Unchangeable / immutable
Tuples are unchangeable, meaning that we cannot change, add
or remove items after the tuple has been created.

• Allow Duplicates
Since tuples are indexed, they can have items with the same
value:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
• Tuple Items - Data Types

Tuple items can be of any data type:


tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

tuple1 = ("abc", 34, True, 40, "male")

• Access Tuple Items


You can access tuple items by referring to the index number, inside square
brackets:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

• How to have only one value in your tuple,

tuple1 = ('hello’,)

tuple2 = ('hello')
Basic Tuples Operations

Tuples respond to the + and * operators much like


strings; they mean concatenation and repetition here too,
except that the result is a new tuple, not a string.
Dictionary Data Type
Dictionaries are used to store data values in key:value pairs.

Python dictionary is an ordered collection (starting from Python


3.7) of items.

It stores elements in key/value pairs. Here, keys are unique


identifiers that are associated with each value.

Defining a Dictionary

A dictionary can be created by placing a sequence of elements


within curly {} braces, separated by ‘comma’. Dictionary holds
pairs of values, one being the Key and the other corresponding
pair element being its Key:value.
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

Values in a dictionary can be of any data type and can be


duplicated, whereas keys can’t be repeated and must
be immutable.
Dictionaries and lists share the following characteristics:

• Both are mutable.

• Both are dynamic. They can grow and shrink as needed.

• Both can be nested. A list can contain another list. A dictionary


can contain another dictionary. A dictionary can also contain a list,
and vice versa.
Dictionaries differ from lists primarily in how elements are
accessed:

• Unlike lists, items in dictionaries are unordered.

>>> spam = ['cats', 'dogs', 'moose’]


>>> bacon = ['dogs', 'moose', 'cats’]
>>> spam == bacon
False

>>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8’}


>>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> eggs == ham
True
FUNCTIONS
You’re already familiar with the different functions
• print(),
• Input(), and
• len() functions

Python provides several builtin functions like these,


but you can also write your own functions.

A function is like a miniprogram within a program.


• In general, you always want to avoid
duplicating code.

• If you ever decide to update the code, for


example, you find a bug you need to fix—you’ll
have to remember to change the code
everywhere you copied it.

• As you get more programming experience,


you’ll often find yourself deduplicating code,

• Deduplication makes your programs shorter,


easier to read, and easier to update.
def hello(): print('Howdy!')

print('Howdy!') print('Howdy!!!')
print('Hello there.')
print('Howdy!!!')
print('Howdy!')
print('Hello there.')
print('Howdy!!!')
hello() print('Hello there.')
hello() print('Howdy!')
hello() print('Howdy!!!')
print('Hello there.')

Howdy! Howdy!

Howdy!!! Howdy!!!

Hello there. Hello there.

Howdy! Howdy!

Howdy!!! Howdy!!!

Hello there. Hello there.

Howdy! Howdy!

Howdy!!! Howdy!!!

Hello there. Hello there.


A major purpose of functions is to group code that
gets executed multiple times.

Without a function defined, you would have to copy


and paste the code each time.
def Statements with Parameters
• When you call the print() or len() function, you pass
them values, called arguments, by typing them between
the parentheses. You can also define your own functions
that accept arguments.
Example:
def hi(name):
print('Hello, ' + name)
hi('Alice’)
hi('Bob’)

Hello, Alice
Hello, Bob
Parameter
def hi(name):
print('Hello, ' + name)
hi('Alice’)
hi('Bob’)

The definition of the hi() function in this program has a


parameter called name.
Parameters are variables that contain arguments.
When a function is called with arguments, the
arguments are stored in the parameters.
The first time the hi() function is called, it has passed
Define, Call, Pass, Argument, Parameter

Function
Define
Parameter
def sayHello(name):
Call print('Hello, ' + name)
sayHello('Al') Argument

The def keyword defines the sayHello() function.


The sayHello('Al') calls the now-created function, sending the
execution to the top of the function’s code. This function call is
also known as passing the string value 'Al' to the function.
A value being passed to a function in a function call is an
argument.
The argument 'Al' is assigned to a local variable named name.
Variables that have arguments assigned to them are parameters.
Return Values
When you call the len() function and pass it an
argument such as 'Hello’,

The function call evaluates to the integer value 5,


which is the length of the string you passed it.

In general, the value that a function call evaluates


to is called the return value of the function.
Return Statements
When creating a function using the def statement, you can
specify what the return value should be with a return
statement.
A return statement consists of the following:
• The return keyword
• The value or expression that the function should
return

A Python function may or may not return a value. If we want


our function to return some value to a function call, we use
the return statement.

The return statement also denotes that the function has ended.
Any code after return is not executed.
In the above example, we have created a function named find_square().
The function accepts a number and returns the square of the number.
None Value
The None keyword is used to define a null value,
or no value at all.
None is not the same as 0, False, or an empty
string.
None is a data type of its own (NoneType) and
only None can be None.

Example
Keyword Arguments and the print() Function

The keyword arguments are identified by the


keyword put before them in the function call, rather
than through their position.

Keyword arguments are often used for optional


parameters.

For example, the print() function has the optional


parameters
end - specify what should be printed at the end
sep - specify what should be printed between
arguments
Python Function Arguments

In the above example, we have created a function named add_numbers() with


arguments: num1 and num2.
Local and Global Scope
Parameters and variables that are assigned in a
called function are said to exist in that function’s
local scope.
Variables that are assigned outside all functions
are said to exist in the global scope.
A variable that exists in a local scope is called a
local variable, while a variable that exists in the
global scope is called a global variable.
A variable must be one or the other; it cannot be
both local and global
Local Variables Cannot Be Used in the Global Scope
Consider this program, which will cause an error when
you run it:

The error happens because the eggs variable exists only in


the local scope created when spam() is called .

Once the program execution returns from spam, that local


scope is destroyed, and there is no longer a variable named
eggs.
Local Scopes Cannot Use Variables in Other Local
Scopes
A new local scope is created whenever a function is
called, including when a function is called from
another function.
Consider this program:
When the program starts, the spam() function is called , and
a local scope is created.

The local variable eggs is set to 99. Then the bacon()


function is called, and a second local scope is created.

In this new local scope, the local variable ham is set to 101,
and a local variable eggs—which is different from the one in
spam()’s local scope—is also created and set to 0.

When bacon() returns, the local scope for that call is


destroyed, including its eggs variable. The program
execution continues in the spam() function to print the value
of eggs .

Since the local scope for the call to spam() still exists, the
only eggs variable is the spam() function’s eggs variable,
which was set to 99.
Four rules to tell whether a variable is in a local
scope or global scope:

• If a variable is being used in the global scope (that is,


outside of all functions), then it is always a global variable.

• If there is a global statement for that variable in a function,


it is a global variable.

• Otherwise, if the variable is used in an assignment


statement in the function, it is a local variable.

• But if the variable is not used in an assignment statement,


it is a global variable.
Exception Handling
• Right now, getting an error, or exception, in your
Python program means the entire program will crash.
• You don’t want this to happen in real-world programs.
• Instead, you want the program to detect errors,
handle them, and then continue to run.
• Errors can be handled with try and except statements.
• The code that could potentially have an error is put in
a try clause.
• The program execution moves to the start of a
following except clause if an error happens.
• For example
Exercise - 1
Write a program to create a function that takes two
arguments, name and age, and print their value.

Use the def keyword with the function name to


define a function.
Next, take two parameters
Print them using the print() function
Call function by passing name and age.
Exercise - 2
Define a function that accepts 2 values and return its sum,
subtraction and multiplication.

Hint
Input:
Enter value of a = 7
Enter value of b = 5

Expected output
Sum is = 12
Sub is = 2
Multiplication is = 35

You might also like