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

Nitin Sharma Python Report

Uploaded by

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

Nitin Sharma Python Report

Uploaded by

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

 
IT REPORT

ON  

INDUSTRIAL TRAINING ON "PYTHON BOOTCAMP ” 

TAKEN AT  

“ institute of engineering & Technology ,Alwar”  

Submitted in partial fulfillment for the award of Degree of

Bachelor of Technology of Bikaner Technical University,

Rajasthan

2020-2021  

Guided by:- MR.Nitin Sharma 

Submitted by:-MRS.Deepika Upadhyay  

Student Name: Nitin Sharma 

ROll number-: 18EIACS052  


DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
INSTITUTE OF ENGINEERING & TECHNOLOGY ALWAR 

DECLARATION

I hereby declare that the seminar report entitled ​“ ​PYTHON BOOTCAMP ​” ​was carried
out and written by me under the guidance of ​MR. NITIN SHARMA (Assistant
Professor),

Department of Computer Science Engineering,IET,Alwar. This work has not been


previously formed the basis for the award of any degree or diploma or certificate nor
has been submitted elsewhere for the award of any degree or diploma.

Student Name: Nitin Sharma

RTU Roll No. : 18EIACS052

Year : 3rd year

Semester : 5th Sem


ACKNOWLEDGEMENT  

A project of such a vast coverage cannot be realized without help from numerous 
sources and people in the organization .I am thankful to the department of CSE for 
providing me a platform to carry out such a training successfully.  
I am also very grateful to ​Dr. Rohit Kumar Singhal (HOD,CSE) ​for his kind support.  
I would like to take this opportunity to show my gratitude towards all my supporting 
facultywho helped me in successful completion of my Second Year Practical Training. 
They have guided , motivated & appreciated and were source of inspiration for me to carry 
out the necessary proceedings for the training to be completed successfully.  
I am also grateful to Nitin Sharma sir from udemy for his guidance and support.  
I would also like to express my heartfelt gratitude to all of my friends whose direct or 
indirect suggestions help me to develop this project and to entire team members for their 
valuable Suggestions.  
Lastly, thanks to all faculty members of Computer Science Engineering Department 
for their moral support and guidance.  

Submitted By: Mr.Nitin Sharma 

Submitted To: MRS. Deepika Upadhyay 


Certificate  

This is to certify that ​NITIN SHARMA ​of B.Tech 3rd year Computer Science Engineering 
has submitted major project report entitled ​PYTHON BOOTCAMP ​in partial fulfillment 
for the award of degree of Bachelor of Technology from Bikaner Technical University, 
Rajasthan in the session 2020-21. This is to further certify that it is a bonafide record of 
the work carried out under my supervision.  

 
Name of Guide : Nitin Sharma 
IET Alwar 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 
 
 
  ABSTRACT  

From numerical weather prediction to processing data from weather radars or visualizing 
atmospheric conditions, computers have become an integral tool in the fields of meteorology and 
atmospheric science. However, computers require specific directions in the form of software. The 
ability to write this software, often customized for the particular needs of the user, goes hand-in 
hand with research and operations. This process can be time consuming and overly burdensome in 
many programming languages. Writing software to address the challenges in meteorology is simple 
using the Python programming language due to the language design, available libraries and 
community culture.  

Python is a general purpose, high-level programming language which is widely used in 
meteorology and elsewhere. The language facilitates a rapid development cycle with its interpreted 
and interactive nature. A focus on code readability makes the language easy to learn, and the 
expressive syntax leads to short, clear programs. Additionally, Python has excellent support for 
interfacing with legacy code written in C, C++ and Fortran making it an excellent tool for 
integrating existing software.  

Python has an extensive and comprehensive collection of freely available packages covering a 
variety of topics. Scientific Python libraries such as NumPy, SciPy, and pandas provide efficient 
implementation of numerical operations and tasks common in science and engineering. These 
libraries provide a strong base from which more advanced scientific software can be built without 
needing to worry about low-level algorithms. Additionally, many domain specific packages exist 
which address the scientific needs of the meteorological community.  

The Python community provides a welcoming and vibrant culture. The tutorials and other 
documentation provided for learning the language are rich and reinforce good programming 
practices. Videos, books, websites, mailing lists, and user groups provide opportunities for 
continued learning for beginners and experts alike. Python conferences around the world allow 
Pythonistas to discuss ideas, challenges, and new developments in an open and collaborative 
environment.  

Python is a practical key to unlocking powerful computational resources that can open the door to a 
variety of new career opportunities or that can enhance productivity in your current position. The 
author will detail his own experience of how Python led him to meteorology. 

 
Table of content  
Cover Page ….Candidate’s Declaration ….. 

Acknowledgement ….. ​CERTIFICATE. …… Abstract. 

…….. ​Table of content  

Chapter 1 About Python  

1.1 Why to learn python …. 1.2 Enviorment setup …. Chapter 

2 Python basic syntax   

 2.1 Python syntax …..  2.2 Python variable …..  Chapter 3 Basic 

operators ….. Chapter 4 Python data types   

4.1 Number …… 4.2 String …… 4.3 List ……. 4.4 Tuple ……..  

4.5 Set …….. 4.5 Dictionary …….. Chapter 5 Decision Making 

and LOOPS Chapter 6Python function ​….​ Chapter 7 Python 

Object-Oriented Language …... Chapter8 Libraries in Python 

…… Chapter 8 Reference   

  
CHAPTER 1​ ​ABOUT PYTHON  

Python  ​is  a  general-purpose  interpreted,  interactive,  object-oriented,  and  high-level 


programming  language.  It  was  created  by  Guido  van  Rossum  during  1985-  1990.  Like 
Perl,  Python  source  code  is  also  available  under  the  GNU  General  Public  License (GPL). 
This  ​tutorial  ​gives  enough  understanding  on ​Python programming ​language . ​The name  
of  the  Python  programming  language  comes  from  an  old  BBC  television  comedy  sketch  
series called ​Monty Python’s Flying Circus​.

Why to Learn Python?  

Python  ​is  a  high-level,  interpreted,  interactive  and  object-oriented  scripting  language. 


Python  is  designed  to  be  highly  readable.  It  uses  English  keywords  frequently  where  as 
other  languages  use  punctuation,  and  it  has  fewer  syntactical  constructions  than  other 
languages.  

Python  ​is  a  MUST  for  students  and  working  professionals  to  become  a  great  Software 
Engineer  specially  when  they  are  working  in  Web  Development  Domain.  I will list down 
some of the key advantages of learning Python:  

∙ ​Python  is  Interpreted  ​−  Python  is  processed  at  runtime  by  the  interpreter.  You  do 

not  need  to  compile  your  program before executing it. This is similar to PERL and 


PHP.  

∙ ​Python is Interactive ​− You can actually sit at a Python prompt and interact with 
the interpreter directly to write your programs.  

∙ ​Python is Object-Oriented ​− Python supports Object-Oriented style or technique of 


programming that encapsulates code within objects.  

∙ ​Python is a Beginner's Language ​− Python is a great language for the beginner 


level programmers and supports the development of a wide range of applications 
from simple text processing to WWW browsers to games.  

Characteristics of Python  

Following are important characteristics of ​Python Programming ​−


∙ ​It supports functional and structured programming methods as well as OOP.  
∙ ​It can be used as a scripting language or can be compiled to byte-code for building 
large applications.  

∙ ​It provides very high-level dynamic data types and supports dynamic type checking.  

∙ ​It supports automatic garbage collection.  

∙ ​It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.  

Applications of Python  

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.  

Enviourment setup​:-  

Many PCs and Macs will have python already installed.  

To check if you have python installed on a Windows PC, search in the start bar for Python 
or run the following on the Command Line (cmd.exe):  

C:\Users\​Your Name​>python --version  

To check if you have python installed on a Linux or Mac, then on linux open the command 
line or on Mac open the Terminal and type:  

python --version  

If you find that you do not have python installed on your computer, then you can download 
it for free from the following website: ​https://www.python.org/  

Python Quickstart  

Python  is  an  interpreted  programming  language,  this  means  that  as  a  developer  you  write 
Python  (.py)  files  in  a  text  editor  and  then  put  those  files  into  the  python  interpreter  to  be 
executed.  

The way to run a python file is like this on the command line:  

C:\Users\​Your Name​>python helloworld.py  

Where "helloworld.py" is the name of your python file.  

Let's write our first Python file, called helloworld.py, which can be done in any text 

editor. helloworld.py

print("Hello, World!")  
Simple as that. Save your file. Open your command line, navigate to the directory where
you saved your file, and run:

C:\Users\​Your Name​>python helloworld.py  

The output should read:  

Hello, World!  

The Python Command Line  

To test a short amount of code in python sometimes it is quickest and easiest not to write 
the code in a file. This is made possible because Python can be run as a command line 
itself.  

Type the following on the Windows, Mac or Linux command line:  

C:\Users\​Your Name​>python  

Or, if the "python" command did not work, you can try "py":  

C:\Users\​Your Name​>py  

From there you can write any python, including our hello world example from earlier in 
the tutorial:  

C:\Users\​Your Name​>python  
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on 
win32  
Type "help", "copyright", "credits" or "license" for more 
information. >>> print("Hello, World!")  

Which will write "Hello, World!" in the command line:  

C:\Users\​Your Name​>python  
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more 
information. >>> print("Hello, World!")  
Hello, World!  

Whenever you are done in the python command line, you can simply type the following to 
quit the python command line interface: exit () 
CHAPTER 2  

PYTHON BASIC SYNTAX  

Execute Python Syntax  

As we learned in the previous page, Python syntax can be executed by writing directly in 
the Command Line:  

>>> print("Hello, World!")  


Hello, World!  

Or by creating a python file on the server, using the .py file extension, and running it in the 
Command Line:  

C:\Users\​Your Name​>python myfile.py  

Python Indentation  

Indentation refers to the spaces at the beginning of a code line.  


Where in other programming languages the indentation in code is for readability only, the 
indentation in Python is very important.  
Python uses indentation to indicate a block of code.  
Example  
if 5 > 2:  
print("Five is greater than two!")  
Python will give you an error if you skip the indentation:  
Example  
Syntax Error:  
if 5 > 2:  
print("Five is greater than two!")  
The number of spaces is up to you as a programmer, but it has to be at least one. 
 
 
Example  
if 5 > 2:  
print("Five is greater than two!")  
if 5 > 2:  
print("Five is greater than two!")  
You have to use the same number of spaces in the same block of code, otherwise Python 
will give you an error:  
Example  
Syntax Error:  
if 5 > 2:  
print("Five is greater than two!")  
print("Five is greater than two!")  
Python Variables  

In Python, variables are created when you assign a value to it:  

Example  
Variables in Python:  
x = 5  
y = "Hello, World!"  

Python has no command for declaring a variable.  

Comments  

Python has commenting capability for the purpose of in-code documentation. 

Comments start with a #, and Python will render the rest of the line as a comment:  

Example  
Comments in Python:  
#This is a comment.  
print("Hello, World!")  

Python comments 
Comments can be used to explain Python code.  
Comments can be used to make the code more readable.  

Comments can be used to prevent execution when testing code.  

Creating a Comment  

Comments starts with a ​#​, and Python will ignore them:  

Example  
#This is a comment  
print("Hello, World!")  

Comments can be placed at the end of a line, and Python will ignore the rest of the line:  

Example  
print("Hello, World!") #This is a comment  

Comments does not have to be text to explain the code, it can also be used to prevent 
Python from executing code:  

Example  
#print("Hello, World!")  
print("Cheers, Mate!")  
Multi Line Comments  

Python does not really have a syntax for multi line comments.  

To add a multiline comment you could insert a ​# ​for each line:  

Example  
#This is a comment  
#written in  
#more than just one line  
print("Hello, World!") 
Or, not quite as intended, you can use a multiline string.  

Since Python will ignore string literals that are not assigned to a variable, you can add a 
multiline string (triple quotes) in your code, and place your comment inside it:  

Example  
"""  
This is a comment  
written in  
more than just one line  
"""  
print("Hello, World!")  

As long as the string is not assigned to a variable, Python will read the code, but then 
ignore it, and you have made a multiline comment.  

Python variable ​:-  

Variables  

Variables are containers for storing data values.  

Creating Variables  

Python has no command for declaring a variable.  

A variable is created the moment you first assign a value to it.  

Example  
x = 5  
y = "John"  
print(x)  
print(y)  

Variables do not need to be declared with any particular ​type​, and can even change type after 
they have been set. 
Example  
x = 4 # x is of type int  
x = "Sally" # x is now of type str  
print(x)  

Casting  

If you want to specify the data type of a variable, this can be done with casting.  

Example  
x = str(3) # x will be '3'  
y = int(3) # y will be 3  
z = float(3) # z will be 3.0  

Get the Type  

You can get the data type of a variable with the ​type() ​function.  

Example  
x = 5  
y = "John"  
print(type(x))  
print(type(y))  

Single of Double Quotes?  

String variables can be declared either by using single or double

quotes: ​Example  

x = "John"  
# is the same as  
x = 'John'  

Case-Sensitive  
Variable names are case-sensitive.
Example  
This will create two variables:
a = 4  
A = "Sally"  
#A will not overwrite  

Variable Names  
A variable can have a short name (like x and y) or a more descriptive name (age, carname,  
total_volume). Rules for Python variables:  
A variable name must start with a letter or the underscore character  
A variable name cannot start with a number  
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and 
_ (underscore))  
Variable names are case-sensitive (age, Age and AGE are three different 
variables) Example  
Legal variable names:  
myvar = "John"  
my_var = "John"  
_my_var = "John"  
myVar = "John"  
MYVAR = "John"  
myvar2 = "John"  
Example  
Illegal variable names:  
2myvar = "John"  
my-var = "John"  
my var = "John"  
Remember that variable names are case-sensitive  
Multi Words Variable Names  
Variable names with more than one word can be difficult to read.  
There are several techniques you can use to make them more readable: 
Camel Case  
Each word, except the first, starts with a capital letter:  
myVariableName = "John"  
Pascal Case
Each word starts with a capital letter:  
MyVariableName = "John"  

Snake Case  
Each word is separated by an underscore character:  
my_variable_name = "John"  
Python Variables - Assign Multiple Values  

Many Values to Multiple Variables  


Python allows you to assign values to multiple variables in one 
line: Example  
x, y, z = "Orange", "Banana", "Cherry"  
print(x)  
print(y)  
print(z)  
Note: ​Make sure the number of variables matches the number of values, or else you will 
get an error.  

One Value to Multiple Variables  


And you can assign the ​same ​value to multiple variables in one 
line: Example  
x = y = z = "Orange"  
print(x)  
print(y)  
print(z)  
Unpack a Collection  
If you have a collection of values in a list, tuple etc. Python allows you extract the values 
into variables. This is called ​unpacking.​   
Example  
Unpack a list:  
fruits = ["apple", "banana", "cherry"]  
x, y, z = fruits  
print(x)
print(y)  
print(z)  

Python – output variables   


Output Variables:-  
The Python ​print ​statement is often used to output variables. To 
combine both text and a variable, Python uses the ​+​ character: 
Example  
x = "awesome"  
print("Python is " + x)  
You can also use the ​+​ character to add a variable to another variable: 
Example  
x = "Python is "  
y = "awesome"  
z = x + y  
print(z)  
For numbers, the ​+​ character works as a mathematical 
operator: Example  
x = 5  
y = 10  
print(x + y)  
If you try to combine a string and a number, Python will give you an 
error: Example  
x = 5  
y = "John"  
print(x + y) 
 
 
 
 
 
 
 
CHAPTER 3  
BASIC OPERATOR  

Python Operators  
Operators are used to perform operations on variables and values.  
In the example below, we use the ​+​ operator to add together two 
values: ​Example  
print(10 + 5)  
Python divides the operators in the following groups:  
∙ ​Arithmetic operators  
∙ ​Assignment operators  
∙ ​Comparison operators  
∙ ​Logical operators  
∙ ​Identity operators  
∙ ​Membership operators  
∙ ​Bitwise operators  
Python Arithmetic Operators  
Arithmetic operators are used with numeric values to perform common 
mathematical operations: 

Operator   Name   Example 

+   Addition   x + y 

-   Subtraction   x - y 

*   Multiplication  
/   Division   x / y 

%   Modulus   x % y 

**   Exponentiation   x ** y 

//   Floor division   x // y 

Assignment Operators  
Assignment operators are used to assign  Python   
values to variables: 
 
Operator   Example   Same As 

=   x = 5   x = 5 

+=   x += 3   x = x + 3 

-=   x -= 3   x = x - 3 

*=   x *= 3   x = x * 3 

/=   x /= 3   x = x / 3 
%=   x %= 3   x = x % 3 

//=   x //= 3   x = x // 3 

**=   x **= 3   x = x ** 3 

&=   x &= 3   x = x & 3 

|=   x |= 3   x = x | 3 

^=   x ^= 3   x = x ^ 3 

>>=   x >>= 3   x = x >> 3 

<<=   x <<= 3   x = x << 3 

Python Comparison Operators  

Comparison operators are used to compare two values: 


Operator   Name   Example 

==   Equal   x == y 
!=   Not equal   x != y 

>   Greater than   x > y 

<   Less than   x < y 

>=   Greater than or equal to  

<=   Less than or equal to   x <= y 

Python Logical Operators  

Logical operators are used to combine conditional statements:  


Operator   Description   Example 

and   Returns True if both statements are true   x < 5 and x 


< 10 

or   Returns True if one of the statements is true   x < 5 or x < 4 

not   Reverse the result, returns False if the result is true   not(x < 5 and 
x < 10) 

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are  
actually the same object, with the same memory location:  
Operator   Description   Example 

is   Returns True if both variables are the  x is y 


same object 

is not   Returns True if both variables are not  x is not y 


the same object 

Python Membership Operators  

Membership operators are used to test if a sequence is presented in an object:  


Operator   Description   Example 

in   Returns True if a sequence with the specified value  x in y 


is ​ ​present in the object 

not in   Returns True if a sequence with the specified value is  x not in y 
not present in the object 

Python Bitwise Operators  

Bitwise operators are used to compare (binary) numbers: 


Operator   Name   Description 

&   AND   Sets each bit to 1 if both bits are 1 


|   OR   Sets each bit to 1 if one of two bits is 1 

^   XOR   Sets each bit to 1 if only one of two bits is 1 

~   NOT   Inverts all the bits 

<<   Zero fill left shift   Shift left by pushing zeros in from the right and let 
the ​ ​leftmost bits fall off 

>>     shift Shift right by pushing copies of the leftmost bit in 
om the left, and let the rightmost bits fall off 
CHAPTER 4  
PYTHON DATA TYPES  

Built-in Data Types  

In programming, data type is an important concept.  

Variables can store data of different types, and different types can do different 

things. ​Python has the following data types built-in by default, in these categories:  

Text Type:   Str 

Numeric Types:   int​, f​ loat​, ​complex 

Sequence Types:   list​, ​tuple​, r​ ange 

Mapping Type:   Dict 

Set Types:   set​, f​ rozenset 

Boolean Type:   Bool 

Binary Types:   bytes​, ​bytearray​, ​memoryview 

Getting the Data Type  

You can get the data type of any object by using the ​type()​ ​function:  

Example  

Print the data type of the variable x:  

x = ​5  
print​(​type​(x))  

Setting the Data Type  


In Python, the data type is set when you assign a value to a variable:
Example   Data Type 

x = "Hello World"   Str 

x = 20   Int 

x = 20.5   Float 

x = 1j   Complex 

x = ["apple", "banana", "cherry"]   List 

x = ("apple", "banana", "cherry")   Tuple 

x = range(6)   Range 

x = {"name" : "John", "age" : 36}   Dict 

x = {"apple", "banana", "cherry"}   Set 


x = frozenset({"apple",  Frozenset 
"banana", "cherry"}) 

x = True   Bool 

x = b"Hello"   Bytes 

x = bytearray(5)   Bytearray 

x = memoryview(bytes(5))   Memoryview 

Setting the Specific Data Type  

If you want to specify the data type, you can use the following constructor functions: 
Example   Data Type 

x = str("Hello World")   Str 

x = int(20)   Int 

x = float(20.5)   Float 
x = complex(1j)   complex 

x = list(("apple", "banana", "cherry"))   List 

x = tuple(("apple", "banana", "cherry"))   Tuple 

x = range(6)   Range 

x = dict(name="John", age=36)   Dict 

x = set(("apple", "banana", "cherry"))   Set 

x = frozenset(("apple", "banana", "cherry"))   frozenset 

x = bool(5)   Bool 

x = bytes(5)   Bytes 

x = bytearray(5)   bytearray 
x = memoryview(bytes(5))   memoryview 

Python number ​:-  


There are three numeric types in Python:  
int  
float  
complex  
Variables of numeric types are created when you assign a value to 
them: ​Example  
x = 1 # int  
y = 2.8 # float  
z = 1j # complex  

To verify the type of any object in Python, use the ​type()​ function:  
Example  
print(type(x))  
print(type(y))  
print(type(z))  
Int  

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited 


length.  

Example  

Integers:  

x = 1  
y = 35656222554887711  
z = -3255522  

print(type(x)) 
print(type(y))  
print(type(z)  

Float  

Float, or "floating point number" is a number, positive or negative, containing one or more 
decimals.  
Example  
Floats:  
x = 1.10  
y = 1.0  
z = -35.59  

print(type(x))  
print(type(y))  
print(type(z))  

Float can also be scientific numbers with an "e" to indicate the power of 

10. ​Example  

Floats:  

x = 35e3  
y = 12E4  
z = -87.7e100  

print(type(x))  
print(type(y))  
print(type(z))  

Complex  

Complex numbers are written with a "j" as the imaginary part:  


Example  
Complex:
x = 3+5j  
y = 5j  
z = -5j  
print(type(x))  
print(type(y))  
print(type(z))  
Type Conversion  
You can convert from one type to another with the ​int()​, ​float()​, and ​complex() 
methods: ​Example  
Convert from one type to another:  
x = 1 # int  
y = 2.8 # float  
z = 1j # complex  
#convert from int to float:  
a = float(x)  
#convert from float to int:  
b = int(y)  
#convert from int to complex:  
c = complex(x)  
print(a)  
print(b)  
print(c)  
print(type(a))  
print(type(b))  
print(type(c))  
Note: ​You cannot convert complex numbers into another number 
type. ​Random Number  

Python does not have a ​random()​ function to make a random number, but Python has a 
built-in module called ​random ​that can be used to make random numbers: ​Example  
Import the random module, and display a random number between 1 and 
9: import random  
print(random.randrange(1, 10)) 

Strings  
Strings in python are surrounded by either single quotation marks, or double quotation 
marks.  
'hello'​ is the same as ​"hello"​.  
You can display a string literal with the ​print()​ function:  
Example  
print("Hello")  
print('Hello')  
Assign String to a Variable  
Assigning a string to a variable is done with the variable name followed by an equal sign 
and the string:  
Example  
a = "Hello"  
print(a)  
Multiline Strings  
You can assign a multiline string to a variable by using three 
quotes: ​Example  
You can use three double quotes:  
a = """Lorem ipsum dolor sit amet,  
consectetur adipiscing elit,  
sed do eiusmod tempor incididunt  
ut labore et dolore magna aliqua."""  
print(a)  
Or three single quotes:  
Example  
a = '''Lorem ipsum dolor sit amet,  
consectetur adipiscing elit,  
sed do eiusmod tempor incididunt  
ut labore et dolore magna aliqua.'''  
print(a)  
Note: ​in the result, the line breaks are inserted at the same position as in the 
code. ​Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes 
representing unicode characters.  
However, Python does not have a character data type, a single character is simply a string 
with a length of 1.  
Square brackets can be used to access elements of the string.  
Example  
Get the character at position 1 (remember that the first character has the position 0): 
a = "Hello, World!"  
print(a[1])  
Looping Through a String  
Since strings are arrays, we can loop through the characters in a string, with a ​for 
loop. ​Example  
Loop through the letters in the word "banana":  
for x in "banana":  
print(x)  
String Length  
To get the length of a string, use the ​len()​ function.  
Example  
The ​len()​ function returns the length of a string:  
a = "Hello, World!"  
print(len(a))  
Check String  
To check if a certain phrase or character is present in a string, we can use the keyword 
in​. ​Example  
Check if "free" is present in the following text:  
txt = "The best things in life are free!"  
print("free" in txt)  
Use it in an ​if ​statement​:  
Example  
Print only if "free" is present:  
txt = "The best things in life are free!"  
if "free" in txt:  
print("Yes, 'free' is present.") 
 
Check if NOT  
To check if a certain phrase or character is NOT present in a string, we can use the 
keyword ​not in​.  
Example  
Check if "expensive" is NOT present in the following text:  
txt = "The best things in life are free!"  
print("expensive" not in txt)  
Use it in an ​if​ statement:  
Example  
print only if "expensive" is NOT present:  
txt = "The best things in life are free!"  
if "expensive" not in txt:  
print("Yes, 'expensive' is NOT present.")  
Escape Character  
To insert characters that are illegal in a string, use an escape character. An escape 
character is a backslash ​\​ followed by the character you want to insert. An example of an 
illegal character is a double quote inside a string that is surrounded by double quotes:  
Example  
You will get an error if you use double quotes inside a string that is surrounded by double 
quotes:  
txt = "We are the so-called "Vikings" from the north."  
To fix this problem, use the escape character ​\"​:  
Example  
The escape character allows you to use double quotes when you normally would not be 
allowed:  
txt = "We are the so-called \"Vikings\" from the north."  
Escape Characters  
Other escape characters used in Python: 
Code   Result 

\'   Single Quote 

\\   Backslash 

\n   New Line 


\r   Carriage Return 

\t   Tab 

\b   Backspace 

\f   Form Feed 

\ooo   Octal value 

\xhh   Hex value 

String Methods  
Python has a set of built-in methods that you can use on strings.  
Note: ​All string methods returns new values. They do not change the original string. 
Method   Description 

capitalize()   Converts the first character to upper case 

casefold()   Converts string into lower case 

center()   Returns a centered string 

count()   Returns the number of times a specified value occurs in a string 

encode()   Returns an encoded version of the string 

endswith()   Returns true if the string ends with the specified value 

expandtabs()   Sets the tab size of the string 

find()   Searches the string for a specified value and returns the position of 
where it was found 

format()   Formats specified values in a string 

format_map()   Formats specified values in a string 


index()   Searches the string for a specified value and returns the position of 
where it was found 

isalnum()   Returns True if all characters in the string are alphanumeric 

isalpha()   Returns True if all characters in the string are in the alphabet 

isdecimal()   Returns True if all characters in the string are decimals 

isdigit()   Returns True if all characters in the string are digits 

isidentifier()   Returns True if the string is an identifier 

islower()   Returns True if all characters in the string are lower case 

isnumeric()   Returns True if all characters in the string are numeric 

isprintable()   Returns True if all characters in the string are printable 

isspace()   Returns True if all characters in the string are whitespaces 

istitle()   Returns True if the string follows the rules of a title 

isupper()   Returns True if all characters in the string are upper case 

j​oin()   Joins the elements of an iterable to the end of the string 

ljust()   Returns a left justified version of the string 

lower()   Converts a string into lower case 

lstrip()   Returns a left trim version of the string 

maketrans()   Returns a translation table to be used in translations 

partition()   Returns a tuple where the string is parted into three parts 

replace()   Returns a string where a specified value is replaced with a specified value 
rfind()   Searches the string for a specified value and returns the last position 
of where it was found 

rindex()   Searches the string for a specified value and returns the last position 
of where it was found 

rjust()   Returns a right justified version of the string 

rpartition()   Returns a tuple where the string is parted into three parts 

rsplit()   Splits the string at the specified separator, and returns a list 

rstrip()   Returns a right trim version of the string 

split()   Splits the string at the specified separator, and returns a list 

splitlines()   Splits the string at line breaks and returns a list 

startswith()   Returns true if the string starts with the specified value 

strip()   Returns a trimmed version of the string 

swapcase()   Swaps cases, lower case becomes upper case and vice versa 

title()   Converts the first character of each word to upper case 

translate()   Returns a translated string 

upper()   Converts a string into upper case 

zfill()   Fills the string with a specified number of 0 values at the beginning 

Python Lists  
Lists are used to store multiple items in a single variable.  
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 
are ​Tuple​, ​Set​, and ​Dictionary​, all with different qualities and usage.
Lists are created using square brackets:  
Example  
Create a List:  
thislist = ["apple", "banana", "cherry"]  
print(thislist)  
List Items  
List items are ordered, changeable, and allow duplicate values.  
List items are indexed, the first item has index ​[0]​, the second item has index ​[1] ​etc. 
Ordered  
When we say that lists are ordered, it means that the items have a defined order, and that 
order will not change.  
If you add new items to a list, the new items will be placed at the end of the list. ​Note: 
There are some ​list methods ​that will change the order, but in general: the order of the 
items will not change.  

Changeable  
The list is changeable, meaning that we can change, add, and remove items in a list after it 
has been created.  

Allow Duplicates  
Since lists are indexed, lists can have items with the same value:  
Example  
Lists allow duplicate values:  
thislist = ["apple", "banana", "cherry", "apple", "cherry"]  
print(thislist)  
List Length  
To determine how many items a list has, use the ​len()​ function:  
Example  
Print the number of items in the list:  
thislist = ["apple", "banana", "cherry"]  
print(len(thislist))  
List Items - Data Types  
List items can be of any data type:  
Example
String, int and boolean data types:  
list1 = ["apple", "banana", "cherry"]  
list2 = [1, 5, 7, 9, 3]  
list3 = [True, False, False]  
A list can contain different data types:  
Example  
A list with strings, integers and boolean values:  
list1 = ["abc", 34, True, 40, "male"]  
type()  
From Python's perspective, lists are defined as objects with the data type 
'list': <class 'list'>  
Example  
What is the data type of a list?  
mylist = ["apple", "banana", "cherry"]  
print(type(mylist))  
Python Collections (Arrays)  
There are four collection data types in the Python programming language: ​List ​is a 
collection which is ordered and changeable. Allows duplicate members. ​Tuple ​is a 
collection which is ordered and unchangeable. Allows duplicate members. ​Set​ ​is a 
collection which is unordered and unindexed. No duplicate members. ​Dictionary ​is a 
collection which is unordered and changeable. No duplicate members. When choosing a 
collection type, it is useful to understand the properties of that type. Choosing the right 
type for a particular data set could mean retention of meaning, and, it could mean an 
increase in efficiency or security.  

Access Items  
List items are indexed and you can access them by referring to the index number: 
Example  
Print the second item of the list:  
thislist = ["apple", "banana", "cherry"]  
print(thislist[1])  
Note: ​The first item has index 0.  
Negative Indexing
Negative indexing means start from the end  
-1 ​refers to the last item, ​-2 ​refers to the second last item etc.  
Example  
Print the last item of the list:  
thislist = ["apple", "banana", "cherry"]  
print(thislist[-1])  
Range of Indexes  
You can specify a range of indexes by specifying where to start and where to end the 
range.  
When specifying a range, the return value will be a new list with the specified 
items. ​Example  
Return the third, fourth, and fifth item:  
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", 
"mango"] print(thislist[2:5])  
Note: ​The search will start at index 2 (included) and end at index 5 (not 
included). Remember that the first item has index 0.  
By leaving out the start value, the range will start at the first 
item: ​Example  
This example returns the items from the beginning to, but NOT included, "kiwi": 
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] 
print(thislist[:4])  
By leaving out the end value, the range will go on to the end of the 
list: ​Example  
This example returns the items from "cherry" and to the end:  
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", 
"mango"] print(thislist[2:])  

Range of Negative Indexes  


Specify negative indexes if you want to start the search from the end of the 
list: ​Example  
This example returns the items from "orange" (-4) to, but NOT included. "mango" 
(-1): thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] 
print(thislist[-4:-1])  

Check if Item Exists


To determine if a specified item is present in a list use the ​in ​keyword: 
Example  
Check if "apple" is present in the list:  
thislist = ["apple", "banana", "cherry"]  
if "apple" in thislist:  
print("Yes, 'apple' is in the fruits list")  
Python Tuples  
Tuples are used to store multiple items in a single variable.  
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 
are ​List​, ​Set​, and ​Dictionary​, all with different qualities and usage.  
A tuple is a collection which is ordered and ​unchangeable​.  
Tuples are written with round brackets.  
Example  
Create a Tuple:  
thistuple = ("apple", "banana", "cherry")  
print(thistuple)  
Tuple Items  
Tuple items are ordered, unchangeable, and allow duplicate values.  
Tuple items are indexed, the first item has index ​[0]​, the second item has index ​[1] 
etc. ​Ordered  

When we say that tuples are ordered, it means that the items have a defined order, and that 
order will not change.  

Unchangeable  
Tuples are unchangeable, meaning that we cannot change, add or remove items after the 
tuple has been created.  

Allow Duplicates  
Since tuple are indexed, tuples can have items with the same value:  
Example  
Tuples allow duplicate values:  
thistuple = ("apple", "banana", "cherry", "apple", "cherry")  
print(thistuple)  
Tuple Length
To determine how many items a tuple has, use the ​len()​ function:  
Example  
Print the number of items in the tuple:  
thistuple = ("apple", "banana", "cherry")  
print(len(thistuple))  
Create Tuple With One Item  
To create a tuple with only one item, you have to add a comma after the item, otherwise 
Python will not recognize it as a tuple.  
Example  
One item tuple, remember the commma:  
thistuple = ("apple",)  
print(type(thistuple))  

#NOT a tuple  
thistuple = ("apple")  
print(type(thistuple))  
Tuple Items - Data Types  
Tuple items can be of any data type:  
Example  
String, int and boolean data types:  
tuple1 = ("apple", "banana", "cherry")  
tuple2 = (1, 5, 7, 9, 3)  
tuple3 = (True, False, False)  
A tuple can contain different data types:  
Example  
A tuple with strings, integers and boolean values:  
tuple1 = ("abc", 34, True, 40, "male")  
type()  
From Python's perspective, tuples are defined as objects with the data type 'tuple': 
<class 'tuple'>  
Example  
What is the data type of a tuple? 
 
mytuple = ("apple", "banana", "cherry")  
print(type(mytuple))  
The tuple() Constructor  
It is also possible to use the ​tuple()​ constructor to make a tuple.  
Example  
Using the tuple() method to make a tuple:  
thistuple = tuple(("apple", "banana", "cherry")) # note the double 
round-brackets print(thistuple)  

Python Sets  
Sets are used to store multiple items in a single variable.  
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 
are ​List​, ​Tuple​, and ​Dictionary​, all with different qualities and usage. A set is a 
collection which is both ​unordered ​and ​unindexed​.  
Sets are written with curly brackets​.  
Example  
Create a Set:  
thisset = {"apple", "banana", "cherry"}  
print(thisset)  
Note: ​Sets are unordered, so you cannot be sure in which order the items will 
appear. Set Items  
Set items are unordered, unchangeable, and do not allow duplicate 
values. Unordered  
Unordered means that the items in a set do not have a defined order. Set items can appear 
in a different order every time you use them, and cannot be referred to by index or key.  

Unchangeable  
Sets are unchangeable, meaning that we cannot change the items after the set has been 
created.  
Once a set is created, you cannot change its items, but you can add new 
items. ​Duplicates Not Allowed  

Sets cannot have two items with the same value.  


Example  
Duplicate values will be ignored: 
 
thisset = {"apple", "banana", "cherry", "apple"}  

print(thisset)  

Get the Length of a Set  


To determine how many items a set has, use the ​len()​ ​method. 
Example  
Get the number of items in a set:  
thisset = {"apple", "banana", "cherry"}  
print(len(thisset))  
Set Items - Data Types  
Set items can be of any data type:  
Example  
String, int and boolean data types:  
set1 = {"apple", "banana", "cherry"}  
set2 = {1, 5, 7, 9, 3}  
set3 = {True, False, False}  
A set can contain different data types:  
Example  
A set with strings, integers and boolean values:  
set1 = {"abc", 34, True, 40, "male"}  

type()  
From Python's perspective, sets are defined as objects with the data type 
'set': <class 'set'>  
Example  
What is the data type of a set?  
myset = {"apple", "banana", "cherry"}  
print(type(myset))  

The set() Constructor  


It is also possible to use the ​set() c​ onstructor to make a 
set. ​Example  
Using the set() constructor to make a set:  
thisset = set(("apple", "banana", "cherry")) # note the double 
round-brackets print(thisset) 

Python Dictionaries  
Dictionaries are used to store data values in key:value pairs.  
A dictionary is a collection which is unordered, changeable and does not allow 
duplicates. Dictionaries are written with curly brackets, and have keys and values: 
Example  
Create and print a dictionary:  
thisdict = {  
"brand": "Ford",  
"model": "Mustang",  
"year": 1964  
}  
print(thisdict)  

Dictionary Items  
Dictionary items are unordered, changeable, and does not allow duplicates. Dictionary 
items are presented in key:value pairs, and can be referred to by using the key name.  
Example  
Print the "brand" value of the dictionary:  
thisdict = {  
"brand": "Ford",  
"model": "Mustang",  
"year": 1964  
}  
print(thisdict["brand"])  

Unordered  
When we say that dictionaries are unordered, it means that the items does not have a defined 
order, you cannot refer to an item by using an index.  

Changeable  
Dictionaries are changeable, meaning that we can change, add or remove items after the 
dictionary has been created.  

Duplicates Not Allowed  


Dictionaries cannot have two items with the same key:  
Example  
Duplicate values will overwrite existing values:
thisdict = {  
"brand": "Ford",  
"model": "Mustang",  
"year": 1964,  
"year": 2020  
}  
print(thisdict)  

Dictionary Length  
To determine how many items a dictionary has, use the ​len() 
function: ​Example  
Print the number of items in the dictionary:  
print(len(thisdict))  

Dictionary Items - Data Types  


The values in dictionary items can be of any data type:  
Example  
String, int, boolean, and list data types:  
thisdict = {  
"brand": "Ford",  
"electric": False,  
"year": 1964,  
"colors": ["red", "white", "blue"]  
}  

type()  
From Python's perspective, dictionaries are defined as objects with the data type 
'dict': <class 'dict'>  
Example  
Print the data type of a dictionary:  
thisdict = {  
"brand": "Ford",  
"model": "Mustang",  
"year": 1964  
}  
print(type(thisdict)) 
CHAPTER 5​ ​PYTHON DECISION MAKING 

AND LOOPS  

Decision making  

Decision making is anticipation of conditions occurring while execution of the program 


and specifying actions taken according to the conditions.  

Decision  structures  evaluate  multiple  expressions  which  produce  TRUE  or  FALSE  as 
outcome.  You  need  to  determine  which  action  to  take  and  which  statements  to  execute  if 
outcome is TRUE or FALSE otherwise.  

Following is the general form of a typical decision making structure found in most of the 
programming languages −  

 
Python programming language assumes any ​non-zero ​and ​non-null ​values as TRUE, and 
if it is either ​zero ​or ​null​, then it is assumed as FALSE value.  

Python programming language provides following types of decision making statements. 


Click the following links to check their detail.
Sr.No.   Statement & Description 

1   if statements  

An ​if statement ​consists of a boolean expression followed by one or more 


statements. 

2   if...else statements  

An ​if statement ​can be followed by an optional ​else statement​, which 


executes when the boolean expression is FALSE. 

3   nested if statements  

You can use one ​if o​ r ​else if ​statement inside another ​if ​or ​else if ​statement(s). 

Loops  

In general, statements are executed sequentially: The first statement in a function is 
executed first, followed by the second, and so on. There may be a situation when you need 
to execute a block of code several number of times.  

Programming languages provide various control structures that allow for more 
complicated execution paths.  

A loop statement allows us to execute a statement or group of statements multiple times. 


The following diagram illustrates a loop statement −
Python programming language provides following types of loops to handle looping 
requirements.  

Sr.No.   Loop Type & Description 

1   while loop  

Repeats a statement or group of statements while a given condition is 


TRUE. It tests the condition before executing the loop body. 

2   for loop  

Executes a sequence of statements multiple times and abbreviates the 


code that manages the loop variable. 

3   nested loops  

You can use one or more loop inside any another while, for or do..while 
loop. 

Loop Control Statements  


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

Let us go through the loop control statements briefly 


Sr.No.   Control Statement & Description 

1   break statement  

Terminates the loop statement and transfers execution to the statement 


immediately following the loop. 

2   continue statement  

Causes the loop to skip the remainder of its body and immediately retest 
its condition prior to reiterating. 

3   pass statement  

The pass statement in Python is used when a statement is required 


syntactically but you do not want any command or code to execute. 
CHAPTER 6​ ​PYTHON FUNCTION  

A function is a block of code which only runs when it is called.  

You can pass data, known as parameters, into a function.  

A function can return data as a result.  

Creating a Function  

In Python a function is defined using the ​def​ ​keyword:  

Example  

def my_function():  
print("Hello from a function")  

Calling a Function  

To call a function, use the function name followed by parenthesis:  

Example  

def my_function():  
print("Hello from a function")  
my_function()  

Arguments  

Information can be passed into functions as arguments.  

Arguments are specified after the function name, inside the parentheses. You can add as 
many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is 
called, we pass along a first name, which is used inside the function to print the full 
name:  
 

Example  

def my_function(​fname​):  
print(fname + " Refsnes")  
my_function(​"Emil"​)  
my_function(​"Tobias"​)  
my_function(​"Linus"​)  

Arguments ​are often shortened to ​args i​ n Python documentations​.  

Parameters or Arguments?  

The terms ​parameter ​and ​argument c​ an be used for the same thing: information that are 
passed into a function.  

From a function's perspective:  

A parameter is the variable listed inside the parentheses in the function 

definition. An argument is the value that is sent to the function when it is called. 

Number of Arguments  

By default, a function must be called with the correct number of arguments. Meaning that 
if your function expects 2 arguments, you have to call the function with 2 arguments, not 
more, and not less.  

Example  

This function expects 2 arguments, and gets 2 arguments:  

def my_function(fname, lname):  


print(fname + " " + lname)  
my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an 
error: 

​Example

This function expects 2 arguments, but gets only 1:  

def my_function(fname, lname):  


print(fname + " " + lname)  
my_function("Emil")  

Arbitrary Arguments, *args  

If you do not know how many arguments that will be passed into your function, add 
a ​* ​before the parameter name in the function definition.  

This way the function will receive a ​tuple o​ f arguments, and can access the items 
accordingly:  

Example  

If the number of arguments is unknown, add a ​* ​before the parameter name:  

def my_function(*kids):  
print("The youngest child is " + kids[2])  
my_function("Emil", "Tobias", "Linus")  

Arbitrary Arguments a​ re often shortened to ​*args i​ n Python documentations. 

Keyword Arguments  

​ ​value s​ yntax.  
You can also send arguments with the ​key =

This way the order of the arguments does not matter.  

Example  

def my_function(child3, child2, child1):  


print("The youngest child is " + child3)  
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
The phrase ​Keyword Arguments ​are often shortened to k​ wargs i​ n Python 

documentations. ​Arbitrary Keyword Arguments, **kwargs  

If you do not know how many keyword arguments that will be passed into your function, 
add two asterisk: ​** ​before the parameter name in the function definition.  

This way the function will receive a ​dictionary o​ f arguments, and can access the items 
accordingly:  

Example  

If the number of keyword arguments is unknown, add a double ​** ​before the parameter 
name:  

def my_function(**kid):  
print("His last name is " + kid["lname"])  
my_function(fname = "Tobias", lname = "Refsnes")  

Arbitrary Kword Arguments a​ re often shortened to ​**kwargs ​in Python documentations. 

Default Parameter Value  

The following example shows how to use a default parameter value. 

If we call the function without argument, it uses the default value:  

Example  

def my_function(​country = "Norway"​):  


print("I am from " + country)  
my_function("Sweden")  
my_function("India")  
my_function()  
my_function("Brazil")  

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list, dictionary 
etc.), and it will be treated as the same data type inside the function.  

E.g. if you send a List as an argument, it will still be a List when it reaches the 

function: ​Example  

def my_function(food):  
for x in food:  
print(x)  
fruits = ["apple", "banana", "cherry"]  
my_function(fruits)  
Return Values  

To let a function return a value, use the ​return ​statement:  

Example  

def my_function(x):  
​return 5 * x  
print(my_function(3))  
print(my_function(5))  
print(my_function(9))  

The pass Statement  

function ​definitions cannot be empty, but if you for some reason have a ​function ​definition 
with no content, put in the ​pass ​statement to avoid getting an error.  

Example  

def myfunction():  
pass  

Recursion  

Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function 
calls itself. This has the benefit of meaning that you can loop through data to reach a 
result.  

The developer should be very careful with recursion as it can be quite easy to slip into 
writing a function which never terminates, or one that uses excess amounts of memory or 
processor power. However, when written correctly recursion can be a very efficient and 
mathematically-elegant approach to programming.  

In this example, ​tri_recursion() ​is a function that we have defined to call itself ("recurse"). 
We use the ​k ​variable as the data, which decrements (​-1​) every time we recurse. The 
recursion ends when the condition is not greater than 0 (i.e. when it is 0).  

To a new developer it can take some time to work out how exactly this works, best way to 
find out is by testing and modifying it.  

Example  

Recursion Example  

def tri_recursion(k):  
if(k > 0):  
result = k + tri_recursion(k - 1)  
print(result)  
else:  
result = 0  
return result  
print("\n\nRecursion Example Results")  
tri_recursion(6) 
CHAPTER 7  

PYTHON- OBJECT ORIENTED 

LANGUAGE​ ​Python Classes/Objects  

Python is an object oriented programming language.  

Almost everything in Python is an object, with its properties and 

methods. A Class is like an object constructor, or a "blueprint" for 

creating objects. ​Create a Class  

To create a class, use the keyword ​class​:  

Example  

Create a class named MyClass, with a property named x:  

class MyClass:  
x = 5  

Create Object  

Now we can use the class named MyClass to create objects:  

Example  

Create an object named p1, and print the value of x:  

p1 = MyClass()  
print(p1.x)  

The __init__() Function  


The examples above are classes and objects in their simplest form, and are not really 
useful in real life applications.

To understand the meaning of classes we have to understand the built-in __init__() 


function.  

All classes have a function called __init__(), which is always executed when the class is 
being initiated.  

Use the __init__() function to assign values to object properties, or other operations that 
are necessary to do when the object is being created:  

Example  

Create a class named Person, use the __init__() function to assign values for name and 
age:  

class Person:  
def __init__(self, name, age):  
self.name = name  
self.age = age  

p1 = Person("John", 36)  

print(p1.name)  
print(p1.age)  

Note: ​The ​__init__()​ function is called automatically every time the class is being used to 
create a new object.  

Object Methods  

Objects can also contain methods. Methods in objects are functions that belong to the 
object.  

Let us create a method in the Person class:  


Example :- ​Insert a function that prints a greeting, and execute it on the p1 object: 

class Person:  
def __init__(self, name, age):  
self.name = name  
self.age = age  

def myfunc(self):  
print("Hello my name is " + self.name)  
p1 = Person("John", 36)  
p1.myfunc()  

Note: ​The self parameter is a reference to the current instance of the class, and is used to 
access variables that belong to the class.  

The self Parameter  

The ​self​ parameter is a reference to the current instance of the class, and is used to access 
variables that belongs to the class.  

It does not have to be named ​self​ , you can call it whatever you like, but it has to be the 
first parameter of any function in the class​:  

Example  

Use the words ​mysillyobject a​ nd ​abc ​instead of ​self​:  

class Person:  
def __init__(mysillyobject, name, age):  
mysillyobject.name = name  
mysillyobject.age = age  

def myfunc(abc):  
print("Hello my name is " + abc.name)  
p1 = Person("John", 36)  

p1.myfunc()

Modify Object Properties  

You can modify properties on objects like this:  

Example  

Set the age of p1 to 40:  

p1.age = 40  

Delete Object Properties  

You can delete properties on objects by using the ​del ​keyword:  

Example  

Delete the age property from the p1 object:  

del p1.age  

Delete Objects  

You can delete objects by using the ​del ​keyword:  

Example  

Delete the p1 object:  

del p1  

The pass Statement  

class ​definitions cannot be empty, but if you for some reason have a ​class d
​ efinition with
no content, put in the ​pass ​statement to avoid getting an error.

Example  

class Person:  

pass 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
CHAPTER 8  

LIBRARIES IN PYTHON  
NUMPY  
NumPy targets the ​CPython ​reference i​ mplementation ​of Python, which is a non
optimizing ​bytecode​ ​interpreter. Mathematical algorithms written for this version of Python
often run much slower than ​compiled​ ​equivalents. NumPy addresses the slowness
problem partly by providing multidimensional arrays and functions and operators that
operate efficiently on arrays, requiring rewriting some code, mostly ​inner loops​, using
NumPy.
Using NumPy in Python gives functionality comparable to ​MATLAB​ ​since they are both
interpreted,​[18]​ ​and they both allow the user to write fast programs as long as most
operations work on arrays or matrices instead of ​scalars​.

Example  

Array creation

>>> ​import ​numpy ​as ​np  


>>> ​x ​= ​np​.​array([​1​, 2
​ ​, ​3​])  
>>> ​x  
array([1, 2, 3])  
>>> ​y ​= ​np​.​arange(​10​) ​# like Python's list(range(10)), but returns an  
array  
>>> ​y  
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

PANDAS  
In ​computer programming​, ​pandas ​is a ​software library​ ​written for the ​Python
programming language​ ​for data manipulation and analysis. In particular, it offers data
structures and operations for manipulating numerical tables and ​time series​. It is ​free
​ ​The name is derived from the
software ​released under the ​three-clause BSD license​.[2]​
term "​panel data​", an ​econometrics ​term for data sets that include observations over
multiple time periods for the same individuals
Viewing and Inspecting Data

Now that you’ve loaded your data, it’s time to take a look. How does the data
frame look? Running the name of the data frame would give you the entire
table, but you can also get the first n rows with ​df.head(n) o
​ r the last n rows
with ​df.tail(n)​. ​df.shape w
​ ould give you the number of rows and columns.
df.info() ​would give you the index, datatype and memory information. The
command ​s.value_counts(dropna=False)​ w
​ ould allow you to view unique
values and counts for a series (like a column or a few columns). A very useful
command is ​df.describe() w
​ hich inputs summary statistics for numerical
columns. It is also possible to get ​statistics ​on the entire data frame or a
series (a column etc):

∙ ​df.mean()​Returns the mean of all columns

∙ ​df.corr()​Returns the correlation between columns in a data frame

∙ ​df.count()​Returns the number of non-null values in each data frame


column

∙ ​df.max()​Returns the highest value in each column

∙ ​df.min()​Returns the lowest value in each column

∙ ​df.median()​Returns the median of each column

∙ ​df.std()​Returns the standard deviation of each column

MATPLOTLIB  
Matplotlib ​is a ​plotting library​ ​for the ​Python​ ​programming language and its numerical
mathematics extension ​NumPy​. It provides an ​object-oriented​ A
​ PI​ ​for embedding plots
into applications using general-purpose ​GUI toolkits​ ​like ​Tkinter​, ​wxPython​, ​Qt​, or ​GTK+​.
There is also a ​procedural​ ​"pylab" interface based on a ​state machine​ ​(like ​OpenGL​),
designed to closely resemble that of ​MATLAB​, though its use is
discouraged.​[3]​ ​SciPy​ ​makes use of Matplotlib​.

Examples  


Line plot


Histogram


Scatter plot

Image plot


Scatter plot


Line plot

SEABORN  
Seaborn is a library for making statistical graphics in Python. It builds on top
of ​matplotlib ​and integrates closely with ​pandas ​data structures.

Seaborn helps you explore and understand your data. Its plotting functions operate on
dataframes and arrays containing whole datasets and internally perform the necessary
semantic mapping and statistical aggregation to produce informative plots. Its dataset
oriented, declarative API lets you focus on what the different elements of your plots
mean, rather than on the details of how to draw them

Here’s an example of what seaborn can do:


# Import seaborn
import ​seaborn ​as ​sns

# Apply the default theme


sns​.​set_theme()

# Load an example dataset


tips ​= ​sns​.​load_dataset(​"tips"​)

# Create a visualization
sns​.​relplot(
data​=​tips,
x​=​"total_bill"​, y​=​"tip"​, col​=​"time"​,
hue​=​"smoker"​, style​=​"smoker"​, size​=​"size"​,
)

Conclusion  

PYTHON is on demand availability of computer system resources, especially data storage 


and computing power, without direct active management by the user. Using python users 
are able to access software and application from wherever they need.It is a very powerful   
and complex tool, but it is built on a few core concepts. These concepts are recurring 
across Sales force products, documentationand customerservice and inform the user 
experience.  

REFERENCE   
https://www.tutorialspoint.com/python/python_basic_operators.ht
m​ ​https://www.w3schools.com/python/python_syntax.asp

You might also like