Python Unit 1
Python Unit 1
Programming
Unit-I
Python Basics
Features in Python
1. Free and Open Source
it is open-source, this means that source code is also available to the public. So you can
download it, use it as well as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc.
3. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, object
4. GUI Programming Support
Graphical User interfaces can be made using a module
5. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify and correct the
majority of your program’s issues once you understand how to interpret Python’s error traces.
6. Python is a Portable language
Python language is also a portable language. For example, if we have Python code for windows
and if we want to run this code on other platforms such as Linux, Unix, and Mac then we do not
need to change it, we can run this code on any platform.
7. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time
8. Large Standard Library
Python has a large standard library that provides a rich set of modules and functions so you do
not have to write your own code for every single thing.
9. Allocating Memory Dynamically
In Python, the variable data type does not need to be specified. The memory is automatically
allocated to a variable at runtime when it is given a value.
10. Few lines of code
Python needs to use only a few lines of code to perform complex tasks. For example, to display
Hello World, you simply need to type one line - print(“Hello World”). Other languages like Java
or C would take up multiple lines to execute this.
Applications of python
Standard Types [Explained in later part of the notes]
Example:
a = "Hello World"
b = 33
print(type(a))
print(type(b))
Output:
<class 'str'>
<class 'int'>
Output:
<class 'NoneType'>
3. File
File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.
• The key function for working with files in Python is the open() function.
• The open() function takes two parameters; filename, and mode.
• There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
4. Set/Frozenset
Python frozenset() Method creates an immutable Set object from an iterable. It is a built-
in Python function. As it is a set object therefore we cannot have duplicate values in the
frozenset
• Frozen set is just an immutable version of a Python set object. While elements of a set
can be modified at any time, elements of the frozen set remain the same after
creation.
• Due to this, frozen sets can be used as keys in Dictionary or as elements of another
set. But like sets, it is not ordered (the elements can be set at any index).
• The syntax of frozenset() function is:
frozenset([iterable])
5. Function/Method
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
• In Python a function is defined using the def keyword
Example
def my_function():
print("Hello from a function")
my_function()
Output
Hello from a function
6. Module
• A Python module is a file containing Python definitions and statements.
• A module can define functions, classes, and variables.
• A module can also include runnable code.
• Grouping related code into a module makes the code easier to understand and use.
It also makes the code logically organized.
Example:
Program 1
# A simple module, calc.py
def add(x, y):
return (x+y)
Output:
12
7. Class
• Python is an object oriented programming language.
• Almost everything in Python is an object, with its properties and methods.
• A Class is like an object constructor, or a "blueprint" for creating objects.
Class
Object
Example:
class MyClass:
x = 5
#Creating object below
p1 = MyClass()
print(p1.x)
Output: 5
Internal Types
1. Code
• Code objects are executable pieces of Python source that are byte-compiled.
• Code objects themselves do not contain any information regarding their execution
environment, but they are at the heart of every user-defined function, all of which do
contain some execution context.
• Along with the code object, a function’s attributes also consist of the administrative
support that a function requires, including its name, documentation string, default
arguments, and global namespace
2. Frame
These are objects representing execution stack frames in Python. Frame
objects contain all the information the Python interpreter needs to know during a runtime
execution environment. Some of its attributes include a link to
the previous stack frame, the code object that is being executed,
dictionaries for the local and global namespaces, and the current instruction.
Each function call results in a new frame object, and for each frame object, a
C stack frame is created as well. One place where you can access a frame
object is in a traceback object
3. Traceback
When you make an error in Python, an exception is raised. If exceptions are not caught or
“handled,” the interpreter exits with some diagnostic information similar to the output
shown below:
Traceback (innermost last):
File "<stdin>", line N?, in ???
ErrorName: error reason
The traceback object is just a data item that holds the stack trace information for an
exception and is created when an exception occurs. If a handler is provided for an
exception, this handler is given access to the traceback object.
4. Slice
• Slice objects are created using the Python extended slice syntax. This extended syntax
allows for different types of indexing. These various types of indexing
5. Ellipsis
Ellipsis objects are used in extended slice notations as demonstrated above.
These objects are used to represent the actual ellipses in the slice syntax (. . .).
Like the Null object None, ellipsis objects also have a single name, Ellipsis,
and have a Boolean True value at all times.
6. Xrange
XRange objects are created by the BIF xrange(), a sibling of the range()
BIF, and used when memory is limited and when range() generates an
unusually large data set
Python deals with objects by passing references. foo2 then becomes a new and additional
reference for the original value. So both foo1 and foo2 now point to the same object. The
same figure above applies here as well.
This number simply indicates how many variables are “pointing to” any particular object.
Python provides the is and is not operators to test if a pair of variables do indeed refer to
the same object. Performing a check such as a is b
Standard Type Built-in Functions
type()
The type() function is used to get the type of an object. When a single argument is
passed to the type() function, it returns the type of the object.
Example:
a = "Hello World"
b = 33
print(type(a))
print(type(b))
Output:
<class 'str'>
<class 'int'>
cmp()
The cmp() Compares two objects, say, obj1 and obj2, and returns a
negative number (integer) if obj1 is less than obj2, a positive number if
obj1 is greater than obj2, and zero if obj1 is equal to obj2.
Example
>>> a, b = -4, 12
>>> cmp(a,b)
-1
>>> cmp(b,a)
1
>>> b = -4
>>> cmp(a,b)
0
isinstance()
The isinstance() function returns True if the specified object is of the specified type,
otherwise False.
If the type parameter is a tuple, this function will return True if the object is one of the
types in the tuple.
Syntax
isinstance(object, type)
Example
Check if the number 5 is an integer:
x = isinstance(5, int)
print(x)
Output: True
There are three different models we have come up with to help categorize the standard
types, with each model showing us the interrelationships between the types. These models help
us obtain a better understanding of how the types are related, as well as how they work.
1. Storage Model
The first way we can categorize the types is by how many objects can be stored in an
object of this type. Python’s types, as well as types from most other languages, can hold
either single or multiple values
2. Update Model
Another way of categorizing the standard types is by asking the question, “Once
created, can objects be changed, or can their values be updated?” When we introduced
Python types early on, we indicated that certain types allow their values to be updated
and others do not. Mutable objects are those whose values can be changed, and
immutable objects are those whose values cannot be changed.
3. Access Model
We use the access model. By this, we mean, how do we access the values of our
stored data? There are three categories under the access model: direct, sequence, and
mapping.
Unsupported Types
char
Python does not have a char type to hold either single character or 8-bit integers. Use strings of
length one for characters and integers for 8-bit numbers.
pointer
Since Python manages memory for you, there is no need to access pointer
addresses. The closest to an address that you can get in Python is by looking at an object’s
identity using the id(). Since you have no control
over this value, it’s a moot point. However, under Python’s covers, everything is a pointer.
Class/Object
• Python is an object oriented programming language.
• Almost everything in Python is an object, with its properties and methods.
• A Class is like an object constructor, or a "blueprint" for creating objects.
Class
Object
To create a class, use the keyword class:
Example:
class MyClass:
x = 5
#Creating object below
p1 = MyClass()
print(p1.x)
Output: 5
Output
John
36
Note: The __init__() function is called automatically every time the class is being
used to create a new object.
Statements and Syntax
Some rules and certain symbols are used with regard to statements in Python:
● Hash mark ( # ) indicates Python comments
● NEWLINE ( \n ) is the standard line separator (one statement per line)
Ex 1:
print ("Hello")
print ('!')
print ("World")
Ex 2: print ("Hello\n!\nWorld")
Output:
Logging on to geeksforgeeks...
All set !
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value can be
integer, floating number or even complex numbers. These values are defined as int, float and
complex class in Python.
Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.
Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific notation.
Complex Numbers – Complex number is represented by complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
Example
a = 5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
String
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of
one or more characters put in a single quote, double-quote or triple quote. In python there is no
character data type, a character is a string of length one. It is represented by str class.
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of
"Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
Output:
Initial String:
GeeksForGeeks
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
To check if a certain phrase or 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
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not
in.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
Output
True
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Output : llo
Output : Hello
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
Output : orl
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!
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Output:
Jello, 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
Additional information
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods return new values. They do not change the original
string.
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position
of where it was found
index() Searches the string for a specified value and returns the position
of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
rfind() Searches the string for a specified value and returns the last
position of where it was found
rindex() Searches the string for a specified value and returns the last
position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
Boolean Values
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean
answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Output:
True
False
False
Example
Print a message based on whether the condition is True or False:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Output:
b is not greater than a
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
Output:
True
True
True
Output:
False
False
False
False
False
False
False
Python Lists
Output:
['apple', 'banana', 'cherry']
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.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
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:
Output:
3
Output:
['abc', 34, True, 40, 'male']
Access Items
List items are indexed and you can access them by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Output:
banana
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.
When specifying a range, the return value will be a new list with the specified items.
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT including, "kiwi":
Output:
['apple', 'banana', 'cherry', 'orange']
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" to the end:
Output:
['cherry', 'orange', 'kiwi', 'melon', 'mango']
Output:
['orange', 'kiwi', 'melon']
Output:
Yes, 'apple' is in the fruits list
Insert Items
To insert a new list item, without replacing any of the existing values, we can use
the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert "watermelon" as the third item:
Output:
['apple', 'banana', 'watermelon', 'cherry']
Append Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
Output:
['apple', 'banana', 'cherry', 'orange']
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Output:
['apple', 'orange', 'banana', 'cherry']
Output:
['apple', 'cherry']
Output:
['apple', 'cherry']
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
Output:
['apple', 'banana']
Output:
['banana', 'cherry']
Output: [Error]
Traceback (most recent call last):
File "demo_list_del2.py", line 3, in <module>
print(thislist) #this will cause an error because you have
succsesfully deleted "thislist".
NameError: name 'thislist' is not defined
Output:
[]
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
Python Tuples
Output:
('apple', 'banana', 'cherry')
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order
will not change.
Unchangeable
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:
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
Output:
3
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
o/p= <class 'str'>
A tuple can contain different data types:
Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
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 tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
o/p: cherry
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
o/p:
('cherry', 'orange', 'kiwi')
Note: The search will start at index 2 (included) and end at index 5 (not
included).
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT included, "kiwi":
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
Python Sets
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
o/p----- 3
Example
A set with strings, integers and boolean values:
Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present in a
set, by using the in keyword.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
o/p------
apple
banana
cherry
Example
Check if "banana" is present in the set:
o/p------
True
Add Items
Once a set is created, you cannot change its items, but you can add new
items.
To add one item to a set use the add() method.
Example
Add an item to a set, using the add() method:
Add Sets
To add items from another set into the current set, use
the update() method.
Example
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
o/p---
{'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Example
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop() method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed.
The return value of the pop() method is the removed item.
Example
Remove the last item by using the pop() method:
Example
The clear() method empties the set:
o/p------ set()
Example
The del keyword will delete the set completely:
Loop Items
You can loop through the set items by using a for loop:
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
o/p--
banana
apple
cherry
Example
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
o/p----
{2, 'b', 'a', 'c', 3, 1}
Note: Both union() and update() will exclude any duplicate items.
Set Methods [Additional Information]
Python has a set of built-in methods that you can use on sets.
Method Description
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another,
specified set
intersection_update() Removes the items in this set that are not present in other, specified
set(s)
symmetric_difference_update() inserts the symmetric differences from this set and another
update() Update the set with the union of this set and others
Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Output:
Ford
Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When we say that dictionaries are ordered, it means that the items have a defined order, and that
order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by
using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Output: 3
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Output:
Mustang
There is also a method called get() that will give you the same result:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model")
print(x)
Output:
Mustang
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
Get a list of the keys:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)
Output:
dict_keys(['brand', 'model', 'year'])
Output:
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])
Get Values
The values() method will return a list of all the values in the dictionary.
Example
Get a list of the values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.values()
print(x)
Output:
dict_values(['Ford', 'Mustang', 1964])
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
Example
Get a list of the key:value pairs
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.items()
print(x)
Output:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Output:
Yes, 'model' is one of the keys in the thisdict dictionary
Change Values
You can change the value of a specific item by referring to its key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Update Dictionary
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Output:
{'brand': 'Ford', 'year': 1964}
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang'}
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Output:
{'brand': 'Ford', 'year': 1964}
Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer
exists.
Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Output:
{}
Example
Print all key names in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
Output:
brand
model
year
Example
Print all values in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
Output:
Ford
Mustang
1964
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Additional Information
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value
** Exponentiation x ** y Try it »
+= x += 3 x=x+3 Try it »
-= x -= 3 x=x-3 Try it »
*= x *= 3 x=x*3 Try it »
/= x /= 3 x=x/3 Try it »
%= x %= 3 x=x%3 Try it »
|= x |= 3 x=x|3 Try it »
^= x ^= 3 x=x^3 Try it »
== Equal x == y Try it »
and Returns True if both statements are true x < 5 and x < 10 Try it
»
not Reverse the result, returns False if the result not(x < 5 and x < 10) Try it
is true »
is not Returns True if both variables are not the x is not y Try it
same object »
<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall
shift off
>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let
shift the rightmost bits fall off
Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Example
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.
The following example has a function with one argument (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname )
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Output:
Emil
Tobias
Linus
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:
my_function("Emil", "Refsnes")
Output:
Emil Refsnes
Output:
b is greater than a
Elif
The elif keyword is pythons way of saying "if the previous conditions were
not true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Output:
a and b are equal
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so
we print to screen that "a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a is greater than b
In this example a is greater than b, so the first condition is not true, also the elif condition is not
true, so we go to the else condition and print to screen that "a is greater than b".
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Output:
b is not greater than a
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
One line if statement:
Example
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
Output:
B
Python Loops
Example
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
Output:
1
2
3
4
5
Note: remember to increment i, or else the loop will continue forever.
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
6
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output:
1
2
3
4
5
i is no longer less than 6
Example
Print each fruit in a fruit list:
Output:
apple
banana
cherry
for x in "banana":
print(x)
Output:
b
a
n
a
n
a
Output:
apple
banana
Output:
apple
cherry
Example
Using the range() function:
for x in range(6):
print(x)
Output:
0
1
2
3
4
5
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
Example
Using the start parameter:
Output:
2
3
4
5
The range() function defaults to increment the sequence by 1, however it is possible to specify
the increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
Output:
2
5
8
11
14
17
20
23
26
29
Important Questions
1) What are the features and applications of Python? [5M]
2) Explain Standard Data Types with example in python. [10M]
3) Write a note on [5M each]
i. Internal types
ii. Standard type operator
iii. Standard type built-in functions
iv. Categories of Standard type
v. Unsupported types
vi. Class and Object