Python Notes
Python Notes
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
brightness_4
# Python program to
a=5
b = 5.0
c = 2 + 4j
Output:
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
# Creation of String
# Creating a String
print(String1)
# Creating a String
print(String1)
print(type(String1))
# Creating a String
print(String1)
print(type(String1))
String1 = '''Geeks
For
Life'''
print(String1)
Output:
I'm a Geek
<class 'str'>
String with the use of Triple Quotes:
<class 'str'>
Geeks
For
Life
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(String1)
print(String1[0])
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
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
# Creation of List
# Creating a List
List = []
print(List)
List = ['GeeksForGeeks']
print(List)
print(List[0])
print(List[2])
print(List)
Output:
[]
['GeeksForGeeks']
Geeks
Geeks
Multi-Dimensional List:
play_arrow
brightness_4
print(List[0])
print(List[2])
# negative indexing
print(List[-3])
Output:
Geeks
Geeks
Geeks
Geeks
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
# creation of Set
Tuple1 = ()
print (Tuple1)
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print(tuple(list1))
print(Tuple1)
# Creating a Tuple
Tuple1 = (0, 1, 2, 3)
print(Tuple3)
Output:
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
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
print(tuple1[0])
# negative indexing
print(tuple1[-1])
Output:
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
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
print(type(true))
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
# Creating a Set
set1 = set()
print(set1)
set1 = set("GeeksForGeeks")
print(set1)
print(set1)
print(set1)
Output:
set()
Set with the use of String:
{'Geeks', 'For'}
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
# Creating a set
print("\nInitial set")
print(set1)
# Accessing element using
# for loop
for i in set1:
# using in keyword
print("Geeks" in set1)
Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True
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
Dict = {}
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Empty 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
# Creating a Dictionary
print(Dict['name'])
# method
print(Dict.get(3))
Output:
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
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
# its block.
Flowchart:-
i = 10
if (i > 15):
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):
# condition is true
else:
# condition is false
Flow Chart:-
ADVERTISING
Output:
i is greater than 15
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):
if (condition2):
Flow chart:-
# python program to illustrate nested If statement
#!/usr/bin/python
i = 10
if (i == 10):
# First if statement
if (i < 15):
# Nested - if statement
# it is true
if (i < 12):
else:
Output:
i is smaller than 15
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:-
#!/usr/bin/python
i = 20
if (i == 10):
elif (i == 15):
elif (i == 20):
else:
Output:
i is 20
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:
i = 10
Output:
i is less than 15
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:
Example:
# Python program to illustrate short hand if-else
i = 10
Output:
True
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:
# 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:
for i in l:
print(i)
print("\nTuple Iteration")
for i in t:
print(i)
print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
Output:
List Iteration
geeks
for
geeks
Tuple Iteration
geeks
for
geeks
String Iteration
Dictionary Iteration
xyz 123
abc 345
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
Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
# or 's'
break
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
pass
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
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()
for i in range(len(l)):
print()
sum = 0
sum = sum + i
Output
0123456789
10 20 30 40
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.
# for-else loop
print(i)
print("No Break\n")
print(i)
break
print("No Break")
Output:
No Break
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:
# while loop
count = 0
count = count + 1
print("Hello Geek")
print()
a = [1, 2, 3, 4]
while a:
print(a.pop())
Output:
Hello Geek
Hello Geek
Hello Geek
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 (;).
count = 0
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.
play_arrow
brightness_4
i=0
a = 'geeksforgeeks'
i += 1
continue
i += 1
Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
# or 's'
i=0
a = 'geeksforgeeks'
i += 1
break
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
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.
# while-else loop
i=0
while i < 4:
i += 1
print(i)
print("No Break\n")
i=0
while i < 4:
i += 1
print(i)
break
print("No Break")
Output:
2
3
No Break
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
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
s = 'geeksforgeeks'
for letter in s:
print(letter)
# or 's'
break
print()
i=0
while True:
print(s[i])
# or 's'
break
i += 1
Output:
e
Out of for loop
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
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.
# Python program to
# demonstrate continue
# statement
# loop from 1 to 10
# If i is equals to 6,
# without printing
if i == 6:
continue
else:
# of i
Output:
1 2 3 4 5 7 8 9 10
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
Python3
def geekFunction:
pass
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
Functions in Python
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.
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
print "odd"
# Driver code
evenOdd(2)
evenOdd(3)
Output:
even
odd
def myFun(x):
x[0] = 20
myFun(lst);
print(lst)
Output:
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):
# to x.
myFun(lst);
print(lst)
Output:
Another example to demonstrate that reference link is broken if we assign a new value (inside the
function).
def myFun(x):
# to x.
x = 20
x = 10
myFun(x);
print(x)
Output:
10
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.
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# argument)
myFun(10)
Output:
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.
print(firstname, lastname)
# Keyword arguments
Output:
('Geeks', 'Practice')
('Geeks', 'Practice')
def myFun(*argv):
print (arg)
Output:
Hello
Welcome
to
GeeksforGeeks
def myFun(**kwargs):
# Driver code
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.
print(cube(7))
Output:
343
# A generator function
def simpleGeneratorFun():
yield 1
yield 2
yield 3
# x is a generator object
x = simpleGeneratorFun()