Saa Unit 4
Saa Unit 4
INTRODUCTION TO PYTHON:
What is Programming?
Programming is a way to “instruct the computer to perform various tasks”.
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991. He is fan of ‘Monty Pyhton’s Flying Circus’, this is a famous TV show in
Netherlands, so named after Monty Pyhton.
Python is an open-source, object-oriented and a high-level programming language for web
and app development. Also, it is used for software development, system scripting.
Mathematics.
Python over other programming languages:
Python has witnessed incredible growth from the past few years, mainly due to its simple
learning, versatility, and efficiency. It is a general-purpose language, designed specifically to
be simple to read and write. Furthermore, the language has become a universal platform for
various development requirements, and it offers a lot of options to the programmers in
general. Other than its easy to use and learn functionality, it offers a mature and supportive
python community, which guides developers in the right direction.
Features of Python:
• Easy to code: Python is a high-level programming language as it is easy to
comprehend as compared to other language like c, c#, Java script, Java and so
forth, one can effortlessly learn and code in python barely in hours.
Additionally, it is also a developer-friendly language.
• Platform Independent: Python programs can be developed and executed on
numerous operating system framework. Python can be used on Linux, Windows,
Macintosh, Solaris and some others.
• Object-Oriented Language: Python bolsters object-oriented language and
concepts of classes, objects encapsulation etc.
• Free and Open Source: Python language is freely available at the official
website. Since, it is open-source, available to the public. So one can download it,
use it as well as share it.
• GUI Programming Support: Graphical Users interfaces can be made using a
module such as PyQt5, PyQt4, wxPython or Tk in python.
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
Example
Syntax Error:
if 7 > 3:
print("Seven is greater than three!")
print("Seven is greater than three!")
Comments of Python:
Comments starts with a #, and Python will ignore them:
➢ Comments can be used to explain Python code.
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
Example:
print ("This is true.")
# This is false
When you run the above code, you will only see the output This is true. Everything else is
ignored.
Multiline Comments:
Example :
Note: Each line that starts with a hash mark will be ignored by the program. Another thing
you can do is use multiline strings by wrapping your comment inside a set of triple quotes:
Example:
Output:
Python keywords:
Python keywords are special reserved words that have specific meanings and purposes and
can’t be used for anything but those specific purposes. These keywords are always
available—you’ll never have to import them into your code.
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
Python keywords are different from Python’s built-in functions and types. The built-in
functions and types are also always available, but they aren’t as restrictive as the keywords in
their usage.
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
You can get the data type of any object by using the type() function:
Example 1:
Print the data type of the variable x:
Output:
Example 2 :
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
Output:
Variables in python:
A Python variable is a reserved memory location to store values. In other words, a variable in
a python program gives data to the computer for processing.
Example:
Legal Variable Names are.
Output:
Example:
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
OutPut:
➢ Python allows you to assign the same value to multiple variables in one line:
Exampe :
OutPut :
Output Variables:
➢ The Python print statement is often used to output variables.
➢ To combine both text and a variable, Python uses the + character.
➢ You can also use the + character to add a variable to another variable.
➢ For numbers, the + character works as a mathematical operator.
User Input
➢ Python allows for user input.
➢ The method is a bit different in Python 3.6 than Python 2.7.
➢ Python 3.6 uses the input() method.
Python operators:
Python operator is a symbol that performs an operation on one or more operands. An operand
is a variable or a value on which we perform the operation.
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
String Concatenation:
String Concatenation (ADDITION) is a very common operation in programming. Python
String Concatenation can be done using various ways. This session is aimed to explore
different ways to concatenate strings in a python program.
We can perform string concatenation in the following methods:
• Using + operator
• Using join () method
• Using % operator
• Using format () function
String concatenation using (+) operator
This is the simplest way of string concatenation. Let’s look at a simple example.
s1 = 'mallika'
s2 = 'gpt'
s3 = 'bantwal'
s4 = s1 + s2 + s3
print(s4)
Output: mallikagptbantwal
If-else in Python:
While writing code in any language, you will have to control the flow of your program. This
is generally the case when there is decision making involved - you will want to execute a
certain line of codes if a condition is satisfied, and a different set of code in case it is not. In
Python, you have the if, elif and the else statements for this purpose.
Simple if statement
if(condition):
indented Statement Block
The block of lines indented the same amount after the colon (:) will be executed whenever the
condition is TRUE.
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
The if-else statement is used to code the same way you would use it in the English language.
The syntax for the if-else statement is:
if(condition):
Indented statement block for when condition is TRUE
else:
Indented statement block for when condition is FALSE
if(Condition1):
Indented statement block for Condition1
elif(Condition2):
Indented statement block for Condition2
else:
Alternate statement block if all condition check above fails.
Loops in Python.
THE WHILE LOOP:
With the while loop we can execute a set of statements as long as a condition is true.
Print i as long as i is less than 8:
i=1
while i < 8:
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.
THE BREAK STATEMENT
With the break statement we can stop the loop even if the while condition is true:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
THE CONTINUE STATEMENT
With the continue statement we can stop the current iteration, and continue with the next:
i = 0
while i < 10:
i += 1
if i == 3:
continue
print(i)
With the else statement we can run a block of code once when the condition no longer is true:
i = 1
while i < 4:
print(i)
i += 1
else:
print("not satisfied")
• while loops
• for loops
➢ With the while loop we can execute a set of statements as long as a condition
is true.
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
OutPut:
To write the programme for finding sum of first 10 natural numbers, follow the following
steps:
Step 1: User must enter the number of natural numbers to find the sum of.
Step 2. The sum variable is initialized to 0.
Step 3. The while loop is used to find the sum of natural numbers and the number is
decremented for each iteration.
Step 4. The numbers are added to the sum variable and this continues till the value of the
variable is greater than 0.
Step 5. When the value of the variable becomes lesser than 0, the total sum of N natural
numbers is printed.
PYTHON LIBRARIES:
Normally, a library is a collection of books or is a room or place where many books are
stored to be used later. Similarly, in the programming world, a library is a collection of
precompiled codes that can be used later on in a program for some specific well-defined
operations. Other than pre-compiled codes, a library may contain documentation,
configuration data, message templates, classes, and values, etc.
A Python library is a collection of related modules. It contains bundles of code that can be
used repeatedly in different programs. It makes Python Programming simpler and
convenient for the programmer. As we don’t need to write the same code again and again
for different programs. Python libraries play a very vital role in fields of Machine Learning,
Data Science, Data Visualization, etc.
❖ Matplotlib
Matplotlib is a Python library that uses Python Script to write 2-dimensional graphs
and plots. Often mathematical or scientific applications require more than single axes
in a representation. This library helps us to build multiple plots at a time. However,
Matplotlib is used to manipulate different characteristics of figures as well.
❖ Numpy
Numpy is a popular array – processing package of Python. It provides good support
for different dimensional array objects as well as for matrices. Numpy is not only
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
confined to providing arrays only, but it also provides a variety of tools to manage
these arrays. It is fast, efficient, and really good for managing matrice and arrays.
❖ Scipy
Scipy is an open-source python library that is used for both scientific and technical
computation. It is a free python library. And very suitable for machine learning.
However, computation is not the only task that makes scipy special. It is also very
popular for image manipulation, as well.
❖ Pandas
❖ xlrd
xlrd is a library for reading data and formatting information from Excel files in the
historical .xlsx format. This library will no longer read anything other than .xlsx files.
For alternatives that read newer file formats, please see http://www.python-excel.org/.
❖ Openpyxl
It was born from lack of existing library to read/write natively from Python the Office
Open XML format.
Before the variables such as mean, mode, median and standard deviation of the data is found,
once has to learn how to import an excel file into python environment.
Pandas is the library which support for the analysis of the data
Path of the file has to be typed correctly with double backward slash.
Python Numpy:
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
➢ If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable. Furthermore, it avoids
repetition and makes the code reusable.
CALLING A FUNCTION.
def my_function():
print("Hello from a function")
my_function()
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
You can send any data types of argument to a function (string, number, list, dictionary etc.),
and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
def my_function(food):
for x in food:
print(x)
my_function(INDIAN FOOD)
RETURN VALUES:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.
def myfunction():
pass
RECURSION:
Python also accepts function recursion, which means a defined function can call itself.
The developer should be very careful with recursion as it can be quite easy to slip into writing
a function which never terminates, or one that uses excess amounts of memory or processor
power. However, when written correctly recursion can be a very efficient and
mathematically-elegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse").
We use the k variable as the data, which decrements (-1) every time we recurse. The
recursion ends when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to
find out is by testing and modifying it.
BASIC SCIENCES
STATISTICS AND ANALYTICS/ 20SC21P 2020-21
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
BASIC SCIENCES