Python Unit 1 & 2
Python Unit 1 & 2
Python
Introduction Python is a high-level, interpreted scripting language developed in the late
1980s by Guido van Rossum at the National Research Institute for Mathematics and
Computer Science in the Netherlands.
The initial version was published at the alt.sources news group in 1991, and version 1.0
was released in 1994.
Python 2.0 was released in 2000, and the 2.x versions were the prevalent releases until
December 2008.
At that time, the development team made the decision to release version 3.0, which
contained significant changes that were not backward compatible with the 2.x versions.
Features of Python
Python is interpreted:
Many languages are compiled, meaning the source code you create needs to be translated
into machine code (the language of computer‟s processor, before it can be run).
Programs written in an interpreted language are passed straight to an interpreter that runs
them directly.
This makes for a quicker development cycle because you just type in your code and run
it, without the intermediate compilation step.
One potential downside to interpreted languages is execution speed. Programs that are
compiled into the native language of the computer processor tend to run more quickly
than interpreted programs.
Python is Free:
The Python interpreter is developed under an OSI-approved open-source license, making
it free to install, use, and distribute, even for commercial purposes.
Python is Portable:
Because Python code is interpreted and not compiled into native machine instructions,
code written for one platform will work on any other platform that has the Python
interpreter installed.
Expressive Language:
Python language is more expressive means that it is more understandable and readable
Object-Oriented Language:
Python supports object oriented language and concepts of classes and objects come into
existence.
GUI Programming Support:
Large Standard Library: Python has a large and broad library and provides rich set of
module and functions for rapid application development
Programming cycle for Python
1. Python‟s programming cycle is dramatically shorter than that of traditional
programming cycle.
2. In Python, there are no compile or link steps.
3. Python programs simply import modules at runtime and use the objects
they contain. Because of this, Python programs run immediately after changes are made.
4. In cases where dynamic module reloading can be used, it is even possible
to change and reload parts of a running program without stopping it at all.
5. Python‟s impact on the programming cycle is as follows:
Since Python is interpreted, there is a rapid turnaround after program changes. And
because Python‟s parser is embedded in Python-based
systems, it is easy to modify programs at runtime.
Python IDEs
Integrated Development Environments (IDEs) are coding tools that make writing,
debugging, and testing your code easier. Many provide helpful features like code
completion, syntax highlighting, debugging tools, variable explorers, visualization tools,
and many other features.
Notebook platforms provide similar benefits to IDEs but are packaged in a different
format. Notebooks allow you to write code, view outputs, and add commentary in the
form of markdown. This approach to coding makes the code more readable and the
analysis more like a writeup that you and others can follow the logic of.
IDEs and notebook platforms are both great tools for data scientists to quickly write code
and analysis for data projects. There are a lot of great tools available. In this article, we
will cover 6 of the more common and best of these tools specifically with functionality
that benefits projects in data science. These tools emphasize easily importing data,
viewing large tables and variables, and viewing visualizations in an easily accessible
way.
JupyterLab Notebook & Jupyter Notebook
JupyterLab and Jupyter Notebook are two of the most popular free notebook software
for data science. They are both web-based tools. Jupyter Notebook is the original web
notebook application and is very beginner friendly with a simple document-centric
interface.
JupyterLab is the next iteration of this software. It provides an interactive and modular
development environment, making setting up a personalized workflow easy. You can use
JupyterLab for workflows in data science, scientific computing, computational
journalism, and machine learning.
Jupyter supports over 40 programming languages, including Python and R, and other data
languages like Julia and Scala. It is also very easy to install with a simple pip command,
and you can also try it on your browser before you install it.
Pros
Has support for over 40 programming languages.
Provides a lot of customizability features to personalize your workflow.
Cons
Requires you to download software.
Spyder
Spyder is a free and open-source environment developed for coding in Python. The tool
features some advanced editing, debugging, and profiling tools that make coding in
Python a lot easier and more efficient.
For example, the editor features autocomplete functionality, syntax highlighting,
horizontal and vertical splitting, and other coding efficiency tools. These all help make
the coding and debugging experience easier and more customizable. The tool also has
advanced features like a variable explorer, which allows you to see variables you have
created with your code, and an easy-to-use plots explorer to look at and save plots your
code has created.
Spyder also offers other plugins to extend the software‟s functionality, including a
notebook, a terminal, and testing software.
Pros
Has a lot of advanced features and interface customization available.
Completely free and open-source.
Has additional plugins to expand the functionality of the tool.
Cons
Only supports Python programming.
It‟s a little advanced for newer programmers.
Google Colab
Google Colaboratory is Google‟s cloud-based notebook environment. Colab is
integrated with the Google suite of products and is easy to get started with if you have a
Google account. You can import data into Colab notebooks from your Google Drive
account and from other sources like Github.
Colab is also very popular in the Machine learning community and allows you to
leverage Google‟s cloud hardware, including GPUs and TPUs, to run machine learning
code regardless of how powerful your own computer is. You can also share Colab
notebooks with others, similar to a Google doc file, making it easy to share your work. It
also supports over 40 programming languages, including Python, R, and Scala.
Pros
Has support for over 40 programming languages.
Free and easy to set up with a google account.
Gives you free access to Google hardware, so you don‟t have to rely on your own
machine‟s hardware for computationally demanding projects.
Easy to share code and collaborate.
Available online with no software installation.
Cons
Losing an internet connection or leaving a session running for too long can cause you to
lose progress on work and need to rerun the notebook (which can take a while for ML
and AI model training notebooks).
Hardware resources and power can be limited without a premium subscription.
How To Work with the Python Interactive Console
The Python interactive console (also called the Python interpreter or Python shell)
provides programmers with a quick way to execute commands and try out or test code
without creating a file.
Providing access to all of Python‟s built-in functions and any installed modules,
command history, and auto-completion, the interactive console offers the opportunity to
explore Python and the ability to paste code into programming files when you are ready.
Interacting with Python A program is a sequence of instructions that specifies how to
perform a Computation. The Computation might be mathematical or working with text.
To write and run Python program, we need to have Python interpreter installed in our
computer. IDLE (GUI integrated) is the standard, most popular Python development
environment.
IDLE is an acronym of Integrated Development and Learning Environment.
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
** x ** y Exponentiation
3. Integral Expressions: These are the kind of expressions that produce only integer
results after all computations and type conversions.
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
5. Relational Expressions: In these types of expressions, arithmetic expressions are
written on both sides of relational operator (> , < , >= , <=). Those arithmetic
expressions are evaluated first, and then compared as per relational operator and
produce a boolean output in the end. These expressions are also called Boolean
expressions.
6. Logical Expressions: These are kinds of expressions that result in
either True or False. It basically specifies one or more conditions. For example, (10 ==
9) is a condition if 10 is equal to 9. As we know it is not correct, so it will return False.
Studying logical expressions, we also come across some logical operators which can be
seen in logical expressions most often. Here are some logical operators in Python:
Assignment statement
An Assignment statement is a statement that is used to set a value to the variable name in a
program.
Assignment statement allows a variable to hold different types of values during its program
lifespan. Another way of understanding an assignment statement is, it stores a value in
the memory location which is denoted by a variable name.
Syntax
The symbol used in an assignment statement is called as an operator. The symbol is ‘=’.
Note: The Assignment Operator should never be used for Equality purpose which is double
equal sign „==‟.
The Basic Syntax of Assignment Statement in a programming language is :
variable = expression ;
where,
variable = variable name
expression = it could be either a direct value or a math expression/formula or a function call
Python Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication and division.
There are 7 arithmetic operators in Python :
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
6. Exponentiation
7. Floor division
1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values.
2. 2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract
the second value from the first value.
3. 3. Multiplication Operator : In Python, * is the multiplication operator. It is used to
find the product of 2 values.
4. 4. Division Operator : In Python, / is the division operator. It is used to find the
quotient when first operand is divided by the second.
5. 5. Modulus Operator : In Python, % is the modulus operator. It is used to find the
remainder when first operand is divided by the second.
6. 6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used
to raise the first operand to power of second.
7. 7. Floor division : In Python, // is used to conduct the floor division. It is used to find
the floor of the quotient when first operand is divided by the second.
What is operator precedence in Python
Operator precedence in Python simply refers to the order of operations. Operators are
used to perform operations on variables and values. Python always evaluates the left
operand before the right- even in function arguments. If you‟re reading about Python,
you sure have heard about BODMAS somewhere in your journey so far (mathematics,
school). In Python, however, we come across BEDMAS. The acronym stands for the
following words, which tell us which operator comes first:
B= Bracket
E = Exponentiation
D = Division
M = Multiplication
A = Addition
S = Subtraction
Through the acronym, we can see that the bracket/parenthesis operator comes before the
exponentiation operation in Python, according to the order of operations.
The same logic applies to each of the following operators, down to the subtraction
operator.
Example
To fully grasp BEDMAS and the order of preference of the operators, let‟s take a look at
the example below:
X = (5 + 3) * 2 ** 2
print(X)
From this program, we can see that there are three operators:
Bracket (B)
Exponentiation (E)
Multiplication (M)
According to operator precedence, Python first deals with the numbers in the bracket
operator (B): (5 + 3) = 8.
We then proceed to the exponentiation operator (E): 2 ** 2 = 4.
Finally, the results of both the bracket (8) and exponentiation (4) operators are then
executed using the multiplication operator (M): 8 * 4 = 32.
In short, Python followed the order of operators outlined in BEDMAS.
Understanding Boolean Logic in Python
Booleans are simple and easy to use concepts that exist in every programming
language. A boolean represents an idea of “true” or “false.” While writing an algorithm
or any program, there are often situations where we want to execute different code in
different situations. Booleans help our code to do just that easy and effective. More
often, a boolean value is returned as a result of some kind of comparison operations.
There are two Boolean keywords: True and False
Comparison Operators
Comparison operators are used to compare values. It returns either True or False after
computing the condition.
> Greater than – True if left operand is greater than the right x>y
< Less than – True if left operand is less than the right\\\ x < y
== Equal to – True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to – True if left operand is greater than or equal to the right
x >= y
<= Less than or equal to – True if left operand is less than or equal to the right
UNIT2
What are Conditional Statements in Python?
Conditional Statement in Python perform different computations or actions depending on
whether a specific Boolean constraint evaluates to true or false. Conditional statements
are handled by IF statements in Python.
In this tutorial, we will see how to apply conditional statements in Python.
What is Python If Statement?
Python if Statement is used for decision-making operations. It contains a body of code
which runs only when the condition given in the if statement is true. If the condition is
false, then the optional else statement runs which contains some code for the else
condition.
When you want to justify one condition while the other condition is not true, then you use
Python if else statement.
Python if Statement Syntax:
if expression
Statement
else
Statement
In python, decision making is performed by the following statements.
Statemen
Description
t
1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
4. if a>b and a>c:
5. print("a is largest");
6. if b>a and b>c:
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");
#!/usr/bin/env python3
Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3
choices for running the loops. The basic functionality of all the techniques is the same,
although the syntax and the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
The following sorts of loops are available in the Python programming language.
# iterate from i = 0 to i = 3
for i in values:
print(i)
for i in digits:
print(i)
else:
print("No items left.")
total = 0
counter = 0
print('Inside loop')
counter = counter + 1
else:
print('Inside else')