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

Python Notes

The document discusses various Python data types including numeric, sequence, boolean, and set types. Numeric types cover integers, floats, and complex numbers. Sequence types include strings, lists, and tuples. Strings can be indexed and sliced. Lists and tuples allow storing multiple values but tuples are immutable. Boolean represents true and false values. Sets are unordered and cannot contain duplicate elements.

Uploaded by

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

Python Notes

The document discusses various Python data types including numeric, sequence, boolean, and set types. Numeric types cover integers, floats, and complex numbers. Sequence types include strings, lists, and tuples. Strings can be indexed and sliced. Lists and tuples allow storing multiple values but tuples are immutable. Boolean represents true and false values. Sets are unordered and cannot contain duplicate elements.

Uploaded by

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

GOVERNMENT ARTS AND SCIENCE COLLEGE FOR WOMEN

BARUGUR -635 104

DEPARTMENT OF COMPUTER SCIENCE

OPEN SOURCE COMPUTING

II M.Sc COMPUTER SCIENCE


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.

Following are the standard or built-in data type of Python:

Numeric

Sequence Type

Boolean

Set

Dictionary

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

Note – type() function is used to determine the type of data type.


play_arrow

brightness_4

# Python program to

# demonstrate numeric value

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

Sequence Type

In Python, sequence is the ordered collection of similar or different data types. Sequences allows to
store multiple values in an organized and efficient fashion. There are several sequence types in Python –
String

List

Tuple

1) 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 String

Strings in Python can be created using single quotes or double quotes or even triple quotes.

play_arrow

brightness_4

# Python Program for

# Creation of String

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

play_arrow

brightness_4
# Python Program to Access

# characters of String

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:

Last character of String is:

Note – To know more about strings, refer Python String.


2) List

Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type.

Creating List

Lists in Python can be created by just placing the sequence inside the square brackets[].

play_arrow

brightness_4

# Python program to demonstrate

# Creation of List

# Creating a List

List = []

print("Intial blank List: ")

print(List)

# Creating a List with

# the use of a String

List = ['GeeksForGeeks']

print("\nList with the use of String: ")

print(List)

# Creating a List with

# the use of multiple values


List = ["Geeks", "For", "Geeks"]

print("\nList containing multiple values: ")

print(List[0])

print(List[2])

# Creating a Multi-Dimensional List

# (By Nesting a list inside a List)

List = [['Geeks', 'For'], ['Geeks']]

print("\nMulti-Dimensional List: ")

print(List)

Output:

Intial blank List:

[]

List with the use of String:

['GeeksForGeeks']

List containing multiple values:

Geeks

Geeks

Multi-Dimensional List:

[['Geeks', 'For'], ['Geeks']]

Accessing elements of List


In order to access the list items refer to the index number. Use the index operator [ ] to access an item
in a list. In Python, negative sequence indexes represent positions from the end of the array. Instead of
having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing
means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.

play_arrow

brightness_4

# Python program to demonstrate

# accessing of element from list

# Creating a List with

# the use of multiple values

List = ["Geeks", "For", "Geeks"]

# accessing a element from the

# list using index number

print("Accessing element from the list")

print(List[0])

print(List[2])

# accessing a element using

# negative indexing

print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list

print(List[-3])

Output:

Accessing element from the list

Geeks

Geeks

Accessing element using negative indexing

Geeks

Geeks

Note – To know more about Lists, refer Python List.

3) Tuple

Just like list, tuple is also an ordered collection of Python objects. The only difference between type and
list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is represented
by tuple class.

Creating Tuple

In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the
use of parentheses for grouping of the data sequence. Tuples can contain any number of elements and
of any datatype (like strings, integers, list, etc.).

Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the
parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
play_arrow

brightness_4

# Python program to demonstrate

# creation of Set

# Creating an empty tuple

Tuple1 = ()

print("Initial empty Tuple: ")

print (Tuple1)

# Creating a Tuple with

# the use of Strings

Tuple1 = ('Geeks', 'For')

print("\nTuple with the use of String: ")

print(Tuple1)

# Creating a Tuple with

# the use of list

list1 = [1, 2, 4, 5, 6]

print("\nTuple using List: ")

print(tuple(list1))

# Creating a Tuple with the

# use of built-in function


Tuple1 = tuple('Geeks')

print("\nTuple with the use of function: ")

print(Tuple1)

# Creating a Tuple

# with nested tuples

Tuple1 = (0, 1, 2, 3)

Tuple2 = ('python', 'geek')

Tuple3 = (Tuple1, Tuple2)

print("\nTuple with nested tuples: ")

print(Tuple3)

Output:

Initial empty Tuple:

()

Tuple with the use of String:

('Geeks', 'For')

Tuple using List:

(1, 2, 4, 5, 6)

Tuple with the use of function:

('G', 'e', 'e', 'k', 's')

Tuple with nested tuples:


((0, 1, 2, 3), ('python', 'geek'))

Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.

Accessing elements of Tuple

In order to access the tuple items refer to the index number. Use the index operator [ ] to access an item
in a tuple. The index must be an integer. Nested tuples are accessed using nested indexing.

play_arrow

brightness_4

# Python program to

# demonstrate accessing tuple

tuple1 = tuple([1, 2, 3, 4, 5])

# Accessing element using indexing

print("Frist element of tuple")

print(tuple1[0])

# Accessing element from last

# negative indexing

print("\nLast element of tuple")

print(tuple1[-1])

print("\nThird last element of tuple")


print(tuple1[-3])

Output:

Frist element of tuple

Last element of tuple

Third last element of tuple

Note – To know more about tuples, refer Python Tuples.

Boolean

Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are
truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in
Boolean context as well and determined to be true or false. It is denoted by the class bool.

Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.

play_arrow

brightness_4

# Python program to

# demonstrate boolean type


print(type(True))

print(type(False))

print(type(true))

Output:

<class 'bool'>

<class 'bool'>

Traceback (most recent call last):

File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in

print(type(true))

NameError: name 'true' is not defined

Set

In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various elements.

Creating Sets

Sets can be created by using the built-in set() function with an iterable object or a sequence by placing
the sequence inside curly braces, separated by ‘comma’. Type of elements in a set need not be the
same, various mixed-up data type values can also be passed to the set.

play_arrow

brightness_4

# Python program to demonstrate

# Creation of Set in Python

# Creating a Set
set1 = set()

print("Intial blank Set: ")

print(set1)

# Creating a Set with

# the use of a String

set1 = set("GeeksForGeeks")

print("\nSet with the use of String: ")

print(set1)

# Creating a Set with

# the use of a List

set1 = set(["Geeks", "For", "Geeks"])

print("\nSet with the use of List: ")

print(set1)

# Creating a Set with

# a mixed type of values

# (Having numbers and strings)

set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])

print("\nSet with the use of Mixed Values")

print(set1)

Output:

Intial blank Set:

set()
Set with the use of String:

{'F', 'o', 'G', 's', 'r', 'k', 'e'}

Set with the use of List:

{'Geeks', 'For'}

Set with the use of Mixed Values

{1, 2, 4, 6, 'Geeks', 'For'}

Accessing elements of Sets

Set items cannot be accessed by referring to an index, since sets are unordered the items has no index.
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.

play_arrow

brightness_4

# Python program to demonstrate

# Accessing of elements in a set

# Creating a set

set1 = set(["Geeks", "For", "Geeks"])

print("\nInitial set")

print(set1)
# Accessing element using

# for loop

print("\nElements of set: ")

for i in set1:

print(i, end =" ")

# Checking the element

# using in keyword

print("Geeks" in set1)

Output:

Initial set:

{'Geeks', 'For'}

Elements of set:

Geeks For

True

Note – To know more about sets, refer Python Sets.

Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a map,
which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair.
Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is
separated by a colon :, whereas each key is separated by a ‘comma’.
Creating Dictionary

In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated, whereas
keys can’t be repeated and must be immutable. Dictionary can also be created by the built-in
function dict(). An empty dictionary can be created by just placing it to curly braces{}.

Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.

play_arrow

brightness_4

# Creating an empty Dictionary

Dict = {}

print("Empty Dictionary: ")

print(Dict)

# Creating a Dictionary

# with Integer Keys

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

print("\nDictionary with the use of Integer Keys: ")

print(Dict)

# Creating a Dictionary

# with Mixed keys

Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}

print("\nDictionary with the use of Mixed Keys: ")

print(Dict)
# Creating a Dictionary

# with dict() method

Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})

print("\nDictionary with the use of dict(): ")

print(Dict)

# Creating a Dictionary

# with each item as a Pair

Dict = dict([(1, 'Geeks'), (2, 'For')])

print("\nDictionary with each item as a pair: ")

print(Dict)

Output:

Empty Dictionary:

{}

Dictionary with the use of Integer Keys:

{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:

{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary with the use of dict():

{1: 'Geeks', 2: 'For', 3: 'Geeks'}


Dictionary with each item as a pair:

{1: 'Geeks', 2: 'For'}

Accessing elements of Dictionary

In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
There is also a method called get() that will also help in accessing the element from a dictionary.

play_arrow

brightness_4

# Python program to demonstrate

# accessing a element from a Dictionary

# Creating a Dictionary

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key

print("Accessing a element using key:")

print(Dict['name'])

# accessing a element using get()

# method

print("Accessing a element using get:")

print(Dict.get(3))

Output:

Accessing a element using key:


For

Accessing a element using get:

Geeks

Python if else

There comes situations in real life when we need to make some decisions and based on these decisions,
we decide what should we do next. Similar situations arises in programming also where we need to
make some decisions and based on these decisions we will execute the next block of code.

Decision making statements in programming languages decides the direction of flow of program
execution. Decision making statements available in python are:

if statement

if..else statements

nested if statements

if-elif ladder

Short Hand if statement

Short Hand if-else statement

if statement

if statement is the most simple decision making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a block of
statement is executed otherwise not.

Syntax:

if condition:

# Statements to execute if

# condition is true

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the
value is true then it will execute the block of statements below it otherwise not. We can
use condition with bracket ‘(‘ ‘)’ also.

As we know, python uses indentation to identify a block. So the block under an if statement will be
identified as shown in the below example:

if condition:
statement1

statement2

# Here if the condition is true, if block

# will consider only statement1 to be inside

# its block.

Flowchart:-

# python program to illustrate If statement

i = 10
if (i > 15):

print ("10 is less than 15")

print ("I am Not in if")

Output:

I am Not in if

As the condition present in the if statement is false. So, the block below the if statement is not executed.

if- else

The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to execute a block of code when
the condition is false.
Syntax:

if (condition):

# Executes this block if

# condition is true

else:

# Executes this block if

# condition is false
Flow Chart:-

ADVERTISING

Output:

i is greater than 15

i'm in else Block

i'm not in if and not in else Block

The block of code following the else statement is executed as the condition present in the if statement is
false after call the statement which is not in block(without spaces).

nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements means an if
statement inside another if statement. Yes, Python allows us to nest if statements within if statements.
i.e, we can place an if statement inside another if statement.

Syntax:

if (condition1):

# Executes when condition1 is true

if (condition2):

# Executes when condition2 is true

# if Block is end here

# if Block is end here

Flow chart:-
# python program to illustrate nested If statement

#!/usr/bin/python

i = 10

if (i == 10):

# First if statement

if (i < 15):

print ("i is smaller than 15")

# Nested - if statement

# Will only be executed if statement above

# it is true

if (i < 12):

print ("i is smaller than 12 too")

else:

print ("i is greater than 15")

Output:

i is smaller than 15

i is smaller than 12 too

if-elif-else ladder

Here, a user can decide among multiple options. The if statements are executed from the top down. As
soon as one of the conditions controlling the if is true, the statement associated with that if is executed,
and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will
be executed.

Syntax:-

if (condition):
statement

elif (condition):

statement

else:

statement
Flow Chart:-

Example:-

# Python program to illustrate if-elif-else ladder

#!/usr/bin/python

i = 20
if (i == 10):

print ("i is 10")

elif (i == 15):

print ("i is 15")

elif (i == 20):

print ("i is 20")

else:

print ("i is not present")

Output:

i is 20

Short Hand if statement

Whenever there is only a single statement to be executed inside the if block then shorthand if can be
used. The statement can be put on the same line as the if statement.
Syntax:

if condition: statement

Example:

# Python program to illustrate short hand if

i = 10

if i < 15: print("i is less than 15")

Output:

i is less than 15

Short Hand if-else statement

This can be used to write the if-else statements in a single line where there is only one statement to be
executed in both if and else block.

Syntax:

statement_when_True if condition else statement_when_False

Example:
# Python program to illustrate short hand if-else

i = 10

print(True) if i < 15 else print(False)

Output:

True

Python For Loops

Last Updated: 02-09-2020

For loops, in general, are used for sequential traversal. It falls under the category of definite iteration.
Definite iterations means the number of repetitions is specified explicitly in advance.
Note: In python, for loops only implements the collection-based iteration.

For in loops

For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python,
there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop
in other languages. Let us learn how to use for in loop for sequential traversals.
Syntax:

for var in iterable:

# statements

Here the iterable is a collection of objects like list, tuple. The indented statements inside the for loops
are executed once for each item in an iterable. The variable var takes the value of next item of the
iterable each time through the loop.
Example:

# Python program to illustrate

# Iterating over a list


print("List Iteration")

l = ["geeks", "for", "geeks"]

for i in l:

print(i)

# Iterating over a tuple (immutable)

print("\nTuple Iteration")

t = ("geeks", "for", "geeks")

for i in t:

print(i)

# Iterating over a String

print("\nString Iteration")

s = "Geeks"

for i in s :

print(i)

# Iterating over dictionary

print("\nDictionary Iteration")

d = dict()

d['xyz'] = 123

d['abc'] = 345

for i in d :

print("% s % d" %(i, d[i]))

Output:
List Iteration

geeks

for

geeks

Tuple Iteration

geeks

for

geeks

String Iteration

Dictionary Iteration

xyz 123

abc 345

Working of for loop :

ADVERTISING
Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope,
all automatic objects that were created in that scope are destroyed. Python supports the following
control statements.

Continue Statement: It returns the control to the beginning of the loop.

# Prints all letters except 'e' and 's'

for letter in 'geeksforgeeks':

if letter == 'e' or letter == 's':

continue

print('Current Letter :', letter)


var = 10

Output:

Current Letter : g

Current Letter : k

Current Letter : f

Current Letter : o

Current Letter : r

Current Letter : g

Current Letter : k

Break Statement: It brings control out of the loop.

for letter in 'geeksforgeeks':

# break the loop as soon it sees 'e'

# or 's'

if letter == 'e' or letter == 's':

break

print('Current Letter :', letter)

Output:

Current Letter : e
Pass Statement: We use pass statement to write empty loops. Pass is also used for empty control
statements, function and classes.

# An empty loop

for letter in 'geeksforgeeks':

pass

print('Last Letter :', letter)

Output:

Last Letter : s

range() function

range() is a built-in function of Python. It is used when a user needs to perform an action for a specific
number of times. range() in Python(3.x) is just a renamed version of a function called xrange() in
Python(2.x). The range() function is used to generate a sequence of numbers.
In simple terms, range() allows user to generate a series of numbers within a given range. Depending on
how many arguments user is passing to the function, user can decide where that series of numbers will
begin and end as well as how big the difference will be between one number and the next.range() takes
mainly three arguments.
start: integer starting from which the sequence of integers is to be returned

stop: integer before which the sequence of integers is to be returned.


The range of integers end at stop – 1.

step: integer value which determines the increment between each integer in the sequence

# Python Program to
# show range() basics

# printing a number

for i in range(10):

print(i, end=" ")

print()

# using range for iteration

l = [10, 20, 30, 40]

for i in range(len(l)):

print(l[i], end=" ")

print()

# performing sum of first 10 numbers

sum = 0

for i in range(1, 10):

sum = sum + i

print("Sum of first 10 numbers :", sum)

Output

0123456789

10 20 30 40

Sum of first 10 numbers : 45

for-else loop
In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted
with the if conditional statements. But Python also allows us to use the else condition with for loops.
Note: The else block just after for/while is executed only when the loop is NOT terminated by a break
statement.

# Python program to demonstrate

# for-else loop

for i in range(1, 4):

print(i)

else: # Executed because no break in for

print("No Break\n")

for i in range(1, 4):

print(i)

break

else: # Not executed as there is a break

print("No Break")

Output:

No Break

Python While Loops

Last Updated: 29-04-2020

In Python, While Loops is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the program is
executed. While loop falls under the category of indefinite iteration. Indefinite iteration means that the
number of times the loop is executed isn’t specified explicitly in advance.

Syntax:

while expression:

statement(s)

Statements represent all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses indentation as
its method of grouping statements. When a while loop is executed, expr is first evaluated in a Boolean
context and if it is true, the loop body is executed. Then the expr is checked again, if it is still true then
the body is executed again and this continues until the expression becomes false.

Example:

# Python program to illustrate

# while loop

count = 0

while (count < 3):

count = count + 1

print("Hello Geek")

print()

# checks if list still

# contains any element

a = [1, 2, 3, 4]

while a:

print(a.pop())

Output:
Hello Geek

Hello Geek

Hello Geek

Working of While Loop :

Single statement while block

Just like the if block, if the while block consists of a single statement the we can declare the entire loop
in a single line. If there are multiple statements in the block that makes up the loop body, they can be
separated by semicolons (;).

# Python program to illustrate

# Single statement while block

count = 0

while (count < 5): count += 1; print("Hello Geek")

Output:

Hello Geek

Hello Geek

Hello Geek

Hello Geek

Hello Geek
Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope,
all automatic objects that were created in that scope are destroyed. Python supports the following
control statements.

Continue Statement: It returns the control to the beginning of the loop.

play_arrow

brightness_4

# Prints all letters except 'e' and 's'

i=0

a = 'geeksforgeeks'

while i < len(a):

if a[i] == 'e' or a[i] == 's':

i += 1

continue

print('Current Letter :', a[i])

i += 1

Output:

Current Letter : g

Current Letter : k

Current Letter : f

Current Letter : o

Current Letter : r

Current Letter : g

Current Letter : k

Break Statement: It brings control out of the loop.


# break the loop as soon it sees 'e'

# or 's'

i=0

a = 'geeksforgeeks'

while i < len(a):

if a[i] == 'e' or a[i] == 's':

i += 1

break

print('Current Letter :', a[i])

i += 1

Output:

Current Letter : g

Pass Statement: We use pass statement to write empty loops. Pass is also used for empty control
statements, functions and classes.

# An empty loop

a = 'geeksforgeeks'

i=0

while i < len(a):

i += 1

pass

print('Value of i :', i)

Output:
Value of i : 13

while-else loop

As discussed above, while loop executes the block until a condition is satisfied. When the condition
becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break out of the loop,
or if an exception is raised, it won’t be executed.

Note: The else block just after for/while is executed only when the loop is NOT terminated by a break
statement.

# Python program to demonstrate

# while-else loop

i=0

while i < 4:

i += 1

print(i)

else: # Executed because no break in for

print("No Break\n")

i=0

while i < 4:

i += 1

print(i)

break

else: # Not executed as there is a break

print("No Break")

Output:

2
3

No Break

Python break statement

Last Updated: 22-11-2019

Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there
may arise a condition where you want to exit the loop completely, skip an iteration or ignore that
condition. These can be done by loop control statements. Loop control statements change execution
from its normal sequence. When execution leaves a scope, all automatic objects that were created in
that scope are destroyed. Python supports the following control statements.

Continue statement

Break statement

Pass statement

In this article, the main focus will be on break statement.

Break statement

Break statement in Python is used to bring the control out of the loop when some external condition is
triggered. Break statement is put inside the loop body (generally after if condition).
Syntax:

break

Example:

# Python program to

# demonstrate break statement

s = 'geeksforgeeks'

# Using for loop

for letter in s:
print(letter)

# break the loop as soon it sees 'e'

# or 's'

if letter == 'e' or letter == 's':

break

print("Out of for loop")

print()

i=0

# Using while loop

while True:

print(s[i])

# break the loop as soon it sees 'e'

# or 's'

if s[i] == 'e' or s[i] == 's':

break

i += 1

print("Out of while loop")

Output:

e
Out of for loop

Out of while loop

Python Continue Statement

Last Updated: 22-11-2019

Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there
may arise a condition where you want to exit the loop completely, skip an iteration or ignore that
condition. These can be done by loop control statements. Loop control statements change execution
from its normal sequence. When execution leaves a scope, all automatic objects that were created in
that scope are destroyed. Python supports the following control statements.

Continue statement

Break statement

Pass statement

In this article, the main focus will be on continue statement.

Continue statement

Continue is also a loop control statement just like the break statement. continue statement is opposite
to that of break statement, instead of terminating the loop, it forces to execute the next iteration of the
loop.
As the name suggests the continue statement forces the loop to continue or execute the next iteration.
When the continue statement is executed in the loop, the code inside the loop following the continue
statement will be skipped and the next iteration of the loop will begin.
Syntax:

continue

Example:
Consider the situation when you need to write a program which prints the number from 1 to 10 and but
not 6. It is specified that you have to do this using loop and only one loop is allowed to use.
Here comes the usage of continue statement. What we can do here is we can run a loop from 1 to 10
and every time we have to compare the value of iterator with 6. If it is equal to 6 we will use the
continue statement to continue to next iteration without printing anything otherwise we will print the
value.

Below is the implementation of the above idea:

# Python program to

# demonstrate continue

# statement
# loop from 1 to 10

for i in range(1, 11):

# If i is equals to 6,

# continue to next iteration

# without printing

if i == 6:

continue

else:

# otherwise print the value

# of i

print(i, end = " ")

Output:

1 2 3 4 5 7 8 9 10

Python pass Statement

Last Updated: 17-06-2020

The pass statement is a null statement. But the difference between pass and comment is that comment
is ignored by the interpreter whereas pass is not ignroed.

The pass statement is generally used as a placeholder i.e. when the user does not know what code to
write. So user simply places pass at that line. Sometimes, pass is used when the user doesn’t want any
code to execute. So user simply places pass there as empty code is not allowed in loops, function
definitions, class definitions, or in if statements. So using pass statement user avoids this error.

Syntax:

pass

Example 1: Pass statement can be used in empty functions

Python3
def geekFunction:

pass

Example 2: pass statement can also be used in empty class

class geekClass:

pass

Example 3: pass statement can be used in for loop when user doesn’t know what to code inside the loop

n = 10

for i in range(n):

# pass can be used as placeholder

# when code is to added later

pass

Functions in Python

Last Updated: 11-09-2018

A function is a set of statements that take inputs, do some specific computation and produces output.
The idea is to put some commonly or repeatedly done task together and make a function, so that
instead of writing the same code again and again for different inputs, we can call the function.
Python provides built-in functions like print(), etc. but we can also create your own functions. These
functions are called user-defined functions.

# A simple Python function to check

# whether x is even or odd

def evenOdd( x ):

if (x % 2 == 0):

print "even"
else:

print "odd"

# Driver code

evenOdd(2)

evenOdd(3)

Output:

even

odd

Pass by Reference or pass by value?


One important thing to note is, in Python every variable name is a reference. When we pass a variable to
a function, a new reference to the object is created. Parameter passing in Python is same as reference
passing in Java.

# Here x is a new reference to same list lst

def myFun(x):

x[0] = 20

# Driver Code (Note that lst is modified

# after function call.

lst = [10, 11, 12, 13, 14, 15]

myFun(lst);

print(lst)

Output:

[20, 11, 12, 13, 14, 15]

When we pass a reference and change the received reference to something else, the connection
between passed and received parameter is broken. For example, consider below program.
def myFun(x):

# After below line link of x with previous

# object gets broken. A new object is assigned

# to x.

x = [20, 30, 40]

# Driver Code (Note that lst is not modified

# after function call.

lst = [10, 11, 12, 13, 14, 15]

myFun(lst);

print(lst)

Output:

[10, 11, 12, 13, 14, 15]

Another example to demonstrate that reference link is broken if we assign a new value (inside the
function).

def myFun(x):

# After below line link of x with previous

# object gets broken. A new object is assigned

# to x.

x = 20

# Driver Code (Note that lst is not modified


# after function call.

x = 10

myFun(x);

print(x)

Output:

10

Exercise: Try to guess the output of following code.

def swap(x, y):

temp = x;

x = y;

y = temp;

# Driver code

x=2

y=3

swap(x, y)

print(x)

print(y)

Output:

Default arguments:
A default argument is a parameter that assumes a default value if a value is not provided in the function
call for that argument.The following example illustrates Default arguments.

# Python program to demonstrate

# default arguments
def myFun(x, y=50):

print("x: ", x)

print("y: ", y)

# Driver code (We call myFun() with only

# argument)

myFun(10)

Output:

('x: ', 10)

('y: ', 50)

Like C++ default arguments, any number of arguments in a function can have a default value. But once
we have a default argument, all the arguments to its right must also have default values.

Keyword arguments:
The idea is to allow caller to specify argument name with values so that caller does not need to
remember order of parameters.

# Python program to demonstrate Keyword Arguments

def student(firstname, lastname):

print(firstname, lastname)

# Keyword arguments

student(firstname ='Geeks', lastname ='Practice')

student(lastname ='Practice', firstname ='Geeks')

Output:

('Geeks', 'Practice')
('Geeks', 'Practice')

Variable length arguments:


We can have both normal and keyword variable number of arguments. Please see this for details.

# Python program to illustrate

# *args for variable number of arguments

def myFun(*argv):

for arg in argv:

print (arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output:

Hello

Welcome

to

GeeksforGeeks

# Python program to illustrate

# *kargs for variable number of keyword arguments

def myFun(**kwargs):

for key, value in kwargs.items():

print ("%s == %s" %(key, value))

# Driver code

myFun(first ='Geeks', mid ='for', last='Geeks')

Output:

last == Geeks
mid == for

first == Geeks

Anonymous functions: In Python, anonymous function means that a function is without a name. As we
already know that def keyword is used to define the normal functions and the lambda keyword is used
to create anonymous functions. Please see this for details.

# Python code to illustrate cube of a number

# using labmda function

cube = lambda x: x*x*x

print(cube(7))

Output:

343

here are two terms involved when we discuss generators.


1. Generator-Function : A generator-function is defined like a normal function, but
whenever it needs to generate a value, it does so with the yield keyword rather than return.
If the body of a def contains yield, the function automatically becomes a generator
function.
# A generator function that yields 1 for first time,
# 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3

# Driver code to check above generator function


for value in simpleGeneratorFun():
print(value)
Output :
1
2
3
2. Generator-Object : Generator functions return a generator object. Generator objects are
used either by calling the next method on the generator object or using the generator object
in a “for in” loop (as shown in the above program).
# A Python program to demonstrate use of
# generator object with next()

# A generator function
def simpleGeneratorFun():
yield 1
yield 2
yield 3

# x is a generator object
x = simpleGeneratorFun()

# Iterating over the generator object using next


print(x.next()) # In Python 3, __next__()
print(x.next())
print(x.next())
Output :
1
2
3
So a generator function returns an generator object that is iterable, i.e., can be used as an Iterators .

As another example, below is a generator for Fibonacci Numbers.


# A simple generator for Fibonacci Numbers
def fib(limit):

# Initialize first two Fibonacci Numbers


a, b = 0, 1

# One by one yield next Fibonacci Number


while a < limit:
yield a
a, b = b, a + b

# Create a generator object


x = fib(5)

# Iterating over the generator object using next


print(x.next()) # In Python 3, __next__()
print(x.next())
print(x.next())
print(x.next())
print(x.next())
# Iterating over the generator object using for
# in loop.
print("\nUsing for in loop")
for i in fib(5):
print(i)
Output :
0
1
1
2
3

Using for in loop


0
1
1
2
3
Applications : Suppose we to create a stream of Fibonacci numbers, adopting the generator
approach makes it trivial; we just have to call next(x) to get the next Fibonacci number without
bothering about where or when the stream of numbers ends.
A more practical type of stream processing is handling large data files such as log files. Generators
provide a space efficient method for such data processing as only parts of the file are handled at
one given point in time. We can also use Iterators for these purposes, but Generato

You might also like