0% found this document useful (0 votes)
73 views

Python Unit 1

Python is a free, open-source, and easy-to-code programming language. It has many features including being object-oriented, supporting GUI programming and debugging, being portable, being interpreted, having a large standard library, and requiring fewer lines of code than other languages to perform complex tasks. The document discusses Python's basic features and applications. It also covers standard types like None, files, sets, functions, modules, and classes. It describes internal types like code objects, frames, tracebacks, slices, and ellipsis. Finally, it discusses standard type operators for object value comparison and identity comparison as well as built-in functions like type().

Uploaded by

Varun Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Python Unit 1

Python is a free, open-source, and easy-to-code programming language. It has many features including being object-oriented, supporting GUI programming and debugging, being portable, being interpreted, having a large standard library, and requiring fewer lines of code than other languages to perform complex tasks. The document discusses Python's basic features and applications. It also covers standard types like None, files, sets, functions, modules, and classes. It describes internal types like code objects, frames, tracebacks, slices, and ellipsis. Finally, it discusses standard type operators for object value comparison and identity comparison as well as built-in functions like type().

Uploaded by

Varun Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Python

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]

Other Built-in Types


1. 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'>

2. Null object (None)


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.
Null – There is no null in Python, we can use None instead of using null values.
Example:
print(type(None))
Code language: Python (python)

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)

def subtract(x, y):


return (x-y)
Now, we are importing the calc that we created earlier to perform
add operation.
Program 2
import calc
print(calc.add(10, 2))

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

To create a class, use the keyword class:

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

Standard Type Operators

1. Object Value Comparison


Comparison operators are used to determine equality of two data values
between members of the same type. These comparison operators are supported for all
built-in types. Comparisons yield Boolean True or False values,
based on the validity of the comparison expression.
Example
>>> 2 == 2
True
>>> 2.46 <= 8.33
True
>>> 5+4j >= 2-3j
True

2. Object Identity Comparison


Python also supports the notion of directly comparing objects themselves. Objects can be
assigned to other variables (by reference). Because each variable points to the same
(shared) data object, any change effected through one variable will change the object and
hence be reflected through all references to the same object.
In order to understand this, you will have to think of variables as linking to objects now
and be less concerned with the values themselves. Let us take a look at three examples.

Example 1: foo1 and foo2 reference the same object


foo1 = foo2 = 4.3

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

str() and repr() (and ‘ ‘ Operator)


The str() STRing and repr() REPResentation or the single back or
reverse quote operator ( ` ` ) come in very handy if the need arises to either
re-create an object through evaluation or obtain a human-readable view of
the contents of objects, data values, object types, etc. To use these operations, a
Python object is provided as an argument and some type of string representation
of that object is returned. In the examples that follow, we take some random
Python types and convert them to their string representations.
Example
>>> str(4.53-2j)
'(4.53-2j)'
>>>
>>> str(1)
'1'
>>>
>>> str(2e10)
'20000000000.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

Categorizing the Standard Types

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.

int versus short versus long


Python’s plain integers are the universal “standard” integer type, obviating the need for three
different integer types, e.g., C’s int, short, and long. For the record, Python’s integers are
implemented as C longs

float versus double


C has both a single precision float type and double-precision double type. Python’s float type is
actually a C double. Python does not support a single-precision floating point type because its
benefits are outweighed by the overhead required to support two types of floating point types.

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

The __init__() Function


• The examples above are classes and objects in their simplest form,
and are not really useful in real life applications.
• To understand the meaning of classes we have to understand the built-
in __init__() function.
• All classes have a function called __init__(), which is always
executed when the class is being initiated.
• Use the __init__() function to assign values to object properties, or
other operations that are necessary to do when the object is being
created:
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)

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")

● Backslash ( \ ) continues a line


Ex 1:
Ex 2:

● Semicolon ( ; ) joins two statements on a line


Ex1: Print(“Hello”)
Print(“World”)
Ex2 : Print(“Hello”) ; Print(“World”)
● Colon ( : ) separates a header line from its suite
if condition:
stmt 1
stmt2
elif condition:
do something else
else:
do another thing
● Statements (code blocks) grouped as suites
ififcondition:
condition:
stmt
stmt11
stmt2
stmt2

● Suites delimited via indentation


site = 'google'
if site == 'google':
print('Logging on to google...')
else:
print('retype the URL.')
print('All set !')

Output:
Logging on to geeksforgeeks...
All set !

● Python files organized as modules

# A simple module, # importing module


#calc.py #calc.py
def add(x, y): import calc
return (x+y) print(calc.add(10, 2))
def subtract(x, y):
return (x-y)
Python Data Types / Standard data types
Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data. Since everything is an
object in Python programming, data types are actually classes and variables are instance (object)
of these classes.

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

String with the use of Double Quotes:


I'm a Geek
<class 'str'>

String with the use of Triple Quotes:


I'm a Geek and I live in a world of "Geeks"
<class 'str'>

Creating a multiline String:


Geeks
For
Life

Accessing elements of String


In Python, individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references to access characters from the back of the String, e.g.
-1 refers to the last character, -2 refers to the second last character and so on.
Example:
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

Output:
Initial String:
GeeksForGeeks

First character of String is:


G

Last character of String is:


s

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

Slice From the Start


By leaving out the start index, the range will start at the first character:
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])

Output : Hello

Slice To the End


By leaving out the end index, the range will go to the end:
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:
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

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position
of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

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

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a


specified value

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

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the


beginning

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

Most Values are True


• Almost any value is evaluated to True if it has some sort of content.
• Any string is True, except empty strings.
• Any number is True, except 0.
• Any list, tuple, set, and dictionary are True, except empty ones.
Example
The following will return True:

print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))

Output:
True
True
True

Some Values are False


In fact, there are not many values that evaluate to False, except empty values, such
as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates
to False.
Example
The following will return False:
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool([]))
print(bool({}))

Output:
False
False
False
False
False
False
False

Python Lists

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

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:
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)

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:

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

A list can contain different data types:


Example
A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]


print(list1)

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":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[:4])

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:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:])

Output:
['cherry', 'orange', 'kiwi', 'melon', 'mango']

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list:
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']

Check if Item Exists


To determine if a specified item is present in a list use the in keyword:
Example
Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

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:

thislist = ["apple", "banana", "cherry"]


thislist.insert(2, "watermelon")
print(thislist)

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:

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.
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']

Remove Specified Item


The remove() method removes the specified item.
Example
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

Output:
['apple', 'cherry']

Remove Specified Index


The pop() method removes the specified index.
Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)

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']

The del keyword also removes the specified index:


Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

Output:
['banana', 'cherry']

The del keyword can also delete the list completely.


Example
Delete the entire list:

thislist = ["apple", "banana", "cherry"]


del thislist

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

Clear the List


The clear() method empties the list.
The list still remains, but it has no content.
Example
Clear the list content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

Output:
[]

List Methods [Additional Information]


Python has a set of built-in methods that you can use on lists.
Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

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

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Python 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.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)

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:

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


print(len(thistuple))

Output:
3

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item, otherwise Python
will not recognize it as a tuple.
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))

o/p= <class 'tuple'>

#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")

Access Tuple Items


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

o/p --- 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 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:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[2:5])

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":

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[:4])
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" and to the end:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[-4:-1])

Check if Item Exists


To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
Add/remove Items
 Since tuples are immutable, they do not have a build-
in append() method
 Tuples are unchangeable, so you cannot remove items from i

Tuple Methods
Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in a tuple


index() Searches the tuple for a specified value and returns the position of where it
was found

Python Sets

myset = {"apple", "banana", "cherry"}

 Sets are used to store multiple items in a single variable.


 Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
 A set is a collection which is unordered, unchangeable*, and unindexed.
 Sets are written with curly brackets.

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.

Duplicates Not Allowed


Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)

o/p----- {'banana', 'cherry', 'apple'}


Get the Length of a Set
To determine how many items a set has, use the len() function.
Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))

o/p----- 3

A set can contain different data types:

Example
A set with strings, integers and boolean values:

set1 = {"abc", 34, True, 40, "male"}

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:

thisset = {"apple", "banana", "cherry"}


print("banana" in thisset)

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:

thisset = {"apple", "banana", "cherry"}


thisset.add("orange")
print(thisset)

o/p------ {'orange', 'apple', 'banana', 'cherry'}

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:

thisset = {"apple", "banana", "cherry"}


x = thisset.pop()
print(x)
print(thisset)
Note: Sets are unordered, so when using the pop() method, you do not know
which item that gets removed.

Example
The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}


thisset.clear()
print(thisset)

o/p------ set()

Example
The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}


del thisset
print(thisset)
o/p--- [Error]
Traceback (most recent call last):
File "demo_set_del.py", line 5, in <module>
print(thisset) #this will raise an error because the set no longer
exists
NameError: name 'thisset' is not defined

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

Join Two Sets


There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both sets, or
the update() method that inserts all the items from one set into another:
Example
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

o/p--- {'c', 2, 3, 'a', 'b', 1}

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

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

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

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in other, specified
set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others
Python Dictionaries

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

Dictionaries are used to store data values in key:value pairs.


A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
Dictionaries are written with curly brackets, and have keys and values:

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.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
Print the number of items in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))

Output: 3

Dictionary Items - Data Types


The values in dictionary items can be of any data type:
Example
String, int, boolean, and list data types:

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'])

Add a new item


Example
Add a new item to the original dictionary, and see that the keys list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change

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)])

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword:

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

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(10 + 5) -------- 15

Python divides the operators in the following groups:


 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:
Operator Name Example Try it

+ Addition x+y Try it »

- Subtraction x-y Try it »

* Multiplication x*y Try it »

/ Division x/y Try it »

% Modulus x%y Try it »

** Exponentiation x ** y Try it »

// Floor division x // y Try it »

Python Assignment Operators


Assignment operators are used to assign values to variables:
Operator Example Same As Try it

= x=5 x=5 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 »

&= 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 »

Python Comparison Operators


Comparison operators are used to compare two values:
Operator Name Example Try it

== Equal x == y Try it »

!= Not equal x != y Try it »

> Greater than x>y Try it »

< Less than x<y Try it »

>= Greater than or equal to x >= y Try it »

<= Less than or equal to x <= y Try it »


Python Logical Operators
Logical operators are used to combine conditional statements:
Operator Description Example Try it

and Returns True if both statements are true x < 5 and x < 10 Try it
»

or Returns True if one of the statements is true x < 5 or x < 4 Try it


»

not Reverse the result, returns False if the result not(x < 5 and x < 10) Try it
is true »

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:
Operator Description Example Try it

is Returns True if both variables are the same x is y Try it


object »

is not Returns True if both variables are not the x is not y Try it
same object »

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:
Operator Description Example Try
it

in Returns True if a sequence with the specified x in y Try it


value is present in the object »

not in Returns True if a sequence with the specified x not in y Try it


value is not present in the object »

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< 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:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

Output:
Emil Refsnes

Python Conditions and If statements


Python supports the usual logical conditions from mathematics:
 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if
statements" and loops.
An "if statement" is written by using the if keyword.
Example
a = 33
b = 200
if b > a:
print("b is greater than a")

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".

You can also have an else without the elif:

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:

if a > b: print("a is greater than b")

O/p----- a is greater than b

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it all on the
same line:

Example
One line if else statement:

a = 2
b = 330
print("A") if a > b else print("B")

Output:
B

Python Loops

Python has two primitive loop commands:


while loops
for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.

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.

The break Statement


With the break statement we can stop the loop even if the while condition is true:
Example
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3

The continue Statement


With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
6

The else Statement


With the else statement we can run a block of code once when the condition no longer is true:
Example
Print a message once the condition is false:

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

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string).
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

Output:
apple
banana
cherry

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:
Example
Loop through the letters in the word "banana":

for x in "banana":
print(x)

Output:
b
a
n
a
n
a

The break Statement


With the break statement we can stop the loop before it has looped through all the items:
Example
Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

Output:
apple
banana

The continue Statement


With the continue statement we can stop the current iteration of the loop, and continue with the
next:
Example
Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

Output:
apple
cherry

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.

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:

for x in range(2, 6):


print(x)

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):

for x in range(2, 30, 3):


print(x)

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

You might also like