Python Overview
Python Overview
Rohit Gupta
All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in
any form or by any means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of the publisher, except in the case of brief
quotations embodied in critical reviews and certain other noncommercial uses permitted by
copyright law. Although the author/co-author and publisher have made every effort to ensure
that the information in this book was correct at press time, the author/co-author and publisher do
not assume and hereby disclaim any liability to any party for any loss, damage, or disruption
caused by errors or omissions, whether such errors or omissions result from negligence,
accident, or any other cause. The resources in this book are provided for informational purposes
only and should not be used to replace the specialized training and professional judgment of a
health care or mental health care professional. Neither the author/co-author nor the publisher
can be held responsible for the use of the information provided within this book. Please always
consult a trained professional before making any decision regarding the treatment of yourself or
others.
https://www.c-sharpcorner.com/ebooks/ 2
Background and Expertise
Rohit Gupta is a Technical Trainer with a Master’s Degree in Informatics and a Bachelor’s
degree in Electronic Science, both from the University of Delhi. As a C# Corner MVP, author,
and speaker, Rohit is dedicated to advancing the fields of Artificial Intelligence, Machine
Learning, and Python. His vision is to create the world’s first human-like humanoid, driven by his
belief that the bond between machines and humans can make the world a better place.
— Rohit Gupta
https://www.c-sharpcorner.com/ebooks/ 3
Table of Contents:
Introduction................................................................................................................................. 5
Python Overview.......................................................................................................................... 8
Python Operators ........................................................................................................................16
Python Data Types ......................................................................................................................23
Python Flow of Control ................................................................................................................38
Python Class ...............................................................................................................................47
https://www.c-sharpcorner.com/ebooks/ 4
1
Introduction
Overview
https://www.c-sharpcorner.com/ebooks/ 5
Who is this Book for?
This is a book written for students, professionals, enthusiasts, and learners who wish to learn
Python Programming.
Pre-Requisites
• To get best out of this book, it is recommended to have prior knowledge of object-
oriented programming.
The current version of Python is 3.9. Since Python 2 will be getting obsolete soon, hence
we will be using Python 3 throughout the book.
You can check your version using
python3 --version
Ubuntu
• For Ubuntu 17.10+, python3 comes installed already
• For Ubuntu 16.10 and 17.03
sudo apt-get update && sudo apt-get install python3
https://www.c-sharpcorner.com/ebooks/ 6
MAC OS / MAC OS X
• Install Homebrew, type in the following command and hit enter
/usr/bin/ruby -e "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install)"
• Open Terminal and type in the following command and hit enter
brew install python3
https://www.c-sharpcorner.com/ebooks/ 7
2
Python Overview
Overview
https://www.c-sharpcorner.com/ebooks/ 8
Python is an interpreted, high-level, general-purpose programming language. Created by Guido
van Rossum and first released in 1991. He started python as a hobby project to keep him
occupied in the week around Christmas. Got its name from the name of British comedy troupe
Monty Python. It is used in:
1. Software Development
2. Web Development
3. System Scripting
4. Mathematics
Features of Python
Easy to use
Python has a very simple syntax, and hence it is very easy to implement anything using the
language
For example,
The following shows the code of printing number from 1 to 10.
C++
#include<iostream.h>
#include<conio.h>
void main()
{
int i,n,sum=0;
clrscr();
n=10;
for(i=1;i<=n;i++)
{
cout<<i;
getch();
}
}
Java
public class Use_For_Loop
{
public static void main(String[] args)
{
for(int i = 1; i <= 10; i++)
{
System.out.println(i);
}
}
}
Python
for i in range(1, 11):
print(i)
https://www.c-sharpcorner.com/ebooks/ 9
Interpreted Language
It means that the code is executed line by line i.e. if line 1 has some issue, then line 2 will not be
executed. Also, it is called “Interpreted Language” as an interpreter is used to execute the code
instead of a compiler
Cross-platform Language
It means that the same code segment can be executed on different operating systems, be it
Windows or Linux or Macintosh or Raspberry Pi, etc.
Expressive Language
It means that python supports a wide range of libraries, used for achieving a wide variety of
functionalities
For example,
Tkinter- GUI programming
Flask & Django – Web Development
Micro Python – Microcontroller programming
NumPy – Performing calculations of N-dimensional arrays
SciKit-Learn – Contains implementations of Machine Learning Algorithms
https://www.c-sharpcorner.com/ebooks/ 10
Python Character Set
The following are the character set recognized by python. It uses the traditional ASCII character
set.
• Letters: A-Z, a-z
• Digits: 0-9
• Special Symbols: Special Symbols available over Keyboard (some of the symbols like
rupee symbol may not be available)
• White Spaces: blank space, tab, carriage return, newline, form feed
• Other Characters: Unicode
Python Tokens
The smallest individual unit in a program is known as a token.
• Keywords: There are in total of 31 reserved keywords. Ex: and, finally, not, etc.
Following is the complete list of Python Keywords
https://www.c-sharpcorner.com/ebooks/ 11
• Punctuators: Used to implement the grammar and structure of a Syntax. Ex: &=, >>=,
<<=, etc. Following is the list of Python Punctuators
Comments: Comments are code segments which are not considered to be code by the python
interpreter. The main purpose of comments is to increase readability of the code. For instance,
comments can contain the explanation of the function preceded by it. Or it may contain the
usability documentation of the succeeding functionality
• Single line comment (#)
• multi-line comment (''' ''')
Function: Functions are a code segment which is used to implement the OOP’s concept of
Modularity, it has some name, and it can be reused. Ex:
KetArgFunc():
If true:
pass
https://www.c-sharpcorner.com/ebooks/ 12
Block & Indentation: Since in python we don’t use brackets, so block and indentation plays a
important role in defining the scope and lifetime, and also for marking the start and end of a
function or code block (a group of statements in block indentation at the same level creates a
block).
Ex: all the statements that are under the function KetArgFunc()
Python Variables
A variable can be considered as a container that holds value. Python is a type-infer language
i.e. one which can detect data types automatically or in other words it means you don’t need to
specify the data type of variable.
Note: although python supports unlimited variable length, following PEP-8, we keep the
maximum length to 79 characters
For example: The following code demonstrates how we can initialize variables
name = 'python' # String Data Type
sum =None # a variable without a value
a = 23 # integer
b = 6.2 # Float
sum = a+b
print(sum)
Multiple Assignments
The following code is a feature of Python
a =b =c =1 #single value to multiple variables
In the above code we can see that if we want to initialize more than 1 variable with the same
value, we can do with a single line of code
a,b = 1, 2 #multiple value to multiple variable
In the above code, we saw that if we want to initialize two different variables with two different
values, we can do it with a single line of code
a,b = b,a #value of a and b is swapped
In the above code, we saw that if we want to perform swapping, we can do it with a single line of
code.
Local Variable
A local variable is a variable which is either a variable declared within the function or is an
argument passed to a function. It is a type of variable who value can be accessed inside a block
only
https://www.c-sharpcorner.com/ebooks/ 13
def fun():
x=8
print(x)
fun()
Output
True
True
Global Variable
A global variable is a variable with global scope, meaning that it is visible (hence accessible)
throughout the program, unless shadowed.
x = 8
def fun():
print(x) #Calling variable 'x' inside fun()
fun()
print(x) #Calling variable 'x' outside fun()
Output
8
8
Exceptions
The other kind of errors in Python is exceptions. Even if a statement or expression is
syntactically correct, it may cause an error when an attempt is made to execute it.
Errors detected during execution are called exceptions
For Example:
>> 10 * (1/10)
https://www.c-sharpcorner.com/ebooks/ 14
The above code is syntactically okay, but when we execute it, it will result in ZeroDivisionError:
integer division or modulo by zero.
Standard Exceptions available in Python are:
SystenExit, OverflowError, FloatingPointError, ZeroDivisonError, EOFError, KeyboardInterrupt,
IndexError, IOError
Handling an Exception
If we see some suspicious code that may raise an exception, we can defend our program by
placing the code in the try block
Syntax
try:
you do your operation here
except Exception1:
if there is Exception1, then execute this block
except Exception2:
if there is Exception2, then execute this block
.........
else:
if there is no exception, then execute this block.
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
Output
Error: can't find file or read data
Add to numbers
n1 = input("Enter 1st number")
n2 = input("Enter second number")
sum = n1+n2
print("Sum:{}".format(sum))
https://www.c-sharpcorner.com/ebooks/ 15
3
Python Operators
Overview
https://www.c-sharpcorner.com/ebooks/ 16
The Precedence of Operators in Python can be found from the rule PEMDAS (Parenthesis,
Exponential, Multiply, Division, Addition, Subtraction). Operators with the same precedence are
evaluated from left to right.
We will now be discussing the various types of operators supported by Python.
Output
x+y=9
x-y=1
x * y = 20
x / y = 1.25
x // y = 1
x ** y = 625
Output
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
https://www.c-sharpcorner.com/ebooks/ 17
print('x or y is',x or y) #if either one is true
print('not x is',not x) #returns the complement
Output
x and y is False
x or y is True
not x is False
Output
a= 6 : 0b110 b= 3 : 0b11
result of AND is 2 : 0b10
result of OR is 7 : 0b111
result of EXOR is 5 : 0b101
result of COMPLEMENT is -7 : -0b111
result of LEFT SHIFT is 24 : 0b11000
result of RIGHT SHIFT is 1 : 0b1
https://www.c-sharpcorner.com/ebooks/ 18
print ("Line 2 - b is available in the given list")
Output
Line 1 - a is available in the given list
Line 2 - b is not available in the given list
Output
Line 1 a= 10 : 10914784 b= 10 : 10914784
Line 2 - a and b have same identity
https://www.c-sharpcorner.com/ebooks/ 19
Python Operator Overloading Examples
# Python Program illustrate how to overload an binary + operator
class A:
def __init__(self, a):
self.a = a
print(ob1 + ob2)
print(ob3 + ob4)
Output
3
CSharpConer
# Python Program to perform addition of two complex numbers using
binary + operator overloading.
class complex:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return self.a, self.b
Ob1 = complex(1, 0)
Ob2 = complex(1, 1)
Ob3 = Ob1 + Ob2
print(Ob3)
Output
(1, 1)
# Python program to overload a comparison operator
class A:
def __init__(self, a):
https://www.c-sharpcorner.com/ebooks/ 20
self.a = a
def __gt__(self, other):
if(self.a>other.a):
return True
else:
return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
print("ob1 is greater than ob2")
else:
print("ob2 is greater than ob1")
Output
ob2 is greater than ob1
# Python program to overload equality and less than operators
class A:
def __init__(self, a):
self.a = a
def __lt__(self, other):
if(self.a<other.a):
return "ob1 is less than ob2"
else:
return "ob2 is less than ob1"
def __eq__(self, other):
if(self.a == other.a):
return "Both are equal"
else:
return "Not equal"
ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2)
ob3 = A(4)
ob4 = A(4)
print(ob1 == ob2)
Output
ob1 is less than ob2
Not equal
https://www.c-sharpcorner.com/ebooks/ 21
Python Programming Examples
To find Simple Interest
r = int(input("Enter Rate of Interest (as Percentage)"))
t = int(input("Enter Time Period (in years)"))
si = (p*r*t)/100
print("Simple Interest {}".format(si))
https://www.c-sharpcorner.com/ebooks/ 22
4
Python Data Types
Overview
https://www.c-sharpcorner.com/ebooks/ 23
Python Data Types
According to Wikipedia, In computer science and computer programming, a data type or simply
type is an attribute of data which tells the compiler or interpreter how the programmer intends to
use the data
Given below is a list of Data Types supported by Python
Number: It is used to store numeric values. Python has 3 numeric types:
a. Integers
Ex: a = 10
b. Floating Point numbers
Ex: a = 10.0
c. Complex numbers
Ex: a = complex(10,5) # 10+5j
String: a string is a sequence of characters. In python, we can create a string using single ( ' ' )
or double quotes (" "). Both are same in python
str = 'computer science'
print('str- ', str) # print string
print('str[0]-', str[0]) # print 1st char
print('str[1:3]-', str[1:3]) # print string from position 1 to 3
print('str[3:]-', str[3:]) # print string starting from 3rd char
print('str*2-' , str*2) # print string two times
print('str + yes-', str+'yes') # concatenated string
Output
str- computer science
str[0]- c
str[1:3]- om
str[3:]- puter science
str*2- computer sciencecomputer science
str + yes- computer scienceyes
Boolean: It is used to store two possible values either true or false
str = "comp sc"
b = str.isupper()
print(b)
Output
False
List: Lists are collections of items, and each item has its index value. Denoted by []
list = [6,9]
list[0] = 55
print(list[0])
print(list[1])
https://www.c-sharpcorner.com/ebooks/ 24
Output
55
9
Tuple: A tuple is an immutable Python Object. Immutable python objects mean you cannot
modify the contents of a tuple once it is assigned. Denoted by ()
tup = (66,99)
print(tup[0])
print(tup[1])
tup[0] = 3 #error will be displayed
Output
66
99
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-514ab40eef4f> in <module>()
2 print(tup[0])
3 print(tup[1])
----> 4 tup[0] = 3 #error will be displayed
Output
{33, 11, 22}
Dictionary: It is an unordered collection of items, and each item consists of a key and a value.
dict = {'subject' : 'comp sc’, 'class' : '11'}
print(dict)
print( "Subject :", dict["subject"])
print("class :", dict.get('class'))
Output
{'subject': 'comp sc', 'class': '11'}
Subject : comp sc
class : 11
Python List
Lists are just like the arrays, declared in other languages. Lists need not be homogeneous
always which makes it a most powerful tool in Python. A single list may contain Datatypes like
Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even
after their creation.
Lists in Python are ordered and have a definite count. The elements in a list are indexed
according to a definite sequence and the indexing of a list is done with 0 being the first index.
https://www.c-sharpcorner.com/ebooks/ 25
Each element in the list has its definite place in the list, which allows duplicating of elements in
the list, with each element having its own distinct place and credibility.
# Python program to demonstrate Creation of List
# Creating a List
List = []
print("Initial blank List: ")
print(List)
Output
Initial blank List:
[]
List with the use of String:
['CSharpCorner']
List containing multiple values:
C
Corner
Multi-Dimensional List:
[['C', 'Sharp'], ['Corner']]
# Creating a List with the use of Numbers (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)
https://www.c-sharpcorner.com/ebooks/ 26
Output
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
List with the use of Mixed Values:
[1, 2, 'C', 4, 'Sharp', 6, 'Corner']
# Python program to demonstrate Addition of elements in a List
# Creating a List
List = []
print("Initial blank List: ")
print(List)
Output
Initial blank List:
[]
List after Addition of Three elements:
[1, 2, 4]
List after Addition of elements from 1-3:
[1, 2, 4, 1, 2, 3]
List after Addition of a Tuple:
[1, 2, 4, 1, 2, 3, (5, 6)]
List after Addition of a List:
https://www.c-sharpcorner.com/ebooks/ 27
[1, 2, 4, 1, 2, 3, (5, 6), ['C', 'Sharp']]
# Python program to demonstrate Addition of elements in a List
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
Output
Initial List:
[1, 2, 3, 4]
List after performing Insert Operation:
['CSharpCorner', 1, 2, 3, 12, 4]
# Python program to demonstrate Addition of elements in a List
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
Output
Initial List:
[1, 2, 3, 4]
List after performing Extend Operation:
[1, 2, 3, 4, 8, 'CSharp', 'Corner']
# Python program to demonstrate accessing of element from list
https://www.c-sharpcorner.com/ebooks/ 28
print("Accessing element from the list using negative indexing")
print(List[-1])
print(List[-2])
Output
Accessing an element from the list
CSharp
Corner
Accessing element from the list using negative indexing
Corner
CSharp
Acessing an element from a multi-dimensional list
Sharp
C
# Python program to demonstrate Removal of elements in a List
# Creating a List
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Intial List: ")
print(List)
Output
Intial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List after Removal of two elements:
https://www.c-sharpcorner.com/ebooks/ 29
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
List after Removing a range of elements:
[7, 8, 9, 10, 11, 12]
List = [1,2,3,4,5]
# Removing element at a specific location from the Set using the pop()
function
List.pop(2)
print("\nList after popping a specific element: ")
print(List)
Output
List after popping an element:
[1, 2, 3, 4]
List after popping a specific element:
[1, 2, 4]
# Creating a List
List = ['c','s', 'h', 'a', 'r', 'p', 'c', 'o','r','n','e','r']
print("Initial List: ")
print(List)
https://www.c-sharpcorner.com/ebooks/ 30
Sliced_List = List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)
Output
Initial List:
['c', 's', 'h', 'a', 'r', 'p', 'c', 'o', 'r', 'n', 'e', 'r']
Elements sliced till 6th element from last:
['c', 'o', 'r', 'n', 'e', 'r']
Elements sliced from index 1 to 6
['s', 'h', 'a', 'r', 'p']
Printing List in order:
['s', 'h', 'a', 'r', 'p', 'c', 'o', 'r', 'n', 'e', 'r']
Elements sliced till 6th element from last:
['c', 's', 'h', 'a', 'r', 'p']
Elements sliced from index -6 to -1
['c', 'o', 'r', 'n', 'e']
Printing List in reverse:
['r', 'e', 'n', 'r', 'o', 'c', 'p', 'r', 'a', 'h', 's', 'c']
Function Description
list.append() Add an item at end of a list
list.extend() Add multiple items at end of a list
list.insert() insert an item at a defined index
list.remove() remove an item from a list
del list[index] delete an item from a list
list.clear() empty all the list
list.pop() remove an item at a defined index
list.index() return index of the first matched item
list.sort() sort the items of a list in ascending or descending order
list.reverse() reverse the items of a list
len(list) return total length of the list
max(list) return item with maximum value in the list
min(list) return item with the minimum value in the list
list(seq) converts a tuple, string, set, dictionary into a list
https://www.c-sharpcorner.com/ebooks/ 31
Python Dictionary
According to Python Official Documentations, think of a dictionary as a set of keys: value pairs,
with the requirement that the keys are unique (within one dictionary). A pair of braces creates an
empty dictionary: {}. Placing a comma-separated list of keys: value pairs within the braces adds
initial keys: value pairs to the dictionary; this is also the way dictionaries are written on output.
A Dictionary in Python works similar to the Dictionary in the real world. Keys of a Dictionary must
be unique and of immutable data type such as Strings, Integers and tuples, but the key-values
can be repeated and be of any type.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Output
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Python', 2: 'language', 3: 'is'}
Dictionary with the use of Mixed Keys:
{'Name': 'an', 1: [1, 2, 3, 4]}
https://www.c-sharpcorner.com/ebooks/ 32
Dictionary with the use of dict():
{1: 'scripting', 2: 'language', 3: 'and'}
Dictionary with each item as a pair:
{1: 'not', 2: 'a'}
Nested Dictionary:
{1: 'programming', 2: 'language', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Python'}}
# Creating an empty Dictionary
Dict = {}
Output
Dictionary after adding 3 elements:
{0: 'Python', 2: 'Programming', 3: 1}
Dictionary after adding 3 elements:
{0: 'Python', 2: 'Programming', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Python', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Python', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Python'}}}
# Python program to demonstrate accesing an element from a Dictionary
# Creating a Dictionary
Dict = {1: 'Python', 'name': 'Programming', 3: 'Language'}
https://www.c-sharpcorner.com/ebooks/ 33
print("Accessing an element using key:")
print(Dict['name'])
print(Dict[1])
Output
Accessing an element using key:
Programming
Python
Accessing an element using get:
Language
# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'The',
'A' : {1 : 'World', 2 : 'of', 3 : 'Python'},
'B' : {1 : 'Scripting', 2 : 'Language'}}
print("Initial Dictionary: ")
print(Dict)
Output
Initial Dictionary:
https://www.c-sharpcorner.com/ebooks/ 34
{5: 'Welcome', 6: 'To', 7: 'The', 'A': {1: 'World', 2: 'of', 3: 'Python'}, 'B': {1: 'Scripting', 2:
'Language'}}
Deleting a specific key:
{5: 'Welcome', 7: 'The', 'A': {1: 'World', 2: 'of', 3: 'Python'}, 'B': {1: 'Scripting', 2: 'Language'}}
Deleting a key from Nested Dictionary:
{5: 'Welcome', 7: 'The', 'A': {1: 'World', 3: 'Python'}, 'B': {1: 'Scripting', 2: 'Language'}}
Popping specific element:
{7: 'The', 'A': {1: 'World', 3: 'Python'}, 'B': {1: 'Scripting', 2: 'Language'}}
Pops an arbitrary key-value pair:
{7: 'The', 'A': {1: 'World', 3: 'Python'}}
Deleting Entire Dictionary:
{}
Following is a list of all the functions provided by Python Dictionary
Function Description
dict.clear() removes all elements of dictionary dict
dict.copy() returns a shallow copy of dictionary dict
returns a list of dict's (key, value) tuple
dict.items()
pairs
dict.setdeafult(key, similar to get(), but will set dict[key] =
default=Nonre) default
adds dictionary dict2's key-values pairs
dict.update(dict2)
to dict
dict.keys() returns list of dictionary dict's keys
dict.values() returns list of dictionary dict's values
Python Tuples
According to Python Official Documentation, A tuple consists of a number of values separated
by commas. A python tuple is immutable. Python tuples are somewhat similar to python list as
all the concepts of python list can be implemented with python tuple, like slicing, indexing, etc.
# Tuple Creating
empty_tuple = ()
print (empty_tuple)
Output
()
('python', 'pythons')
('python', 'pythons')
# Code for concatenating 2 tuples
tuple1 = (0, 1, 2, 3)
https://www.c-sharpcorner.com/ebooks/ 35
tuple2 = ('python', 'python')
print("Concated Tuple: ")
print(tuple1 + tuple2)
Output
Concated Tuple:
(0, 1, 2, 3, 'python', 'python')
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'python')
tuple3 = (tuple1, tuple2)
print("Nested Tuple:")
print(tuple3)
Output
Nested Tuple:
((0, 1, 2, 3), ('python', 'python'))
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print("Tuple created using repetition")
print(tuple3)
Output
Tuple created using repetition
('python', 'python', 'python')
# code to test slicing
tuple1 = (0 ,1, 2, 3)
print("Python Tuple Slicing")
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])
Output
Python Tuple Slicing
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
# Code for printing the length of a tuple
tuple2 = ('python', 'python')
print("Length of Tuple")
print(len(tuple2))
Output
Length of Tuple
2
https://www.c-sharpcorner.com/ebooks/ 36
#Python List to Python Tuple
list1 = [0, 1, 2]
print("list to tuple")
print(tuple(list1))
print(tuple('python')) # string 'python'
Output
list to tuple
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Following is a list of all the functions provided by Python Tuple
Function Description
tuple(seq) converts a list into tuple
min(tuple) returns item from the tuple with minimum value
max(tuple) returns item from the tuple with maximum value
len(tuple) gives the total length of the tuple
cmp(tuple1,tuple2) compares elements of both tuples
https://www.c-sharpcorner.com/ebooks/ 37
5
Python Flow of Control
Overview
https://www.c-sharpcorner.com/ebooks/ 38
Python Control Statements
Control statements are used to control the flow of execution depending upon the specified
condition/logic.
If- Statement
An if statement is a programming conditional statement that, if proved true, performs a function
or displays information
noofbooks = 2
if (noofbooks == 2) :
print("You have")
print("two books")
print("outside of if statement")
Output
You have
two books
outside of if statement
In the above code, we are checking if noofbooks is equal to 2, then execute the given code.
if-else statement
the if-else statement executes some code if the test expression is true (non-zero) and some
other code if the test expression is false
https://www.c-sharpcorner.com/ebooks/ 39
a=10
if a<100:
print('less than 100')
else:
print('more than equal 100')
Output
less than 100
In the above code, we are checking if a is less than 100, else will print "more than equal 100'
Output
enter a number:-45.0
Negative number
In the above code, we are first checking if num is greater than or equal to 0 and then if it is zero
if both the conditions are met, "zero" is printed, otherwise "Negative number"
https://www.c-sharpcorner.com/ebooks/ 40
While Loop
It is used to execute a block of a statement if a given condition is true. And when the condition
becomes false, the control will come out of the loop. The condition is checked every time at the
beginning of the loop
x=1
while x<=4 :
print(x)
x = x+1
Output
1
2
3
4
In the above code, we are printing all the values from 1 to 4
For Loop
It is used to iterate over items of any sequence, such as a list or a string.
Output
3
4
In the above code, we are printing numbers from 3 to 5.
https://www.c-sharpcorner.com/ebooks/ 41
for i in range (1,3):
for j in range(1,11):
k=i*j
print(k, end = ' ')
print()
Output
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
In the above code, we are running our loop firstly from 1 to 3 and then for each iteration running
for another 10 times.
Break
It is used to terminate the loop
https://www.c-sharpcorner.com/ebooks/ 42
for val in "string":
if val == "i":
break
print(val)
In the above code, we break the loop as soon as "i" is encountered, hence printing "str"
continue
It is used to skip all the remaining statements in the loop and move controls back to the top of
the loop.
Output
n
t
The End
In the above chapter, we will be printing "nt", because for "i" it will skip.
pass
This statement does nothing. It can be used when a statement is required syntactically but the
program requires no action.
for i in "initial":
if(i == "i"):
pass
else:
print(i)
https://www.c-sharpcorner.com/ebooks/ 43
Output
n
t
a
l
Continue forces the loop to start the next iteration while pass means "there is no code to
execute here" and will continue through the remainder of the loop body.
print(fact)
https://www.c-sharpcorner.com/ebooks/ 44
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
https://www.c-sharpcorner.com/ebooks/ 45
#function to print reverse array
def a_rev():
a1 = a_inp()
print("Reversed Array:")
for i in range(len(a1), 0, -1):
print(a1[i-1])
while True:
print("----Program to Demonstarte Python Arrays----")
print("1. Sum of elements an Array")
print("2. Largest Element of an Array")
print("3. Rotating an Array")
print("4. Reverse an Array")
if ch == 1:
a_sum()
elif ch == 2:
a_large()
elif ch == 3:
a_rot()
elif ch == 4:
a_rev()
else:
print("Enter a valid choice")
https://www.c-sharpcorner.com/ebooks/ 46
6
Python Class
Overview
https://www.c-sharpcorner.com/ebooks/ 47
According to Wikipedia, A class is a code template for creating objects. Objects have member
variables and have behavior associated with them. In python, a class is created by the
keyword class. An object is created using the constructor of the class. This object will then be
called the instance of a class. In Python, we create instances in the following manner.
Declaring a Class
Given below is the syntax for declaring a class:
class name:
# statements
Using a Class
A python class can be implemented in the following ways:
We can create a class and then invoke it by creating an object
#Class Point created
class Point:
x = 0 #class member
y = 0 #class member
# main
p1 = Point() #Class Point object
p1.x = 2 #Initialization Class member x value
p1.y = -5 #Initialization Class member x value
print(p1.x, p1.y)
Output
2 -5
We can import a previously defined class and implement it as we did in the above code
#Importing Point Class
from Point import *
# main
p1 = Point() #Class Point object
p1.x = 7 #Initialization Class member x value
p1.y = -3 #Initialization Class member x value
p1.name = "Tyler Durden" # Python objects are dynamic (can add fields
any time!)
Output
7 -3 Tyler Durden
https://www.c-sharpcorner.com/ebooks/ 48
Self-keyword
According to Python Official Documentation, the first argument of a method is called self. This is
nothing more than a convention: the name self has absolutely no special meaning to Python.
‘self’ represents the instance of the class. By using the “self” keyword we can access the
attributes and functions of the class in python. It binds the attributes with the given arguments.
Let us dive deeper into this and get an idea as how “self” works
class Point(object):
def __init__(self,x = 0,y = 0):
self.x = x
self.y = y
In the above, code self helps us to fetch and initialize the values of the class members.
p = Point()
In the above code, when we create an object, we are actually calling the __init__ function i.e.
the python class constructor.
Since we are not passing any parameter to the __init__(), so self will get replaced with the
reference of object ‘p’.
p1 = Point(p)
In the above code, we are passing ‘p’ as the parameter, so self, x and y in the __init__ will get
replaced by reference of p1, reference of p and p.y respectively.
Now let us look at an example and try to understand how to implement __init__ function.
class Point:
def __init__(self, x, y):
self.x = y
self.y = y
In the above code, we are passing the class instance that is required to initiate the class
working, and the value of self.x and self.y as x and y respectively.
Object Functions
Given below is the syntax for declaring the object functions.
https://www.c-sharpcorner.com/ebooks/ 49
def name (self, parameter, ......, parameter):
statements
In the above code, self is very important, as, without the presence of self, python will not allow
us to use any of the class member functions. It is similar to "this" used in Java. With only one
difference that in java using "this" is not compulsory
def set_location(self, x, y):
self.x = x
self.y = y
def distance_from_origin(self):
return sqrt(self.x * self.x + self.y * self.y)
Calling Functions
A client can call the functions of an object in two ways
object.function( parameter)
Class.function( object, parameters)
p = Point(3, -4)
p.distance (1, 5) #using object name
Point.distance (p, 1, 5) #using class name
Given below is a code to demonstrate all of them things that we learned till now
from math import *
class Point:
x=0
y=0
def distance_from_origin(self):
return sqrt(self.x * self.x + self.y * self.y)
https://www.c-sharpcorner.com/ebooks/ 50
p = Point()
p.set_location(3, -4)
print("Initial")
print(p.x, p.y)
dist = p.distance_from_origin()
print("Distance from Origin")
print(dist)
p1 = Point()
p1.set_location(-3, 4)
dist = p.distance(p1)
print("Distance from point (-3, 4)")
print(dist)
Output
Initial
3 -4
Distance from Origin
5.0
Distance from point (-3, 4)
10.0
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_from_origin(self):
return sqrt(self.x * self.x + self.y * self.y)
https://www.c-sharpcorner.com/ebooks/ 51
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
p = Point(3, -4)
print(p.x, p.y)
dis = p.distance(p)
print(dis)
Output
3 -4
0.0
https://www.c-sharpcorner.com/ebooks/ 52
OUR MISSION
Free Education is Our Basic Need! Our mission is to empower millions of developers worldwide by
providing the latest unbiased news, advice, and tools for learning, sharing, and career growth. We’re
passionate about nurturing the next young generation and help them not only to become great
programmers, but also exceptional human beings.
ABOUT US
CSharp Inc, headquartered in Philadelphia, PA, is an online global community of software
developers. C# Corner served 29.4 million visitors in year 2022. We publish the latest news and articles
on cutting-edge software development topics. Developers share their knowledge and connect via
content, forums, and chapters. Thousands of members benefit from our monthly events, webinars,
and conferences. All conferences are managed under Global Tech Conferences, a CSharp
Inc sister company. We also provide tools for career growth such as career advice, resume writing,
training, certifications, books and white-papers, and videos. We also connect developers with their poten-
tial employers via our Job board. Visit C# Corner
MORE BOOKS