Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Python Overview

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

Python Overview

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

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.

Author – Rohit Gupta


Publisher – C# Corner
Editorial Team – Deepak Tewatia, Baibhav Kumar
Publishing Team – Praveen Kumar
Promotional & Media – Rohit Tomar

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

In this chapter, we explore the fundamentals of classes and objects in


Python. You will discover who can benefit from this book, the
prerequisites for optimal understanding, and a comprehensive guide to
installing Python 3 across different operating systems. By the end of
this chapter, you will be equipped with the foundational knowledge and
tools needed to embark on your Python programming journey.

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

What is in this Book?


In this book, we will be studying python and how to write programs using python.
In this book, we will discuss Python, what are the components of Python and how to write a
program in Python.
After completing the book, you should be able to write programs in Python

Steps to Install Python 3


Windows
• Python latest version can be download from https://www.python.org/downloads/.
• At the time of writing this, the latest version was 3.9.
• Run the installer file with the Administrator.
• Make sure to tick the following
• Add Python 3.x to PATH
• Adding python to Path will make python available to you over the whole system
• Click on Install Now
• Wait till the process gets over.

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

• For Ubuntu 14.04 and 16.04


sudo add-apt-repository ppa:deadsnakes/ppa
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

In this chapter, we explore Python's history, features, and uses in


software and web development. We cover its simplicity, cross-
platform capabilities, and key libraries. The chapter also introduces
Python's character set, tokens, variables, and basic syntax, along
with error handling and exceptions. This provides a solid foundation
for effective Python programming.

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

Free & Open Source


It is said to be “free” as we don’t have to pay penny to use python. It is said to be “open source”
as there is a community which provide helps free of cost.

Companies using Python


The following is the list of world’s top companies using Python to improve their product quality.
The following list also list the products in which the companies are using Python.
• Google: Google spider and search engine are written in Python
• NASA: NASA uses Python in its Integrated Planning System as the standard scripting
language. Nasa website is written in python (Django framework)
• NOKIA: NOKIA is using Python to provide high level programming environment for their
S60(Symbian)
• IBM: IBM uses Python to create the business practice logic for factory tool control
applications
• Amazon: Amazon uses Python because of its popular, scalable & appropriate for dealing
with Big Data that's the big plus for the kind of solutions Amazon strived to create.
• Facebook: Facebook decided to use Python as the core language for the backend of
their applications connected with image processing.
• Walt Disney Feature Animation: It uses Python as a scripting language for animation.
All the magic that happens in Disneyland has a bit of Python behind it.
• Dropbox: Many of our choices to store our data are going online. We create a
document; we save it & we share it. It is the ideal way to preserve your documents
online. This file hosting has been created by using Python.
• Reddit: It is a place where you can find a lot of information & entertainment across
thousands of categories. Popularly called internet’s front page has been developed by
using Python.
• Quora: Quora is a portal where you get your answers. Quora’s language programming
has been developed using Python’s framework.

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

• Identifiers: A python identifier is a name used to identify a variable, function, class,


module or other objects. Ex: MyBook, myBook, mybook, etc.
• Literals: Literals in Python can be defined as numbers, text, or other data that represent
values to be stored in variables. Ex: age = 22, escape sequence, etc.
• Operators: It can be defined as symbols that are used to perform operations on
operands. Ex: arithmetic operators, etc.

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

Rules to define Python Identifiers


An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores, and digits (0 to 9).
• Python does not allow special characters
• An identifier must not be a keyword of Python.
• Python is a case sensitive programming language.
• Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.
• Starting an identifier with a single leading underscore indicates that the identifier is
private.
• Starting an identifier with two leading underscores indicates a strongly private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.

Barebone of a Python Program


Expression: Expression means a code segment which results in a mathematical result. Ex:
(20=4)/4
Statements: Statements are code segments which instructs that we are doing something. Ex:
a=20
print("Calling in proper sequence")

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

Ex: #this is a single-line comment


''' this is multiple '''

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.

Variable Scope and Lifetime


Scope refers to the visibility of variables. In other words, which parts of your program can see or
use it.
The lifetime of a variable or object is the time period in which the variable/object has valid
memory. Lifetime is also called "allocation function" or "storage duration."

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

print(x) #error will be shown

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

Python Errors & Exception


Errors
A Syntax error is an error in the syntax of a sequence of characters or tokens that are intended
to be written in a particular programming language.
For Example:
while True print 'Hello world'

In the above code, it is an Invalid Syntax error. It should be as


while True:
print 'Hello world'

Standard Errors available in Python are:


IndentationError, SystemExit, ValueError, TypeError, RuntimeError

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

Python Programming Example


Take input from user
n = input("Enter any number")
print(n)

Add to numbers
n1 = input("Enter 1st number")
n2 = input("Enter second number")
sum = n1+n2
print("Sum:{}".format(sum))

To find the ASCII value of the input


ch = input("Enter a character")

print("The ASCII value of {}".format(ch),"is {}".format(ord(ch)))

https://www.c-sharpcorner.com/ebooks/ 15
3
Python Operators

Overview

In this chapter, we explore Python's operator precedence and various


types of operators, including arithmetic, comparison, logical, bitwise,
membership, and identity operators. We also cover operator overloading
with examples and provide practical coding exercises, such as
calculating interest and the area of a circle, to reinforce these concepts.

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.

Python Arithmetic Operator


These operators are used for mathematical operations.
x = 5
y = 4
print('x + y =',x+y) #Addition
print('x - y =',x-y) #Subtraction
print('x * y =',x*y) #Multiplication
print('x / y =',x/y) #Division
print('x // y =',x//y) #Floor Division
print('x ** y =',x**y) #Exponent

Output
x+y=9
x-y=1
x * y = 20
x / y = 1.25
x // y = 1
x ** y = 625

Python Comparison Operators


These operators are used to compare values.
x = 101
y = 121
print('x > y is',x>y) #Greater than
print('x < y is',x<y) #Less than
print('x == y is',x==y) #Equal to
print('x != y is',x!=y) #Not Equal to
print('x >= y is',x>=y) #Greater than equal to
print('x <= y is',x<=y) #Less than equal to

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

Python Logical Operators


These operators are used to perform logical operations.
x = True
y = False
print('x and y is',x and y) #if both are 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

Python Bitwise Operators


Used to manipulate bit values
a = 6
b = 3
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c = 0
c = a & b
print ("result of AND is ", c,':',bin(c))
c = a | b
print ("result of OR is ", c,':',bin(c))
c = a ^ b
print ("result of EXOR is ", c,':',bin(c))
c = ~a
print ("result of COMPLEMENT is ", c,':',bin(c))
c = a << 2
print ("result of LEFT SHIFT is ", c,':',bin(c))
c = a>>2
print ("result of RIGHT SHIFT is ", c,':',bin(c))

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

Python Membership Operators


These operators are used to test for membership in a sequence
a = 5
b = 10
list = [1, 2, 3, 4, 5]
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:

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

Python Identity Operators


These operators check if values on either side of equality operator point to the same object
a = 10
b = 10
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if (a is b):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")

Output
Line 1 a= 10 : 10914784 b= 10 : 10914784
Line 2 - a and b have same identity

Python Operator Overloading


According to Wikipedia, In computer programming, operator overloading, sometimes termed
operator ad hoc polymorphism is a specific case of polymorphism, where different operators
have different implementations depending on their arguments. Operator overloading is generally
defined by a programming language, a programmer, or both.

Operator Class Functions


- __sub__(self, other)
+ __add__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
== __eq__(self, other)
!= __ne__(self, other)
< __lt__(self, other)
> __gt__(self, other)
<= __le__(self, other)
>= __ge__(self, other)
-= __isub__(self, other)
+= __iadd__(self, other)
*= __imul__(self, other)
/= __idiv__(self, other)
//= __ifloordiv__(self, other)
%= __imod__(self, other)
**= __ipow__(self, other)
~ __invert__(self, other)

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

# adding two objects


def __add__(self, o):
return self.a + o.a
ob1 = A(1)
ob2 = A(2)
ob3 = A("CSharp")
ob4 = A("Coner")

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

# adding two objects


def __add__(self, other):
return self.a + other.a, self.b + other.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))

To find compound interest


p = int(input("Enter Principle"))
r = int(input("Enter Rate of Interest (as Percentage)"))
t = int(input("Enter Time Period (in years)"))
ci = p*pow((1+(r/100)),t)
print("Compound Interest {}".format(ci))

To find the area of a circle


import math
r = int(input("Enter the radius of the circle"))
ar = math.pi*pow(r,2)
print("Area of the circle is {}".format(ar))

https://www.c-sharpcorner.com/ebooks/ 22
4
Python Data Types

Overview

In this chapter, we explore the various data types in Python, including


numbers, strings, booleans, lists, tuples, sets, and dictionaries. We
examine their key characteristics, usage, and functionalities,
providing practical examples and code snippets. This comprehensive
overview will equip you with the knowledge to effectively utilize these
fundamental data types in Python programming.

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

TypeError: 'tuple' object does not support item assignment


Set: It is an unordered collection of unique and immutable items. Python Dictionary is used
commonly instead of Python Set. Denoted by {}
set1 = {11, 22, 33, 22}
print(set1)

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)

# Creating a List with the use of a String


List = ['CSharpCorner']
print("\nList with the use of String: ")
print(List)

# Creating a List with the use of multiple values


List = ["C", "Sharp", "Corner"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List (By Nesting a list inside a List)


List = [['C', 'Sharp'] , ['Corner']]
print("\nMulti-Dimensional 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)

# Creating a List with mixed type of values (Having numbers and


strings)
List = [1, 2, 'C', 4, 'Sharp', 6, 'Corner']
print("\nList with the use of Mixed Values: ")
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)

# Addition of Elements in the List


List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

# Adding elements to the List using Iterator


for i in range(1, 4):
List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)

# Adding Tuples to the List


List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)

# Addition of List to a List


List2 = ['C', 'Sharp']
List.append(List2)
print("\nList after Addition of a 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)

# Addition of Element at specific Position (using Insert Function)


List.insert(3, 12)
List.insert(0, 'CSharpCorner')
print("\nList after performing Insert Operation: ")
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)

# Addition of multiple elements to the List at the end (using Extend


Function)
List.extend([8, 'CSharp', 'Corner'])
print("\nList after performing Extend Operation: ")
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

# Creating a List with the use of multiple values


List = ["CSharp", "Corner"]

# accessing a element from the list using index number


print("Accessing an element from the list")
print(List[0])
print(List[1])

https://www.c-sharpcorner.com/ebooks/ 28
print("Accessing element from the list using negative indexing")
print(List[-1])
print(List[-2])

# Creating a Multi-Dimensional List (By Nesting a list inside a List)


List = [['Corner', 'Sharp'] , ['C']]

# accessing an element from the Multi-


Dimensional List using index number
print("Acessing an element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])

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)

# Removing elements from List using Remove() function


List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)

# Removing elements from List using iterator function


for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
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 from the Set using the pop() function


List.pop()
print("\nList after popping an element: ")
print(List)

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

# Print elements from beginning to a pre-defined point using Slice


Sliced_List = List[6:]
print("\nElements sliced from 6th element to last: ")
print(Sliced_List)

# Print elements of a range using index List slicing


Sliced_List = List[1:6]
print("\nElements sliced from index 1 to 6")
print(Sliced_List)

# Printing elements in order using Slice operation


Sliced_List = List[1::]
print("\nPrinting List in order: ")
print(Sliced_List)

# Print elements from beginning to a pre-defined point using Slice


Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last: ")
print(Sliced_List)

# Print elements of a range using negative index List slicing

https://www.c-sharpcorner.com/ebooks/ 30
Sliced_List = List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)

# Printing elements in reverse using Slice operation


Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
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']

Following is a list of all the functions provided by Python List

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)

# Creating a Dictionary with Integer Keys


Dict = {1: 'Python', 2: 'language', 3: 'is'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary with Mixed keys


Dict = {'Name': 'an', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary with dict() function


Dict = dict({1: 'scripting', 2: 'language', 3:'and'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary with each item as a Pair


Dict = dict([(1, 'not'), (2, 'a')])
print("\nDictionary with each item as a pair: ")
print(Dict)

# Creating a Nested Dictionary


print("\nNested Dictionary: ")
Dict = {1: 'programming', 2: 'language', 3:{'A' : 'Welcome', 'B' : 'To'
, 'C' : 'Python'}}
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 = {}

# Adding elements one at a time


Dict[0] = 'Python'
Dict[2] = 'Programming'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values to a single Key


Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)

# Adding Nested Key value to Dictionary


Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Python'}}
print("\nAdding a Nested Key: ")
print(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'}

# accessing an element using key

https://www.c-sharpcorner.com/ebooks/ 33
print("Accessing an element using key:")
print(Dict['name'])
print(Dict[1])

# accessing an element using get() function


print("\accessing an element using get:")
print(Dict.get(3))

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)

# Deleting a Key value


del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)

# Deleting a Key from Nested Dictionary


del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)

# Deleting a Key using pop()


Dict.pop(5)
print("\nPopping specific element: ")
print(Dict)

# Deleting an arbitrary Key-value pair using popitem()


Dict.popitem()
print("\nPops an arbitrary key-value pair: ")
print(Dict)

# Deleting entire Dictionary


Dict.clear()
print("\nDeleting Entire 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)

tup = 'python', 'pythons'


print(tup)
tup = ('python', 'pythons')
print(tup)

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

In this chapter, we explore Python’s control statements and loops,


covering conditions with it and if-else, looping mechanisms like while
and for, and control flow tools such as break, continue, and pass.
You’ll gain practical skills for managing program execution and
iteration in Python.

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'

Nested If-Else Statement


The nested if ... else statement allows you to check for multiple test expressions and executes
different codes for more than two conditions

num = float(input("enter a number:"))


if num >=0:
if num==0:
print("zero")
else:
print("Negative number")

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"

Python Control Loops


A control loop is a mechanism of declaring the control flow, it is looped as the same flow control
is repeated and again.

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.

for i in range (3,5):


print(i)

Output
3
4
In the above code, we are printing numbers from 3 to 5.

Nested For Loop


For loop within for loop is what we mean by nested for loops

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.

Python Jump Statements


They are used to transfer the program's control from one location to another. Means these are
used to alter the flow of a loop like-to skip a part of a loop or terminate a loop.

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.

for val in "init":


if val == "i":
continue
print(val)
print(" The End")

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.

Python Programming Examples


Factorial of a number
num = int(input("Enter number to find factorial"))
fact = 1
for i in range(1, num+1):
if i ==0:
fact = fact * 1
else:
fact= fact * i

print(fact)

To find list of all prime number in each interval


st = int(input("enter the start value of interval"))
et = int(input("enter the end value of interval"))

for i in range(st, et+1):


if i >1:
for j in range(2, i):
if i%j ==0:
break
else:
print(i)

To find N-th fibonocci series


nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,": {}".format(n1))
#print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)

https://www.c-sharpcorner.com/ebooks/ 44
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

A menu driven program to showcase various operations on python array


#function to take array input
def a_inp():
s = int(input("Enter the size of array"))
lst = []
for i in range(0, s):
ele = int(input())
lst.append(ele)
return lst

#function to print the sum of array elements


def a_sum():
a1 = a_inp()
print("sum of array elements is {}".format(sum(a1)))

#function to print the largest element


def a_large():
a1 = a_inp()
print("Largest array element is {}".format(max(a1)))

#function to left rotate the array


def a_rot():
a1 = a_inp()
n = int(input("How many elements to rotate"))
if n < len(a1):
print("Rotated Array:")
leftRotate(a1, n, len(a1))
else:
print("Enter value less than {}".format(len(a1)))

#driver function to do left rotate


def leftRotate(arr, d, n):
for i in range(d):
leftRotatebyOne(arr, n)

#function to left Rotate arr[] of size n by 1*/


def leftRotatebyOne(arr, n):
temp = arr[0]
for i in range(n-1):
arr[i] = arr[i+1]
arr[n-1] = temp

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

ch = int(input("Enter your choice"))

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

ch1 = input("Do you want to continue (y/n)")


if ch1 == 'n' or ch1 == 'N':
break

https://www.c-sharpcorner.com/ebooks/ 46
6
Python Class
Overview

In this chapter, we explore the basics of Python classes and object-


oriented programming. You’ll learn how to declare classes, create
objects, and utilize methods and constructors to manage data and
behavior effectively.

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

print(p1.x, p1.y, p1.name)

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.

Python Class Constructors


According to Wikipedia, in class-based object-oriented programming, a constructor is a special
type of subroutine called to create an object. It prepares the new object for use, often accepting
arguments that the constructor uses to set required member variables.
A constructor resembles an instance method, but it differs from a method in that it has no explicit
return type, it is not implicitly inherited, and it usually has different rules for scope modifiers.
In Python, the __init__() method is called the constructor and is always called when an object is
created.
Given below is the syntax of Python Class Constructor
def __init__(self, [parameter1, …, ….]):
#body

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)

def distance(self, other):


dx = self.x - other.x
dy = self.y - other.y
return sqrt(dx * dx + dy * dy)

In the above code, we have created 3 functions namely set_location(),


distance_from_origin() and distance().

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

def distance(self, other):


dx = self.x - other.x
dy = self.y - other.y
return sqrt(dx * dx + dy * dy)

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

toString and __str__


It is equivalent to Java's toString which converts objects to a string. It is automatically involved
when str or print is called.
Given below is the syntax for __str__ function
def __str__( self):
return string

from math import *

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)

def distance(self, other):


dx = self.x - other.x
dy = self.y - other.y
return sqrt(dx * dx + dy * dy)

def translate(self, dx, dy):


self.x += dx
self.y += dy

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

You might also like