Unit-1 2
Unit-1 2
Unit-1 2
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets
for this purpose.
Python is consistently rated as one of the world's most popular programming languages.
Python is fairly easy to learn, so if you are starting to learn any programming language then
Python could be your great choice. Today various Schools, Colleges and Universities are
teaching Python as their primary programming language. There are many other good reasons
which makes Python as the top choice of any programmer:
Applications of Python
The latest release of Python is 3.x. As mentioned before, Python is one of the most widely
used language over the web. I'm going to list few of them here:
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than
shell scripting.
Python Variables
Python Variable is containers which store values. Python is not “statically typed”. We do not
need to declare variables before using them or declare their type. A variable is created the
moment we first assign a value to it. A Python variable is a name given to a memory location.
It is the basic unit of storage in a program.
Var = "Geeksforgeeks"
VAR= “A “
print(Var)
Output:
Geeksforgeeks
Notes:
The value stored in a variable can be changed during program execution.
A Python Variables is only a name given to a memory location, all the operations
done on the variable effects that memory location.
Output:
45
1456.8
John
Output:
100
Output:
Before declare: 100
After re-declare: 120.3
Also, Python allows assigning a single value to several variables simultaneously with “=”
operators.
For example:
a = b = c = 10
print(a)
print(b)
print(c)
Output:
10
10
10
Assigning different values to multiple variables
Python allows adding different values in a single line with “,”operators.
a, b, c = 1, 20.2, "GeeksforGeeks"
print(a)
print(b)
print(c)
Output:
1
20.2
GeeksforGeeks
a = 10
a = "GeeksforGeeks"
print(a)
Output:
GeeksforGeeks
a = 10
b = 20
print(a+b)
a = "Geeksfor"
b = "Geeks"
print(a+b)
Output
30
GeeksforGeeks
Can we use + for different types also?
No use for different types would produce an error.
Output :
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Local variables are the ones that are defined and declared inside a function. We can not call
this variable outside the function.
Output:
Welcome geeks
Global variables are the ones that are defined and declared outside a function, and we need
to use them inside a function.
Output:
I love Geeksforgeeks
Output:
Value of x inside a function : 20
Value of x outside a function : 20
Object References
Now if we assign the new value in Y, then the previous object refers to the garbage values.
y = "Computer
Variables can hold values, and every value has a data-type. Python is a dynamically typed
language; hence we do not need to define the type of the variable while declaring it. The
interpreter implicitly binds the value with its type.
a = 5
The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python provides us
the type() function, which returns the type of the variable passed.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can hold different types of values. For example, a person's name must be stored as
a string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them.
The data types defined in Python are given below.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
In this section of the tutorial, we will give a brief introduction of the above data-types. We
will discuss each one of them in detail later in this tutorial.
Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the
variable. Similarly, the isinstance() function is used to check an object belongs to a particular
class.
Python creates Number objects when a number is assigned to a variable. For example;
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python
has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y
denote the real and imaginary parts, respectively. The complex numbers like 2.14j,
2.0 + 2.3j, etc.
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions
and operators to perform operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.
Example - 1
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''”
print(s)
Output:
Example - 2
str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Python Lists are similar to arrays in C. However, the list can contain data of different types.
The items stored in the list are separated with a comma (,) and enclosed within square
brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+)
and repetition operator (*) works with the list in the same way as they were working with the
strings.
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
#Printing the list1
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
# List Concatenation using + operator
print (list1 + list1)
# List repetation using * operator
print (list1 * 3)
Output:
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.
1. tup = ("hi", "Python", 2)
2. # Checking type of tup
3. print (type(tup))
4. #Printing the tuple
5. print (tup)
6. # Tuple slicing
7. print (tup[1:])
8. print (tup[0:1])
9. # Tuple concatenation using + operator
10. print (tup + tup)
11. # Tuple repatation using * operator
12. print (tup * 3)
13. # Adding value to tup. It will throw an error.
14. tup[2] = "hi"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces
{}.
1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
2. # Printing dictionary
3. print (d)
4. # Accesing value using keys
5. print("1st name is "+d[1])
6. print("2nd name is "+ d[4])
7. print (d.keys())
8. print (d.values())
Output:
Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be
represented by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
Consider the following example.
1. # Python program to check the boolean type
2. print(type(True))
3. print(type(False))
4. print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify
after creation), and has unique elements. In set, the order of the elements is undefined; it may
return the changed sequence of the element. The set is created by using a built-in
function set(), or a sequence of elements is passed in the curly braces and separated by the
comma. It can contain various types of values. Consider the following example.
1. # Creating Empty set
2. set1 = set()
3. set2 = {'James', 2, 3,'Python'}
4. #Printing Set value
5. print(set2)
6. # Adding element to the set
7. set2.add(10)
8. print(set2)
9. #Removing element from the set
10. set2.remove(2)
11. print(set2)
Output:
Sets in Python
A Set is an unordered collection data type that is iterable, mutable, and has no duplicate
elements.
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set. This is based on a
data structure known as a hash table. Since sets are unordered, we cannot access items using
indexes as we do in lists.
Output:
set
Output:
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}
Python Frozen Sets
Frozen sets in Python are immutable objects that only support methods and operators that
produce a result without affecting the frozen set or sets to which they are applied. It can be
done with frozenset() method in Python.
While elements of a set can be modified at any time, elements of the frozen set remain the
same after creation.
If no parameters are passed, it returns an empty frozenset.
Output:
Normal Set
{'a', 'c', 'b'}
Frozen Set
{'e', 'g', 'f'}
Methods for Sets
Insertion in set is done through set.add() function, where an appropriate record value is
created to store in the hash table. Same as checking for an item, i.e., O(1) on average.
However, in worst case it can become O(n).
# A Python program to
# demonstrate adding elements
# in a set
# Creating a Set
people = {"Jay", "Idrish", "Archi"}
print("People:", end = " ")
print(people)
# This will add Daxit
# in the set
people.add("Daxit")
# Adding elements to the
# set using iterator
for i in range(1, 6):
people.add(i)
print("\nSet after adding element:", end = " ")
print(people)
Output:
People: {'Idrish', 'Archi', 'Jay'}
Two sets can be merged using union() function or | operator. Both Hash Table values are
accessed and traversed with merge operation perform on them to combine the elements, at the
same time duplicates are removed. The Time Complexity of this is O(len(s1) +
len(s2)) where s1 and s2 are two sets whose union needs to be done.
# Python Program to
# demonstrate union of
# two sets
people = {"Jay", "Idrish", "Archil"}
vampires = {"Karan", "Arjun"}
dracula = {"Deepanshu", "Raju"}
# Union using union()
# function
population = people.union(vampires)
print("Union using union() function")
print(population)
# Union using "|"
# operator
population = people|dracula
print("\nUnion using '|' operator")
print(population)
Output:
Union using union() function
{'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'}
This can be done through intersection() or & operator. Common Elements are selected. They
are similar to iteration over the Hash lists and combining the same values on both the Table.
Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union
needs to be done.
# Python program to
# demonstrate intersection
# of two sets
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
# Intersection using
# intersection() function
set3 = set1.intersection(set2)
print("Intersection using intersection() function")
print(set3)
# Intersection using
# "&" operator
set3 = set1 & set2
print("\nIntersection using '&' operator")
print(set3)
Output:
Intersection using intersection() function
{3, 4}
To find difference in between sets. Similar to find difference in linked list. This is done
through difference() or – operator. Time complexity of finding difference s1 – s2 is
O(len(s1))
# Python program to
# demonstrate difference
# of two sets
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
# Difference of two sets
# using difference() function
set3 = set1.difference(set2)
print(" Difference of two sets using difference() function")
print(set3)
# Difference of two sets
# using '-' operator
set3 = set1 - set2
print("\nDifference of two sets using '-' operator")
print(set3)
Output:
Difference of two sets using difference() function
{0, 1, 2}
Difference of two sets using '-' operator
{0, 1, 2}
# Python program to
# demonstrate clearing
# of set
set1 = {1,2,3,4,5,6}
print("Initial set")
print(set1)
# This method will remove
# all the elements of the set
set1.clear()
print("\nSet after using clear() function")
print(set1)
Output:
Initial set
{1, 2, 3, 4, 5, 6}
Operators Notes
s1 == s2 s1 is equivalent to s2
s1 != s2 s1 is not equivalent to s2
s1 <= s2 s1 is subset of s2
s1 >= s2 s1 is superset of s2
Output:
('Set1 = ', set([1, 2, 3, 4, 5]))
('Set2 = ', set([3, 4, 5, 6, 7]))
('Union of Set1 & Set2: Set3 = ', set([1, 2, 3, 4, 5, 6, 7]))
('Intersection of Set1 & Set2: Set4 = ', set([3, 4, 5]))
Python operators
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]
== If the values of two operands are equal, then the condition (a == b) is not true.
becomes true.
> If the value of left operand is greater than the value of right (a > b) is not true.
operand, then condition becomes true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the value (a >= b) is not true.
of right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of (a <= b) is true.
right operand, then condition becomes true.
+= Add AND It adds right operand to the left operand and assign c += a is
the result to left operand equivalent to c = c
+a
-= Subtract AND It subtracts right operand from the left operand and c -= a is equivalent
assign the result to left operand to c = c - a
*= Multiply AND It multiplies right operand with the left operand and c *= a is
assign the result to left operand equivalent to c = c
*a
/= Divide AND It divides left operand with the right operand and c /= a is equivalent
assign the result to left operand to c = c / a
%= Modulus AND It takes modulus using two operands and assign the c %= a is
result to left operand equivalent to c = c
%a
//= Floor Division It performs floor division on operators and assign c //= a is
value to the left operand equivalent to c =
c // a
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively.
Following table lists out the bitwise operators supported by Python language with an example
each in those, we use the above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
[ Show Example ]
& Binary AND Operator copies a bit to the result if it exists in both (a & b) (means 0000
operands 1100)
^ Binary XOR It copies the bit if it is set in one operand but not (a ^ b) = 49 (means
both. 0011 0001)
~ Binary Ones (~a ) = -61 (means
Complement 1100 0011 in 2's
It is unary and has the effect of 'flipping' bits. complement form due
to a signed binary
number.
<< Binary Left The left operands value is moved left by the number a << 2 = 240 (means
Shift of bits specified by the right operand. 1111 0000)
>> Binary The left operands value is moved right by the a >> 2 = 15 (means
Right Shift number of bits specified by the right operand. 0000 1111)
There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then
[ Show Example ]
and Logical If both the operands are true then condition becomes true. (a and b)
AND is true.
or Logical OR If any of the two operands are non-zero then condition becomes (a or b)
true. is true.
not Logical NOT Used to reverse the logical state of its operand. Not(a
and b) is
false.
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below −
[ Show Example ]
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
[ Show Example ]
is not Evaluates to false if the variables on either side of the x is not y, here is
operator point to the same object and true otherwise. not results in 1 if id(x)
is not equal to id(y).
The following table lists all operators from highest precedence to lowest.
[ Show Example ]
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >> <<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
Identity Operators
a=3
b=3
c=4
print a is b # prints True
print a is not b # prints False
print a is not c # prints True
x=1
y=x
z=y
print z is 1 # prints True
print z is x # prints True
str1 = "FreeCodeCamp"
str2 = "FreeCodeCamp"
a = [10,20,30]
b = [10,20,30]
Membership Operators
a = [1,2,3,4,5]
Unit 2:
Python If ... Else
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.
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33,
and so we print to screen that "b is greater than a".
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.
Example
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif
The elif keyword is Python's 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")
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
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")
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".
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("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
Example
a = 2
b = 330
print("A") if a > b else print("B")
You can also have multiple else statements on the same line:
Example
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
Example
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
Example
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not
The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:
Example
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.
Example
a = 33
b = 200
if b > a:
pass
break Statement
With the break statement we can stop the loop even if the while condition is true:
Example
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1. # Initiating the loop
2. for string in "Python Loops":
3. if string == 'n':
4. break
5. print('Current Letter: ', string)
continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
# Python program to show how to use continue loop control
# Initiating the loop
for string in "While Loops":
if string == "o" or string == "i" or string == "e":
continue
print('Current Letter:', string)
while loops
for loops
Example
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
With the else statement we can run a block of code once when the condition no longer is true:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
For loop:
Generally, a 'for' loop is used to repeat a code N number of times, where N is the number of
items in the sequence or collection. In Python, we can use for loop to iterate over a list,
a tuple, a dictionary, a set, or a string.
Quick Reference
for c in chars:
print(c)
1. Syntax
statement(s)
Here, the variable val represents a value from the sequence, for the current iteration. After
each iteration. the value points to the next available value in the sequence. Once all the values
have been iterated, the for loop terminates.
PlayNext
Unmute
Current Time 0:00
/
Duration 1:45
Loaded: 3.80%
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
2. Python for Loop Examples
Python program to iterate over a list of items using for loop. This program prints all the
names stored in the list.
for x in names:
print(x)
In Python, strings are iterable. They are a sequence of characters, so we can iterate over the
characters as follows:
name = "alex"
for x in name:
print(x)
print(key)
print(item)