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

Python Book

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

Python Book

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

Python Study Material with Programming

Fundamental:

Why is Programming Important


In this article, you will learn about why is programming important, what are its uses in
technology and how it impacts business and career. Programming is important for learning to
innovate, create eco-friendly solutions for global problems. Programming is important in our
daily life to enhance and increase the power of computers and the internet.

Programming is important for speeding up the input and output processes in a machine.
Programming is important to automate, collect, manage, calculate, analyze the processing of
data and information accurately.

Programming is important to create software and applications that help computer and mobile
users in daily life. Due to all these reasons, it’s really important to learn how to use
programming languages in our daily life.

Java, javascript, C#, C++, PHP, Python, Swift, SQL, Ruby, etc. programming languages are
the reasons behind the innovations in information technologies. If today we are seeing
robots, artificial intelligence, machine learning, bitcoins, the blockchain, IOT (Internet of
Things), Cloud Computing, etc. new technology and products in IT industry, then it’s
because of programming languages.

A programming language is a method to communicate with machines in a systematic format.


To understand programming languages first we need to start from programs.

What is a program?
A program is a group of logical, mathematical, systematical and managed functions grouped
together to perform a specific task. Just like there are various programs in the marriage such
as Shanti, Barat Prasthan, Lagan, vadhu pravesh, reception, dham etc.

What is a function?
Groups of classes are called a function. A function requires specific classes. For example, if
you want to create a function to play songs then you need to create specific classes under this
programs in which play, pause, stop and etc. are the classes. Now in a marriage example,
shanti program contains various function such as mama swagat, batna lepan, lok sangit, sehra
bandi are various functions inside the Shanti program. That’s why small and big functions
are important in a programming language to create software.

Language Types
Machine and assembly languages
A machine language consists of the numeric codes for the operations that a particular
computer can execute directly. The codes are strings of 0s and 1s, or binary digits (“bits”),
which are frequently converted both from and to hexadecimal (base 16) for human viewing
and modification. Machine language instructions typically use some bits to represent
operations, such as addition, and some to represent operands, or perhaps the location of the
next instruction. Machine language is difficult to read and write, since it does not resemble
conventional mathematical notation or human language, and its codes vary from computer to
computer.

Assembly language is one level above machine language. It uses short mnemonic codes for
instructions and allows the programmer to introduce names for blocks of memory that hold
data. One might thus write “add pay, total” instead of “0110101100101000” for an
instruction that adds two numbers. Assembly language is designed to be easily translated into
machine language. Although blocks of data may be referred to by name instead of by their
machine addresses, assembly language does not provide more sophisticated means of
organizing complex information.

Computers are a balanced mix of software and hardware. Hardware is just a piece of
mechanical device and its functions are being controlled by a compatible software.
Hardware understands instructions in the form of electronic charge, which is the counterpart
of binary language in software programming. Binary language has only two alphabets, 0
and 1. To instruct, the hardware codes must be written in binary format, which is simply a
series of 1s and 0s. It would be a difficult and cumbersome task for computer programmers
to write such codes, which is why we have compilers to write such codes.

Language Processing System


We have learnt that any computer system is made of hardware and software. The hardware
understands a language, which humans cannot understand. So we write programs in high-
level language, which is easier for us to understand and remember. These programs are then
fed into a series of tools and OS components to get the desired code that can be used by the
machine. This is known as Language Processing System.
The high-level language is converted into binary language in various phases. A compiler is
a program that converts high-level language to assembly language. Similarly,
an assembler is a program that converts the assembly language to machine-level language.
Let us first understand how a program, using C compiler, is executed on a host machine.
• User writes a program in C language (high-level language).
• The C compiler, compiles the program and translates it to assembly program (low-
level language).
• An assembler then translates the assembly program into machine code (object).
• A linker tool is used to link all the parts of the program together for execution
(executable machine code).
• A loader loads all of them into memory and then the program is executed.
Before diving straight into the concepts of compilers, we should understand a few other
tools that work closely with compilers.

Preprocessor
A preprocessor, generally considered as a part of compiler, is a tool that produces input for
compilers. It deals with macro-processing, augmentation, file inclusion, language extension,
etc.
Interpreter
An interpreter, like a compiler, translates high-level language into low-level machine
language. The difference lies in the way they read the source code or input. A compiler
reads the whole source code at once, creates tokens, checks semantics, generates
intermediate code, executes the whole program and may involve many passes. In contrast,
an interpreter reads a statement from the input, converts it to an intermediate code, executes
it, then takes the next statement in sequence. If an error occurs, an interpreter stops
execution and reports it. whereas a compiler reads the whole program even if it encounters
several errors.
Assembler
An assembler translates assembly language programs into machine code.The output of an
assembler is called an object file, which contains a combination of machine instructions as
well as the data required to place these instructions in memory.
Linker
Linker is a computer program that links and merges various object files together in order to
make an executable file. All these files might have been compiled by separate assemblers.
The major task of a linker is to search and locate referenced module/routines in a program
and to determine the memory location where these codes will be loaded, making the
program instruction to have absolute references.
Loader
Loader is a part of operating system and is responsible for loading executable files into
memory and execute them. It calculates the size of a program (instructions and data) and
creates memory space for it. It initializes various registers to initiate execution.
Cross-compiler
A compiler that runs on platform (A) and is capable of generating executable code for
platform (B) is called a cross-compiler.
Source-to-source Compiler
A compiler that takes the source code of one programming language and translates it into
the source code of another programming language is called a source-to-source compiler.
What is Software Testing?
Software testing is defined as an activity to check whether the actual results match the
expected results and to ensure that the software system is Defect free. It involves execution
of a software component or system component to evaluate one or more properties of interest.

Software testing also helps to identify errors, gaps or missing requirements in contrary to the
actual requirements. It can be either done manually or using automated tools. Some prefer
saying Software testing as a White Box and Black Box Testing.

Types of Testing:-

1. Unit Testing

It focuses on smallest unit of software design. In this we test an individual unit or group of
inter related units.It is often done by programmer by using sample input and observing its
corresponding outputs.

2. Integration Testing

The objective is to take unit tested components and build a program structure that has been
dictated by design.Integration testing is testing in which a group of components are
combined to produce output.

3. Regression Testing

Every time new module is added leads to changes in program. This type of testing make sure
that whole component works properly even after adding components to the complete
program.

4. Alpha Testing

This is a type of validation testing.It is a type of acceptance testing which is done before the
product is released to customers.

5. Beta Testing

The beta test is conducted at one or more customer sites by the end-user of the software. This
version is released for the limited number of users for testing in real time environment

6. System Testing

In this software is tested such that it works fine for different operating system.It is covered
under the black box testing technique. In this we just focus on required input and output
without focusing on internal working.
Debugging
Debugging, in computer programming and engineering, is a multistep process that involves
identifying a problem, isolating the source of the problem, and then either correcting the
problem or determining a way to work around it. The final step of debugging is to test the
correction or workaround and make sure it works.

The debugging process

In software development, debugging involves locating and correcting code errors in a


computer program. Debugging is part of the software testing process and is an integral part
of the entire software development lifecycle. The debugging process starts as soon as code is
written and continues in successive stages as code is combined with other units of
programming to form a software product. In a large program that has thousands and
thousands of lines of code, the debugging process can be made easier by using strategies
such as unit tests, code reviews and pair programming.

Documentation
In computer hardware and software product development, documentation is the information
that describes the product to its users. It consists of the product technical manuals and online
information (including online versions of the technical manuals and help facility
descriptions). The term is also sometimes used to mean the source information about the
product contained in design documents, detailed code comments, white papers, and
blackboard session notes.

The term is derived from the idea that engineers and programmers "document" their products
in formal writing. The earliest computer users were sometimes simply handed the engineers'
or programmers' "documentation." As the product audience grew, it became necessary to add
professional technical writers and editors to the process. Today, IBM and other companies
look at developing product information based on what users actually need to do when using
the product. In this task-oriented view, product information can be divided into and
sometimes physically organized into these task categories: evaluating, planning for, setting
up or installing, customizing, administering, using, and maintaining the product.

Definition of Algorithm
Problem-solving in terms of computers, what does it mean? We know that a computer can
solve any computational problem, but how does it work? Before solving a problem one
should always know what to do and how to do it, and what types of steps should be carried
out etcetera. Therefore, an algorithm is the series of steps that must be executed to solve a
problem.
Features of an Algorithm:
• As we know that an algorithm takes some inputs, execute some finite number of steps
and gives an output. So, the certain step involved in the algorithm must be executable.
• It must generate some result.
• After a specific period, it must cease to run.

Definition of Flowchart

We have discussed the term algorithm in the previous definition. Now, what is a flowchart?
It is nothing but a manner of representing an algorithm. It is also known as the flow diagram,
which illustrates a process or a detailed series of steps needed to produce a specific output. A
flow chart is comprised of the different symbols and control lines to connect those symbols.
Each symbol specifies distinct functions. It is extremely useful in programming because it
simplifies the complicated algorithm and converts it into the understandable pictorial
representation.

Construction of the Flow Chart:


The symbols used in the flowchart are described below.

• Rounded rectangle: Show the starting and ending point of the process.

• Rectangle: Illustrates a processing step.

• Diamond: Renders the decision point generally in the form of Yes/No or True/False.

• Control flow lines: Describes the flow and control of the data.
Parallelogram: Represents the Inputs given to the process or an Output generated by the
process.

Key Differences Between Algorithm and Flowchart-


1. An algorithm involves a combination of sequential steps to interpret the logic of the
solution. In contrast, a flowchart is the pictorial illustration of the algorithm.
2. A flow chart is more understandable as compared to the algorithm.
3. The algorithm is written in a language that can be perceived by humans. On the other
hand, the flowchart is made up using different shapes and symbols.
4. There are no stringent rules are implemented in the algorithms while the flowchart is
abode by predefined rules.
5. Errors and bugs are easily detected in the algorithm as compared to the flow charts.
6. Flow charts are simple to create. On the contrary, the construction of the algorithm is
complex.

Some Example of Flow Chart-

Flow Chart to add two numbers:


Flow Chart to convert temperature from Celsius to Fahrenheit-

Flow Chart to swap two numbers-


Flow Chart to check a number Even or Odd-

Flow chart to add a group of natural numbers-


Python Introduction
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.

It is used for:

• web development (server-side),


• software development,
• mathematics,
• system scripting.

What can Python do?


• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.

The Python programming language


The programming language you will learn is Python. Python is an example of a high-level
language; other high-level languages you might have heard of are C, C++, Perl, and Java.
There are also low-level languages, sometimes referred to as “machine languages” or
“assembly languages.” Loosely speaking, computers can only run programs written in
lowlevel languages. So programs written in a high-level language have to be processed
before they can run. This extra processing takes some time, which is a small disadvantage of
high-level languages. The advantages are enormous. First, it is much easier to program in a
high-level language. Programs written in a high-level language take less time to write, they
are shorter and easier to read, and they are more likely to be correct. Second, high-level
languages are portable, meaning that they can run on different kinds of computers with few
or no modifications. Low-level programs can run on only one kind of computer and have to
be rewritten to run on another.

An interpreter processes the program a little at a time, alternately reading lines


and performing computations.
A compiler translates source code into object code, which is run by a hardware
executor.
Due to these advantages, almost all programs are written in high-level languages. Lowlevel
languages are used only for a few specialized applications.
Two kinds of programs process high-level languages into low-level languages: interpreters
and compilers. An interpreter reads a high-level program and executes it, meaning that it
does what the program says. It processes the program a little at a time, alternately reading
lines and performing computations.

A compiler reads the program and translates it completely before the program starts running.
In this context, the high-level program is called the source code, and the translated program
is called the object code or the executable. Once a program is compiled, you can execute it
repeatedly without further translation.

Python is considered an interpreted language because Python programs are executed by an


interpreter. There are two ways to use the interpreter: interactive mode and script mode. In
interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you type
1 + 1, the interpreter replies 2.

Alternatively, you can store code in a file and use the interpreter to execute the contents of
the file, which is called a script. By convention, Python scripts have names that end with
.py.
To execute the script, you have to tell the interpreter the name of the file. If you have a script
named dinsdale.py and you are working in a UNIX command window, you type python
dinsdale.py.

Execute Python Syntax


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.

if 5 > 2:
print("Five is greater than two!")

Python Variables
In Python variables are created the moment you assign a value to it:
Variables in Python:
x =5
y = "Hello, World!"

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

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 _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Assign Value 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)

Global Variables
Variables that are created outside of a function (as in all of the examples above) are known
as global variables. Global variables can be used by everyone, both inside of functions and
outside.

Example
Create a variable outside of a function, and use it inside the function
x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can only be
used inside that function.

To create a global variable inside a function, you can use the global keyword.

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
Variable names and keywords

Programmers generally choose names for their variables that are meaningful—they
document what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters and numbers, but they
have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin
variable names with a lowercase letter.

The underscore character, _, can appear in a name. It is often used in names with multiple
words, such as my_name or airspeed_of_unladen_swallow.
If you give a variable an illegal name, you get a syntax error:

Available keywords in Python-

And del from not while


as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try

Python data types


Python data types are divided in two categories, mutable data types and immutable data
types.
Immutable Data types in Python
1. Numeric
2. String
3. Tuple
Mutable Data types in Python
1. List
2. Dictionary
3. Set

1. Numeric Data Type in Python


Integer – In Python 3, there is no upper bound on the integer number which means we can
have the value as large as our system memory allows.

# Integer number
num = 100
print(num)
print("Data Type of variable num is", type(num))
Long – Long data type is deprecated in Python 3 because there is no need for it, since the
integer has no upper limit, there is no point in having a data type that allows larger upper
limit than integers.

Float – Values with decimal points are the float values, there is no need to specify the data type in
Python. It is automatically inferred based on the value we are assigning to a variable. For example
here fnum is a float data type.

# float number
fnum = 34.45
print(fnum)
print("Data Type of variable fnum is", type(fnum))

Complex Number – Numbers with real and imaginary parts are known as complex numbers.
Unlike other programming language such as Java, Python is able to identify these complex
numbers with the values. In the following example when we print the type of the variable
cnum, it prints as complex number.

# complex number
cnum = 3 + 4j
print(cnum)
print("Data Type of variable cnum is", type(cnum))

Binary, Octal and Hexadecimal numbers


In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using
the prefixes.
0b(zero + ‘b’) and 0B(zero + ‘B’) – Binary Number
0o(zero + ‘o’) and 0O(zero + ‘O’) – Octal Number
0x(zero + ‘x’) and 0X(zero + ‘X’) – Hexadecimal Number

# integer equivalent of binary number 101


num = 0b101
print(num)

# integer equivalent of Octal number 32


num2 = 0o32
print(num2)

# integer equivalent of Hexadecimal number FF


num3 = 0xFF
print(num3)
2. Python Data Type – String
String is a sequence of characters in Python. The data type of String in Python is called “str”.

Strings in Python are either enclosed with single quotes or double quotes. In the following
example we have demonstrated two strings one with the double quotes and other string s2
with the single quotes. To read more about strings, refer this article: Python Strings.

# Python program to print strings and type

s = "This is a String"
s2 = 'This is also a String'

# displaying string s and its type


print(s)
print(type(s))

# displaying string s2 and its type


print(s2)
print(type(s2))

3. Python Data Type – Tuple


Tuple is immutable data type in Python which means it cannot be changed. It is an ordered
collection of elements enclosed in round brackets and separated by commas. To read more
about tuple, refer this tutorial: Python tuple.

# tuple of integers
t1 = (1, 2, 3, 4, 5)
# prints entire tuple
print(t1)

# tuple of strings
t2 = ("hi", "hello", "bye")
# loop through tuple elements
for s in t2:
print (s)

# tuple of mixed type elements


t3 = (2, "Lucy", 45, "Steve")
'''
Print a specific element
indexes start with zero
'''
print(t3[2])
4. Python Data Type – List
List is similar to tuple, it is also an ordered collection of elements, however list is a mutable
data type which means it can be changed unlike tuple which is an immutable data type.

A list is enclosed with square brackets and elements are separated by commas. To read more
about Lists, refer this guide: Python Lists

# list of integers
lis1 = (1, 2, 3, 4, 5)
# prints entire list
print(lis1)

# list of strings
lis2 = ("Apple", "Orange", "Banana")
# loop through tuple elements
for x in lis2:
print (x)

# List of mixed type elements


lis3 = (20, "Chaitanya", 15, "BeginnersBook")
'''
Print a specific element in list
indexes start with zero
'''
print("Element at index 3 is:",lis3[3])

5. Python Data Type – Dictionary


Dictionary is a collection of key and value pairs. A dictionary doesn’t allow duplicate keys
but the values can be duplicate. It is an ordered, indexed and mutable collection of elements.
To read more about it refer: Python dictionary.

The keys in a dictionary doesn’t necessarily to be a single data type, as you can see in the
following example that we have 1 integer key and two string keys.

# Dictionary example

dict = {1:"Chaitanya","lastname":"Singh", "age":31}

# prints the value where key value is 1


print(dict[1])
# prints the value where key value is "lastname"
print(dict["lastname"])
# prints the value where key value is "age"
print(dict["age"])
6. Python Data Type – Set
A set is an unordered and unindexed collection of items. This means when we print the
elements of a set they will appear in the random order and we cannot access the elements of
set based on indexes because it is unindexed.
Elements of set are separated by commas and enclosed in curly braces. Lets take an example
to understand the sets in Python.

# Set Example
myset = {"hi", 2, "bye", "Hello World"}

# loop through set


for a in myset:
print(a)

# checking whether 2 exists in myset


print(2 in myset)

# adding new element


myset.add(99)
print(myset)
Types of Operator
Python language supports the following types of operators.

• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic Operators

Comparison Operators
Assignment Operators

Bitwise Operators
Logical Operators

Membership Operators

Python If Statement
If statements are control flow statements which helps us to run a particular code only
when a certain condition is satisfied. For example, you want to print a message on the
screen only when a condition is true then you can use if statement to accomplish this in
programming.

Syntax of If statement in Python


The syntax of if statement in Python is pretty simple.

if condition:
block_of_code

Syntax of If-else statement in Python

The syntax of if statement in Python is pretty simple.


if condition:
block_of_code_1
else:
block_of_code_2

If statement flow diagram

If-else example in Python


num = 22
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Python If elif else statement
Syntax of if elif else statement in Python
This way we are checking multiple conditions.

if condition:
block_of_code_1
elif condition_2:
block_of_code_2
elif condition_3:
block_of_code_3
..
..
..
else:
block_of_code_n

1. There can be multiple ‘elif’ blocks, however there is only ‘else’ block is
allowed.
2. Out of all these blocks only one block_of_code gets executed. If the condition is
true then the code inside ‘if’ gets executed, if condition is false then the next
condition(associated with elif) is evaluated and so on. If none of the conditions
is true then the code inside ‘else’ gets executed.

Example

num = 1122
if 9 < num < 99:
print("Two digit number")
elif 99 < num < 999:
print("Three digit number")
elif 999 < num < 9999:
print("Four digit number")
else:
print("number is <= 9 or >= 9999")

Python Nested If else statement


Here we have a if statement inside another if..else statement block. Nesting control
statements makes us to check multiple conditions.

num = -99
if num > 0:
print("Positive Number")
else:
print("Negative Number")
#nested if
if -99<=num:
print("Two digit Negative Number")

Python for Loop


A loop is a used for iterating over a set of statements repeatedly. In Python we have
three types of loops for, while and do-while.
Syntax of For loop in Python
for <variable> in <sequence>:
# body_of_loop that has set of statements
# which requires repeated execution
Here <variable> is a variable that is used for iterating over a <sequence>. On every iteration
it takes the next value from <sequence> until the end of sequence is reached.

# Program to print squares of all numbers present in a list

# List of integer numbers


numbers = [1, 2, 4, 6, 11, 20]

# variable to store the square of each num temporary


sq = 0

# iterating over the given list


for val in numbers:
# calculating square of each number
sq = val * val
# displaying the squares
print(sq)

Function range()
In the above example, we have iterated over a list using for loop. However we can also use a
range() function in for loop to iterate over numbers defined by range().

range(n): generates a set of whole numbers starting from 0 to (n-1).


For example:
range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]

range(start, stop): generates a set of whole numbers starting from start to stop-1.
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]

range(start, stop, step_size): The default step_size is 1 which is why when we didn’t
specify the step_size, the numbers generated are having difference of 1. However by
specifying step_size we can generate numbers having the difference of step_size.
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]

Lets use the range() function in for loop:


Python for loop example using range() function
# Program to print the sum of first 5 natural numbers

# variable to store the sum


sum = 0

# iterating over natural numbers using range()


for val in range(1, 6):
# calculating sum
sum = sum + val

# displaying sum of first 5 natural numbers


print(sum)

For loop with else block


In Python we can have an optional ‘else’ block associated with the loop. The ‘else’ block
executes only when the loop has completed all the iterations. Lets take an example:

for val in range(5):


print(val)
else:
print("The loop has completed execution")

Nested For loop in Python


When a for loop is present inside another for loop then it is called a nested for loop. Lets take
an example of nested for loop.

for num1 in range(3):


for num2 in range(10, 14):
print(num1, ",", num2)

Python While Loop


While loop is used to iterate over a block of code repeatedly until a given condition
returns false. The main difference is that we use while loop when we are not certain of
the number of times the loop requires execution, on the other hand when we exactly
know how many times we need to run the loop, we use for loop.

Syntax of while loop


while condition:
#body_of_while
The body_of_while is set of Python statements which requires repeated execution. These set
of statements execute repeatedly until the given condition returns false.
Flow of while loop
1. First the given condition is checked, if the condition returns false, the loop is terminated
and the control jumps to the next statement in the program after the loop.
2. If the condition returns true, the set of statements inside loop are executed and then the
control jumps to the beginning of the loop for next iteration.

num = 1
# loop will repeat itself as long as
# num < 10 remains true
while num < 10:
print(num)
#incrementing the value of num
num = num + 3

Infinite while loop


Example 1:
This will print the word ‘hello’ indefinitely because the condition will always be true.

while True:
print("hello")
Example 2:

num = 1
while num<5:
print(num)
This will print ‘1’ indefinitely because inside loop we are not updating the value of num, so
the value of num will always remain 1 and the condition num < 5 will always return true.

Nested while loop in Python


When a while loop is present inside another while loop then it is called nested while loop.
Lets take an example to understand this concept.

i=1
j=5
while i < 4:
while j < 8:
print(i, ",", j)
j=j+1
i=i+1
while loop with else block
We can have a ‘else’ block associated with while loop. The ‘else’ block is optional. It
executes only after the loop finished execution.

num = 10
while num > 6:
print(num)
num = num-1
else:
print("loop is finished")

Python break Statement


The break statement is used to terminate the loop when a certain condition
is met. We already learned in previous tutorials (for loop and while loop)
that a loop is used to iterate a set of statements repeatedly as long as the loop
condition returns true. The break statement is generally used inside a loop
along with a if statement so that when a particular condition (defined in if
statement) returns true, the break statement is encountered and the loop
terminates.

Syntax of break statement in Python


The syntax of break statement in Python is similar to what we have seen in Java.
break
Example of break statement
In this example, we are searching a number ’88’ in the given list of numbers. The
requirement is to display all the numbers till the number ’88’ is found and when it is found,
terminate the loop and do not display the rest of the numbers.

# program to display all the elements before number 88


for num in [11, 9, 88, 10, 90, 3, 19]:
print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break
Python Continue Statement
The continue statement is used inside a loop to skip the rest of the statements in the body of
loop for the current iteration and jump to the beginning of the loop for next iteration.
The break and continue statements are used to alter the flow of loop, break terminates the
loop when a condition is met and continue skip the current iteration.

Syntax of continue statement in Python


The syntax of continue statement in Python is similar to what we have seen in Java(except
the semicolon)

Continue

Example of continue statement


Lets say we have a list of numbers and we want to print only the odd numbers out of that list.
We can do this by using continue statement.
We are skipping the print statement inside loop by using continue statement when the
number is even, this way all the even numbers are skipped and the print statement executed
for all the odd numbers.

# program to display only odd numbers


for num in [20, 11, 9, 66, 4, 89, 44]:
# Skipping the iteration when number is even
if num%2 == 0:
continue
# This statement will be skipped for all even numbers
print(num)

Python pass Statement


The pass statement acts as a placeholder and usually used when there is no need of
code but a statement is still required to make a code syntactically correct. For example
we want to declare a function in our code but we want to implement that function in
future, which means we are not yet ready to write the body of the function. In this case
we cannot leave the body of function empty as this would raise error because it is
syntactically incorrect, in such cases we can use pass statement which does
nothing but makes the code syntactically correct.

Python pass statement example


If the number is even we are doing nothing and if it is odd then we are displaying the
number.
for num in [20, 11, 9, 66, 4, 89, 44]:
if num%2 == 0:
pass
else:
print(num)

Python - Date & Time


A Python program can handle date and time in several ways. Converting between date
formats is a common chore for computers. Python's time and calendar modules help track
dates and times.

What is Tick?
Time intervals are floating-point numbers in units of seconds. Particular instants in time are
expressed in seconds since 12:00am, January 1, 1970(epoch).
There is a popular time module available in Python which provides functions for working
with times, and for converting between representations. The function time.time() returns the
current system time in ticks since 12:00am, January 1, 1970(epoch).
Example
import time; # This is required to include time module.

ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks

This would produce a result something as follows –

Number of ticks since 12:00am, January 1, 1970: 7186862.73399

What is TimeTuple?
Many of Python's time functions handle time as a tuple of 9 numbers, as shown below −
Getting current time
To translate a time instant from a seconds since the epoch floating-point value into a time-
tuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple
with all nine items valid.
import time;

localtime = time.localtime(time.time())
print "Local current time :", localtime

This would produce the following result, which could be formatted in any other
presentable form –

Local current time : time.struct_time(tm_year=2013, tm_mon=7,


tm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)

Getting formatted time


You can format any time as per your requirement, but simple method to get time in readable
format is asctime() −
import time;

localtime = time.asctime( time.localtime(time.time()) )


print "Local current time :", localtime

This would produce the following result –

Local current time : Tue Jan 13 10:17:09 2009

Getting calendar for a month


The calendar module gives a wide range of methods to play with yearly and monthly
calendars. Here, we print a calendar for a given month ( Jan 2008 ) −
import calendar

cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal

This would produce the following result –


Here is the calendar:
January 2008
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

Python - Functions
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can
also create your own functions. These functions are called user-defined functions.\

Why functions?

• It may not be clear why it is worth the trouble to divide a program into functions. There are
several reasons:
• Creating a new function gives you an opportunity to name a group of statements, which
makes your program easier to read and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if you make a
change, you only have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a time and then
assemble them into a working whole.
• Well-designed functions are often useful for many programs. Once you write and debug
one, you can reuse it.

Defining a Function
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
• Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.

def printme( str ):


"This prints a passed string into this function"
print str
return

Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in
the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following result –

I'm first call to user defined function!


Again second call to the same function

Pass by reference vs value


All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the
calling function. For example −
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values in the
same object. So, this would produce the following result –

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]


Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

Function Arguments
You can call a function by using the following types of formal arguments −

• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments

Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives
a syntax error as follows −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme(“Hello”)

Recursion

It is legal for one function to call another; it is also legal for a function to call itself. It may
not be obvious why that is a good thing, but it turns out to be one of the most magical things
a program can do. For example, look at the following function:

def countdown(n):
if n <= 0:
print 'Blastoff!'
else:
print n
countdown(n-1)

If n is 0 or negative, it outputs the word, “Blastoff!” Otherwise, it outputs n and then calls a
function named countdown—itself—passing n-1 as an argument.
What happens if we call this function like this?
>>> countdown(3)
The execution of countdown begins with n=3, and since n is greater than 0, it outputs the
value 3, and then calls itself...
As another example, we can write a function that prints a string n times.

def print_n(s, n):


if n <= 0:
return
print s
print_n(s, n-1)
If n <= 0 the return statement exits the function. The flow of execution immediately returns
to the caller, and the remaining lines of the function are not executed.
Python - Strings
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example –

var1 = 'Hello World!'


var2 = "Python Programming"

Accessing Values in Strings


Python does not support a character type; these are treated as strings of length one, thus also
considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring. For example −
var1 = 'Hello World!'
var2 = "Python Programming"

print "var1[0]: ", var1[0]


print "var2[1:5]: ", var2[1:5]

When the above code is executed, it produces the following result –

var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new
value can be related to its previous value or to a completely different string altogether. For
example −
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'

Escape Characters
Following table is a list of escape or non-printable characters that can be represented with
backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.

Backslash notation Description

\a Bell or alert

\b Backspace

\cx Control-x

\C-x Control-x

\e Escape

\f Formfeed

\M-\C-x Meta-Control-x

\n Newline

\nnn Octal notation, where n is in the range 0.7

\r Carriage return

\s Space
\t Tab

\v Vertical tab

\x Character x

\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

String Special Operators


Assume string variable a holds 'Hello' and variable b holds 'Python', then −

Operator Description Example

+ Concatenation - Adds values on either side of the operator a + b will give


HelloPython

* Repetition - Creates new strings, concatenating multiple copies a*2 will give -
of the same string HelloHello

[] Slice - Gives the character from the given index a[1] will give e

[:] Range Slice - Gives the characters from the given range a[1:4] will give ell

in Membership - Returns true if a character exists in the given H in a will give 1


string

not in Membership - Returns true if a character does not exist in the M not in a will give
given string 1

r/R Raw String - Suppresses actual meaning of Escape characters. print r'\n' prints \n
The syntax for raw strings is exactly the same as for normal and print R'\n'prints
strings with the exception of the raw string operator, the letter \n
"r," which precedes the quotation marks. The "r" can be
lowercase (r) or uppercase (R) and must be placed immediately
preceding the first quote mark.
% Format - Performs String formatting See at next section

Built-in String Methods


Python includes the following built-in methods to manipulate strings −

Sl.No. Methods with Description

1 capitalize()

Capitalizes first letter of string

2 center(width, fillchar)

Returns a space-padded string with the original string centered to a total of width columns.

3 count(str, beg= 0,end=len(string))

Counts how many times str occurs in string or in a substring of string if starting index beg and
ending index end are given.

4 decode(encoding='UTF-8',errors='strict')

Decodes the string using the codec registered for encoding. encoding defaults to the default string
encoding.

5 encode(encoding='UTF-8',errors='strict')

Returns encoded string version of string; on error, default is to raise a ValueError unless errors is
given with 'ignore' or 'replace'.

6 endswith(suffix, beg=0, end=len(string))

Determines if string or a substring of string (if starting index beg and ending index end are given)
ends with suffix; returns true if so and false otherwise.

7 expandtabs(tabsize=8)

Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.

8 find(str, beg=0 end=len(string))

Determine if str occurs in string or in a substring of string if starting index beg and ending index
end are given returns index if found and -1 otherwise.

9 index(str, beg=0, end=len(string))

Same as find(), but raises an exception if str not found.


10 isalnum()

Returns true if string has at least 1 character and all characters are alphanumeric and false
otherwise.

11 isalpha()

Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.

12 isdigit()

Returns true if string contains only digits and false otherwise.

13 islower()

Returns true if string has at least 1 cased character and all cased characters are in lowercase and
false otherwise.

14 isnumeric()

Returns true if a unicode string contains only numeric characters and false otherwise.

15 isspace()

Returns true if string contains only whitespace characters and false otherwise.

16 istitle()

Returns true if string is properly "titlecased" and false otherwise.

17 isupper()

Returns true if string has at least one cased character and all cased characters are in uppercase
and false otherwise.

18 join(seq)

Merges (concatenates) the string representations of elements in sequence seq into a string, with
separator string.

19 len(string)

Returns the length of the string

20 ljust(width[, fillchar])

Returns a space-padded string with the original string left-justified to a total of width columns.

21 lower()
Converts all uppercase letters in string to lowercase.

22 lstrip()

Removes all leading whitespace in string.

23 maketrans()

Returns a translation table to be used in translate function.

24 max(str)

Returns the max alphabetical character from the string str.

25 min(str)

Returns the min alphabetical character from the string str.

26 replace(old, new [, max])

Replaces all occurrences of old in string with new or at most max occurrences if max given.

27 rfind(str, beg=0,end=len(string))

Same as find(), but search backwards in string.

28 rindex( str, beg=0, end=len(string))

Same as index(), but search backwards in string.

29 rjust(width,[, fillchar])

Returns a space-padded string with the original string right-justified to a total of width columns.

30 rstrip()

Removes all trailing whitespace of string.

31 split(str="", num=string.count(str))

Splits string according to delimiter str (space if not provided) and returns list of substrings; split
into at most num substrings if given.

32 splitlines( num=string.count('\n'))

Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.

33 startswith(str, beg=0,end=len(string))

Determines if string or a substring of string (if starting index beg and ending index end are given)
starts with substring str; returns true if so and false otherwise.

34 strip([chars])

Performs both lstrip() and rstrip() on string.

35 swapcase()

Inverts case for all letters in string.

36 title()

Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are
lowercase.

37 translate(table, deletechars="")

Translates string according to translation table str(256 chars), removing those in the del string.

38 upper()

Converts lowercase letters in string to uppercase.

39 zfill (width)

Returns original string leftpadded with zeros to a total of width characters; intended for numbers,
zfill() retains any sign given (less one zero).

40 isdecimal()

Returns true if a unicode string contains only decimal characters and false otherwise.

Python - Lists
The most basic data structure in Python is the sequence. Each element of a sequence is
assigned a number - its position or index. The first index is zero, the second index is one,
and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples,
which we would see in this tutorial.
There are certain things you can do with all sequence types. These operations include
indexing, slicing, adding, multiplying, and checking for membership. In addition, Python
has built-in functions for finding the length of a sequence and for finding its largest and
smallest elements.
A list is a sequence

Like a string, a list is a sequence of values. In a string, the values are characters; in a list,
they can be any type. The values in a list are called elements or sometimes items. There are
several ways to create a new list; the simplest is to enclose the elements in square brackets ([
and ]):
[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
The first example is a list of four integers. The second is a list of three strings. The elements
of a list don’t have to be the same type. The following list contains a string, a float, an
integer, and (lo!) another list:
['spam', 2.0, 5, [10, 20]]

A list within another list is nested. A list that contains no elements is called an empty list;
you can create one with empty brackets, [].
As you might expect, you can assign list values to variables:

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']


>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []

Unlike strings, lists are mutable. When the bracket operator appears on the left side of an
assignment, it identifies the element of the list that will be assigned.

>>> numbers = [17, 123]


>>> numbers[1] = 5
>>> print numbers
[17, 5]
The one-eth element of numbers, which used to be 123, is now 5.

Python Lists
The list is a most versatile datatype available in Python which can be written as a list of
comma-separated values (items) between square brackets. Important thing about a list is that
items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square
brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so
on.
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or indices
to obtain value available at that index. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

When the above code is executed, it produces the following result –

list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side
of the assignment operator, and you can add to elements in a list with the append() method.
For example −
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
append() method is discussed in subsequent section.
When the above code is executed, it produces the following result −
Value available at index 2 :
1997
New value available at index 2 :
2001

Delete List Elements


To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know. For example −

list1 = ['physics', 'chemistry', 1997, 2000];


print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
When the above code is executed, it produces following result –

['physics', 'chemistry', 1997, 2000]


After deleting value at index 2 :
['physics', 'chemistry', 2000]

remove() method is discussed in subsequent section.

Basic List Operations


Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too,
except that the result is a new list, not a string.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

Indexing, Slicing, and Matrixes


Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.
Assuming following input −
L = ['spam', 'Spam', 'SPAM!']

Python Expression Results Description

L[2] SPAM! Offsets start at zero

L[-2] Spam Negative: count from the right


L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Built-in List Functions & Methods


Python includes the following list functions −

Sr.No. Function with Description

1 cmp(list1, list2)

Compares elements of both lists.

2 len(list)

Gives the total length of the list.

3 max(list)

Returns item from the list with max value.

4 min(list)

Returns item from the list with min value.

5 list(seq)

Converts a tuple into list.

Python includes following list methods

Sr.No. Methods with Description

1 list.append(obj)

Appends object obj to list

2 list.count(obj)

Returns count of how many times obj occurs in list

3 list.extend(seq)
Appends the contents of seq to list

4 list.index(obj)

Returns the lowest index in list that obj appears

5 list.insert(index, obj)

Inserts object obj into list at offset index

6 list.pop(obj=list[-1])

Removes and returns last object or obj from list

7 list.remove(obj)

Removes object obj from list

8 list.reverse()

Reverses objects of list in place

9 list.sort([func])

Sorts objects of list, use compare func if given

Python - Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples
use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you
can put these comma-separated values between parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing –

tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is
only one value –
tup1 = (50,);

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so
on.
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with the index or indices
to obtain value available at that index. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];

When the above code is executed, it produces the following result –

tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple
elements. You are able to take portions of existing tuples to create new tuples as the
following example demonstrates −
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# Following action is not valid for tuples


# tup1[0] = 100;

# So let's create a new tuple as follows


tup3 = tup1 + tup2;
print tup3;

When the above code is executed, it produces the following result –

(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing wrong with
putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example −
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;

This produces the following result. Note an exception raised, this is because after del
tup tuple does not exist any more –
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined

Basic Tuples Operations


Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the
prior chapter −

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

Indexing, Slicing, and Matrixes


Because tuples are sequences, indexing and slicing work the same way for tuples as they do
for strings. Assuming following input −
L = ('spam', 'Spam', 'SPAM!')
Python Expression Results Description

L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from the right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Built-in Tuple Functions


Python includes the following tuple functions −

Sr.No. Function with Description

1 cmp(tuple1, tuple2)

Compares elements of both tuples.

2 len(tuple)

Gives the total length of the tuple.

3 max(tuple)

Returns item from the tuple with max value.

4 min(tuple)

Returns item from the tuple with min value.

5 tuple(seq)

Converts a list into tuple.

Python - Dictionary
Each key is separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces. An empty dictionary without any items is
written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can
be of any type, but the keys must be of an immutable data type such as strings, numbers, or
tuples.
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along with the key
to obtain its value. Following is a simple example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result −
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an
error as follows −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following result −
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry as shown below in the simple example –

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']
When the above code is executed, it produces the following result −
dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements


You can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a simple
example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']
This produces the following result. Note that an exception is raised because after del
dict dictionary does not exist any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions −

Sr.No. Function with Description

1 cmp(dict1, dict2)

Compares elements of both dict.

2 len(dict)

Gives the total length of the dictionary. This would be equal to the number of items in the
dictionary.

3 str(dict)

Produces a printable string representation of a dictionary

4 type(variable)

Returns the type of the passed variable. If passed variable is dictionary, then it would return a
dictionary type.

Python includes following dictionary methods −

Sr.No. Methods with Description

1 dict.clear()

Removes all elements of dictionary dict


2 dict.copy()

Returns a shallow copy of dictionary dict

3 dict.fromkeys()

Create a new dictionary with keys from seq and values set to value.

4 dict.get(key, default=None)

For key key, returns value or default if key not in dictionary

5 dict.has_key(key)

Returns true if key in dictionary dict, false otherwise

6 dict.items()

Returns a list of dict's (key, value) tuple pairs

7 dict.keys()

Returns list of dictionary dict's keys

8 dict.setdefault(key, default=None)

Similar to get(), but will set dict[key]=default if key is not already in dict

9 dict.update(dict2)

Adds dictionary dict2's key-values pairs to dict

10 dict.values()

Returns list of dictionary dict's values

Python - Modules
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes
and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py.
Here's an example of a simple module, support.py
def print_func( par ):
print "Hello : ", par
return

The import Statement


You can use any Python source file as a module by executing an import statement in some
other Python source file. The import has the following syntax −
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches
before importing a module. For example, to import the module support.py, you need to put
the following command at the top of the script −
# Import module support
import support

# Now you can call defined function that module as follows


support.print_func("Zara")
When the above code is executed, it produces the following result −
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening over and over again if multiple imports
occur.

The from...import Statement


Python's from statement lets you import specific attributes from a module into the current
namespace. The from...import has the following syntax −
from modname import name1[, name2[, ... nameN]]
For example, to import the function fibonacci from the module fib, use the following
statement −
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just
introduces the item fibonacci from the module fib into the global symbol table of the
importing module.
Importing with from

Python provides two ways to import modules; we have already seen one:

>>> import math


>>> print math
<module 'math' (built-in)>
>>> print math.pi
3.14159265359

If you import math, you get a module object named math. The module object contains
constants like pi and functions like sin and exp.
But if you try to access pi directly, you get an error.

>>> print pi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined

As an alternative, you can import an object from a module like this:


>>> from math import pi
Now you can access pi directly, without dot notation.
>>> print pi
3.14159265359

Or you can use the star operator to import everything from the module:
>>> from math import *
>>> cos(pi)
-1.0

The from...import * Statement


It is also possible to import all names from a module into the current namespace by using
the following import statement −
from modname import *
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.

The globals() and locals() Functions


The globals() and locals() functions can be used to return the names in the global and local
namespaces depending on the location from where they are called.
If locals() is called from within a function, it will return all the names that can be accessed
locally from that function.
If globals() is called from within a function, it will return all the names that can be accessed
globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted
using the keys() function.

The reload() Function


When the module is imported into a script, the code in the top-level portion of a module is
executed only once.
Therefore, if you want to re-execute the top-level code in a module, you can use
the reload() function. The reload() function imports a previously imported module again.
The syntax of the reload() function is this −
reload(module_name)
Here, module_name is the name of the module you want to reload and not the string
containing the module name. For example, to reload hello module, do the following −
reload(hello)

File Handling in Python


What is a file?

File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).

Since, random access memory (RAM) is volatile which loses its data when computer is
turned off, we use files for future use of the data.

When we want to read from or write to a file we need to open it first. When we are done, it
needs to be closed, so that resources that are tied with the file are freed.

Hence, in Python, a file operation takes place in the following order.

1. Open a file
2. Read or write (perform operation)
3. Close the file

Python too supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. The concept of file handling
has stretched over various other languages, but the implementation is either complicated or
lengthy, but alike other concepts of Python, this concept here is also easy and short. Python
treats file differently as text or binary and this is important. Each line of code includes a
sequence of characters and they form text file. Each line of a file is terminated with a special
character, called the EOL or End of Line characters like comma {,} or newline character. It
ends the current line and tells the interpreter a new one has begun. Let’s start with Reading
and Writing files.
Working of open() function
We use open () function in Python to open a file in read or write mode. As explained above,
open ( ) will return a file object. To return a file object we use open() function along with
two arguments, that accepts file name and the mode, whether to read or write. So, the syntax
being: open(filename, mode).

Python File Modes

Mode Description

'r' Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates the file if it
'w' exists.

'x' Open a file for exclusive creation. If the file already exists, the operation fails.

Open for appending at the end of the file without truncating it. Creates a new file if it
'a' does not exist.

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)

How to open a file?


Python has a built-in function open() to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly.

>>> f = open("test.txt") # open file in current directory


>>> f = open("C:/Python/file.txt") # specifying full path

One must keep in mind that the mode argument is not mandatory. If not passed, then Python
will assume it to be “ r ” by default.

file = open('file.txt', 'r')


# This will print every line one by one in the file
for each in file:
print (each)
The open command will open the file in the read mode and the for loop will print each line
present in the file.
Working of read() mode
There is more than one way to read a file in Python. If you need to extract a string that
contains all characters in the file then we can use file.read(). The full code would work like
this:

# Python code to illustrate read() mode


file = open("file.text", "r")
print file.read()

Another way to read a file is to call a certain number of characters like in the following
code the interpreter will read the first five characters of stored data and return it as a
string:

# Python code to illustrate read() mode character wise


file = open("file.txt", "r")
print file.read(5)

Creating a file using write() mode


Let’s see how to create a file and how write mode works:
To manipulate the file, write the following in your Python environment:
# Python code to create a file
file = open('file.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

The close() command terminates all the resources in use and frees the system of this
particular program.
Working of append() mode
# Python code to illustrate append() mode
file = open('file.txt','a')
file.write("This will add this line")
file.close()

Using write along with with() function


We can also use write function along with with() function:
# Python code to illustrate with() alongwith write()
with open("file.txt", "w") as f:
f.write("Hello World!!!")

split() using file handling


We can also split lines using file handling in Python. This splits the variable when space is
encountered. You can also split using any characters as we wish. Here is the code:
# Python code to illustrate split() function
with open("file.text", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print word

Python File Methods


There are various methods available with the file object. Some of them have been used in above
examples.

Here is the complete list of methods in text mode with a brief description.

Method Description

close() Close an open file. It has no effect if the file is already closed.

Separate the underlying binary buffer from the TextIOBase and


detach() return it.

fileno() Return an integer number (file descriptor) of the file.

flush() Flush the write buffer of the file stream.

isatty() Return True if the file stream is interactive.

Read atmost n characters form the file. Reads till end of file if it is
read(n) negative or None.

readable() Returns True if the file stream can be read from.

Read and return one line from the file. Reads in at most n bytes if
readline(n=-1) specified.

Read and return a list of lines from the file. Reads in at


readlines(n=-1) most n bytes/characters if specified.

Change the file position to offset bytes, in reference to from (start,


seek(offset,from=SEEK_SET) current, end).

seekable() Returns True if the file stream supports random access.

tell() Returns the current file location.

Resize the file stream to size bytes. If size is not specified, resize to
truncate(size=None) current location.
writable() Returns True if the file stream can be written to.

Write string s to the file and return the number of characters


write(s) written.

writelines(lines) Write a list of lines to the file.

NumPy in Python
What is NumPy?
NumPy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays.
It is the fundamental package for scientific computing with Python. It contains various
features including these important ones:
• A powerful N-dimensional array object
• Sophisticated (broadcasting) functions
• Tools for integrating C/C++ and Fortran code
• Useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional
container of generic data.
Arbitrary data-types can be defined using Numpy which allows NumPy to seamlessly and
speedily integrate with a wide variety of databases.
Installation:

• Mac and Linux users can install NumPy via pip command:
pip install numpy
• Windows does not have any package manager analogous to that in linux or mac.
Please download the pre-built windows installer for NumPy from here (according to
your system configuration and Python version).
And then install the packages manually.

What is np.zeros and np.ones?


You can create a matrix full of zeroes or ones using np.zeros and np.one commands
respectively. It can be used when you initialized the weights during the first iteration in
TensorFlow and other statistic tasks.
Numpy Zero

numpy.zeros(shape, dtype=float, order='C')

Numpy Once

numpy.ones(shape, dtype=float, order='C')

Example numpy zero

import numpy as np
np.zeros((2,2))

Output:

array([[0., 0.],
[0., 0.]])

Numpy
Numpy is the most basic and a powerful package for working with data in python.

If you are going to work on data analysis or machine learning projects, then having a
solid understanding of numpy is nearly mandatory.

Because other packages for data analysis (like pandas) is built on top of numpy and the
scikit-learn package which is used to build machine learning applications works heavily
with numpy as well.

So what does numpy provide?

At the core, numpy provides the excellent ndarray objects, short for n -dimensional
arrays.

In a ‘ndarray’ object, aka ‘array’, you can store multiple items of the same data type. It
is the facilities around the array object that makes numpy so convenient for performing
math and data manipulations.

You might wonder, ‘I can store numbers and other objects in a python list itself and do
all sorts of computations and manipulations through list comprehensions, for -loops etc.
What do I need a numpy array for?’

Well, there are very significant advantages of using numpy arrays overs lists.

To understand this, let’s first see how to create a numpy array.


2. How to create a numpy array?
There are multiple ways to create a numpy array, most of which will be covered as you
read this. However one of the most common ways is to create one from a list or a list
like an object by passing it to the np.array function.

# Create an 1d array from a list

import numpy as np

list1 = [0,1,2,3,4]

arr1d = np.array(list1)

# Print the array and its type

print(type(arr1d))

arr1d

#> class 'numpy.ndarray'

#> array([0, 1, 2, 3, 4])

The key difference between an array and a list is, arrays are designed to handle
vectorized operations while a python list is not.

That means, if you apply a function it is performed on every item in the array, rather
than on the whole array object.

Let’s suppose you want to add the number 2 to every item in the list. The intuitive way
to do it is something like this:

list1 + 2 # error

That was not possible with a list. But you can do that on a ndarray.
# Add 2 to each element of arr1d

arr1d + 2

#> array([2, 3, 4, 5, 6])

Another characteristic is that, once a numpy array is created, you cannot increase its
size. To do so, you will have to create a new array. But such a behavior of extending
the size is natural in a list.

Nevertheless, there are so many more advantages. Let’s find out.

So, that’s about 1d array. You can also pass a list of lists to create a matrix like a 2d
array.

# Create a 2d array from a list of lists

list2 = [[0,1,2], [3,4,5], [6,7,8]]

arr2d = np.array(list2)

arr2d

#> array([[0, 1, 2],

#> [3, 4, 5],

#> [6, 7, 8]])

You may also specify the datatype by setting the dtype argument. Some of the most
commonly used numpy dtypes are: 'float' , 'int' , 'bool' , 'str' and 'object' .

To control the memory allocations you may choose to use one of ‘float32’, ‘float64’,
‘int8’, ‘int16’ or ‘int32’.

# Create a float 2d array


arr2d_f = np.array(list2, dtype='float')

arr2d_f

#> array([[ 0., 1., 2.],

#> [ 3., 4., 5.],

#> [ 6., 7., 8.]])

The decimal point after each number is indicative of the float datatype. You can also
convert it to a different datatype using the astype method.

# Convert to 'int' datatype

arr2d_f.astype('int')

#> array([[0, 1, 2],

#> [3, 4, 5],

#> [6, 7, 8]])

# Convert to int then to str datatype

arr2d_f.astype('int').astype('str')

#> array([['0', '1', '2'],

#> ['3', '4', '5'],

#> ['6', '7', '8']],

#> dtype='U21')

A numpy array must have all items to be of the same data type, unlike lists. This is
another significant difference.
However, if you are uncertain about what datatype your array will hold or if you want
to hold characters and numbers in the same array, you can set the dtype as 'object' .

# Create a boolean array

arr2d_b = np.array([1, 0, 10], dtype='bool')

arr2d_b

#> array([ True, False, True], dtype=bool)

# Create an object array to hold numbers as well as strings

arr1d_obj = np.array([1, 'a'], dtype='object')

arr1d_obj

#> array([1, 'a'], dtype=object)

Finally, you can always convert an array back to a python list using tolist() .

# Convert an array back to a list

arr1d_obj.tolist()

#> [1, 'a']

To summarise, the main differences with python lists are:

1. Arrays support vectorised operations, while lists don’t.


2. Once an array is created, you cannot change its size. You will have to create a new
array or overwrite the existing one.
3. Every array has one and only one dtype. All items in it should be of that dtype.
4. An equivalent numpy array occupies much less space than a python list of lists.

3. How to inspect the size and shape of a numpy array?


Every array has some properties I want to understand in order to know about the array.

Let’s consider the array, arr2d. Since it was created from a list of lists, it has 2
dimensions that can be shown as rows and columns, like in a matrix.

Had I created one from a list of list of lists, it would have 3 dimensions, as in a cu be.
And so on.

Let’s suppose you were handed a numpy vector that you didn’t create yourself. What
are the things you would want to explore in order to know about that array?

Well, I want to know:

<li>If it is a 1D or a 2D array or more. (ndim)</li>

<li>How many items are present in each dimension (shape)</li>

<li>What is its datatype (dtype)</li>

<li>What is the total number of items in it (size)</li>

<li>Samples of first few items in the array (through indexing)</li>

# Create a 2d array with 3 rows and 4 columns

list2 = [[1, 2, 3, 4],[3, 4, 5, 6], [5, 6, 7, 8]]

arr2 = np.array(list2, dtype='float')


arr2

#> array([[ 1., 2., 3., 4.],

#> [ 3., 4., 5., 6.],

#> [ 5., 6., 7., 8.]])

# shape

print('Shape: ', arr2.shape)

# dtype

print('Datatype: ', arr2.dtype)

# size

print('Size: ', arr2.size)

# ndim

print('Num Dimensions: ', arr2.ndim)

#> Shape: (3, 4)

#> Datatype: float64

#> Size: 12

#> Num Dimensions: 2


4. How to extract specific items from an array?
arr2

#> array([[ 1., 2., 3., 4.],

#> [ 3., 4., 5., 6.],

#> [ 5., 6., 7., 8.]])

You can extract specific portions on an array using indexing starting with 0, something
similar to how you would do with python lists.

But unlike lists, numpy arrays can optionally accept as many parameters in the square
brackets as there is number of dimensions.

# Extract the first 2 rows and columns

arr2[:2, :2]

list2[:2, :2] # error

#> array([[ 1., 2.],

#> [ 3., 4.]])

Additionally, numpy arrays support boolean indexing.

A boolean index array is of the same shape as the array-to-be-filtered and it contains
only True and False values. The values corresponding to True positions are retained in
the output.

# Get the boolean output by applying the condition to each element.

b = arr2 > 4

#> array([[False, False, False, False],

#> [False, False, True, True],


#> [ True, True, True, True]], dtype=bool)

arr2[b]

#> array([ 5., 6., 5., 6., 7., 8.])

4.1 How to reverse the rows and the whole array?


Reversing an array works like how you would do with lists, but you need to do for all
the axes (dimensions) if you want a complete reversal.

# Reverse only the row positions

arr2[::-1, ]

#> array([[ 5., 6., 7., 8.],

#> [ 3., 4., 5., 6.],

#> [ 1., 2., 3., 4.]])

# Reverse the row and column positions

arr2[::-1, ::-1]

#> array([[ 8., 7., 6., 5.],

#> [ 6., 5., 4., 3.],

#> [ 4., 3., 2., 1.]])

4.2 How to represent missing values and infinite?


Missing values can be represented using np.nan object, while np.inf represents infinite.
Let’s place some in arr2d.

# Insert a nan and an inf

arr2[1,1] = np.nan # not a number

arr2[1,2] = np.inf # infinite


arr2

#> array([[ 1., 2., 3., 4.],

#> [ 3., nan, inf, 6.],

#> [ 5., 6., 7., 8.]])

# Replace nan and inf with -1. Don't use arr2 == np.nan

missing_bool = np.isnan(arr2) | np.isinf(arr2)

arr2[missing_bool] = -1

arr2

#> array([[ 1., 2., 3., 4.],

#> [ 3., -1., -1., 6.],

#> [ 5., 6., 7., 8.]])

4.3 How to compute mean, min, max on the ndarray?


The ndarray has the respective methods to compute this for the whole array.

# mean, max and min

print("Mean value is: ", arr2.mean())

print("Max value is: ", arr2.max())

print("Min value is: ", arr2.min())

#> Mean value is: 3.58333333333

#> Max value is: 8.0

#> Min value is: -1.0

However, if you want to compute the minimum values row wise or column wise, use
the np.amin version instead.
# Row wise and column wise min

print("Column wise minimum: ", np.amin(arr2, axis=0))

print("Row wise minimum: ", np.amin(arr2, axis=1))

#> Column wise minimum: [ 1. -1. -1. 4.]

#> Row wise minimum: [ 1. -1. 5.]

Computing the minimum row-wise is fine. But what if you want to do some other
computation/function row-wise? It can be done using the np.apply_over_axis which
you will see in the upcoming topic.

# Cumulative Sum

np.cumsum(arr2)

#> array([ 1., 3., 6., 10., 13., 12., 11., 17., 22., 28., 35., 43.])

5. How to create a new array from an existing array?


If you just assign a portion of an array to another array, the new array you just created
actually refers to the parent array in memory.

That means, if you make any changes to the new array, it will reflect in the parent array
as well.

So to avoid disturbing the parent array, you need to make a copy of it using copy(). All
numpy arrays come with the copy() method.

# Assign portion of arr2 to arr2a. Doesn't really create a new array.

arr2a = arr2[:2,:2]

arr2a[:1, :1] = 100 # 100 will reflect in arr2

arr2

#> array([[ 100., 2., 3., 4.],


#> [ 3., -1., -1., 6.],

#> [ 5., 6., 7., 8.]])

# Copy portion of arr2 to arr2b

arr2b = arr2[:2, :2].copy()

arr2b[:1, :1] = 101 # 101 will not reflect in arr2

arr2

#> array([[ 100., 2., 3., 4.],

#> [ 3., -1., -1., 6.],

#> [ 5., 6., 7., 8.]])

6. Reshaping and Flattening Multidimensional arrays


Reshaping is changing the arrangement of items so that shape of the array changes
while maintaining the same number of dimensions.
Flattening, however, will convert a multi-dimensional array to a flat 1d array. And not
any other shape.

First, let’s reshape the arr2 array from 3×4 to 4×3 shape.

# Reshape a 3x4 array to 4x3 array

arr2.reshape(4, 3)

#> array([[ 100., 2., 3.],

#> [ 4., 3., -1.],

#> [ -1., 6., 5.],

#> [ 6., 7., 8.]])


6.1 What is the difference between flatten() and ravel()?
There are 2 popular ways to implement flattening. That is using the flatten() method
and the other using the ravel() method.

The difference between ravel and flatten is, the new array created using ravel is
actually a reference to the parent array. So, any changes to the new array will affect the
parent as well. But is memory efficient since it does not create a copy.

# Flatten it to a 1d array

arr2.flatten()

#> array([ 100., 2., 3., 4., 3., -1., -1., 6., 5., 6., 7., 8.])

# Changing the flattened array does not change parent

b1 = arr2.flatten()

b1[0] = 100 # changing b1 does not affect arr2

arr2

#> array([[ 100., 2., 3., 4.],

#> [ 3., -1., -1., 6.],

#> [ 5., 6., 7., 8.]])

# Changing the raveled array changes the parent also.

b2 = arr2.ravel()

b2[0] = 101 # changing b2 changes arr2 also

arr2

#> array([[ 101., 2., 3., 4.],

#> [ 3., -1., -1., 6.],

#> [ 5., 6., 7., 8.]])


7. How to create sequences, repetitions and random numbers
using numpy?
The np.arange function comes handy to create customised number sequences
as ndarray .

# Lower limit is 0 be default

print(np.arange(5))

# 0 to 9

print(np.arange(0, 10))

# 0 to 9 with step of 2

print(np.arange(0, 10, 2))

# 10 to 1, decreasing order

print(np.arange(10, 0, -1))

#> [0 1 2 3 4]

#> [0 1 2 3 4 5 6 7 8 9]

#> [0 2 4 6 8]

#> [10 9 8 7 6 5 4 3 2 1]

You can set the starting and end positions using np.arange. But if you are focussed on
the number of items in the array you will have to manually calculate the appropriate
step value.

Say, you want to create an array of exactly 10 numbers between 1 and 50, Can you
compute what would be the step value?

Well, I am going to use the np.linspace instead.


# Start at 1 and end at 50

np.linspace(start=1, stop=50, num=10, dtype=int)

#> array([ 1, 6, 11, 17, 22, 28, 33, 39, 44, 50])

Notice since I explicitly forced the dtype to be int, the numbers are not equally spaced
because of the rounding.
Similar to np.linspace, there is also np.logspace which rises in a logarithmic scale. In
np.logspace, the given start value is actually base^start and ends with base^stop, with a
default based value of 10.
# Limit the number of digits after the decimal to 2
np.set_printoptions(precision=2)

# Start at 10^1 and end at 10^50

np.logspace(start=1, stop=50, num=10, base=10)

#> array([ 1.00e+01, 2.78e+06, 7.74e+11, 2.15e+17, 5.99e+22,

#> 1.67e+28, 4.64e+33, 1.29e+39, 3.59e+44, 1.00e+50])

The np.zeros and np.ones functions lets you create arrays of desired shape where all
the items are either 0’s or 1’s.

np.zeros([2,2])

#> array([[ 0., 0.],

#> [ 0., 0.]])

np.ones([2,2])

#> array([[ 1., 1.],

#> [ 1., 1.]])


7.1 How to create repeating sequences?
np.tile will repeat a whole list or array n times. Whereas, np.repeat repeats each item
n times.

a = [1,2,3]

# Repeat whole of 'a' two times

print('Tile: ', np.tile(a, 2))

# Repeat each element of 'a' two times

print('Repeat: ', np.repeat(a, 2))

#> Tile: [1 2 3 1 2 3]

#> Repeat: [1 1 2 2 3 3]

7.2 How to generate random numbers?


The random module provides nice functions to generate random numbers (and also
statistical distributions) of any given shape.

# Random numbers between [0,1) of shape 2,2

print(np.random.rand(2,2))

# Normal distribution with mean=0 and variance=1 of shape 2,2

print(np.random.randn(2,2))

# Random integers between [0, 10) of shape 2,2

print(np.random.randint(0, 10, size=[2,2]))

# One random number between [0,1)

print(np.random.random())

# Random numbers between [0,1) of shape 2,2


print(np.random.random(size=[2,2]))

# Pick 10 items from a given list, with equal probability

print(np.random.choice(['a', 'e', 'i', 'o', 'u'], size=10))

# Pick 10 items from a given list with a predefined probability 'p'

print(np.random.choice(['a', 'e', 'i', 'o', 'u'], size=10, p=[0.3, .1, 0.1, 0.4, 0.1])) # picks more
o's

#> [[ 0.84 0.7 ]

#> [ 0.52 0.8 ]]

#> [[-0.06 -1.55]

#> [ 0.47 -0.04]]

#> [[4 0]

#> [8 7]]

#> 0.08737272424956832

#> [[ 0.45 0.78]

#> [ 0.03 0.74]]

#> ['i' 'a' 'e' 'e' 'a' 'u' 'o' 'e' 'i' 'u']

#> ['o' 'a' 'e' 'a' 'a' 'o' 'o' 'o' 'a' 'o']

Now, everytime you run any of the above functions, you get a different set of random
numbers.

If you want to repeat the same set of random numbers every time, you need to set the
seed or the random state. The see can be any value. The only requirement is you must
set the seed to the same value every time you want to generate the same set of random
numbers.

Once np.random.RandomState is created, all the functions of the np.random module


becomes available to the created randomstate object.
# Create the random state

rn = np.random.RandomState(100)

# Create random numbers between [0,1) of shape 2,2

print(rn.rand(2,2))

#> [[ 0.54 0.28]

#> [ 0.42 0.84]]

# Set the random seed

np.random.seed(100)

# Create random numbers between [0,1) of shape 2,2

print(np.random.rand(2,2))

#> [[ 0.54 0.28]

#> [ 0.42 0.84]]

7.3 How to get the unique items and the counts?


The np.unique method can be used to get the unique items. If you want the repetition
counts of each item, set the return_counts parameter to True.

# Create random integers of size 10 between [0,10)

np.random.seed(100)

arr_rand = np.random.randint(0, 10, size=10)

print(arr_rand)

#> [8 8 3 7 7 0 4 2 5 2]

# Get the unique items and their counts


uniqs, counts = np.unique(arr_rand, return_counts=True)

print("Unique items : ", uniqs)

print("Counts : ", counts)

#> Unique items : [0 2 3 4 5 7 8]

#> Counts : [1 2 1 1 1 2 2]

You might also like