Python Unit1 Part1
Python Unit1 Part1
Unit 1
Introduction Python
Features in Python
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc.
3. Easy to Read
Learning Python is quite simple. Python‟s syntax is really straightforward. The code
block is defined by the indentations rather than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports
object-oriented language and concepts of classes, object encapsulation, etc.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need
to remember the system architecture, nor do we need to manage the memory.
7. Extensible feature
Python is an Extensible language. We can write some Python code into C or C++
language and also we can compile that code in C/C++ language.
8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify and
correct the majority of your program‟s issues once you understand how
to interpret Python‟s error traces.
APPLICATION OF PYTHON
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle
internet protocols such as HTML and XML, JSON, Email processing etc. One of
Python web-framework named Django is used on Instagram. Python provides many
frameworks, and these are given below:
Django and Pyramid framework(Use for heavy applications)
Flask and Bottle (Micro-framework)
Plone and Django CMS (Advance Content management)
3) Console-based Application
Console-based applications run from the command-line or shell. These applications
are computer program which are used commands to execute. Python provides many
free library or module which helps to build the command-line apps.
4) Software Development
Python is useful for the software development process. It works as a support
language and can be used to build control and management, testing, etc.
SCons is used to build control.
Buildbot and Apache Gumps are used for automated continuous compilation
and testing.
Round or Trac for bug tracking and project management.
Pandas, Scipy, Scikit-learn, etc. Few popular frameworks of machine libraries are
given below.
SciPy
Scikit-learn
NumPy
Pandas
Matplotlib
6) Business Applications
E-commerce and ERP are an example of a business application. This kind of
application requires extensively, scalability and readability, and Python provides all
these features.
Oddo is an example of the all-in-one Python-based application which offers a range of
business applications. Python provides a Tryton platform which is used to develop
the business application.
PYTHON VERSIONS
Python 1.0 January 1994 Functional programming tools(lambda, map, filter and reduce)
EOL-Jan 2020 Support for Unicode. Unification of data types and classes
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.
Python has two basic modes: script and interactive. The normal mode is the mode where
the scripted and finished .py files are run in the Python interpreter. Interactive mode is
a command line shell which gives immediate feedback for each statement, while running
previously fed statements in active memory. As new lines are fed into the interpreter, the
fed program is evaluated both in part and in whole.
Interactive mode is a good way to play around and try variations on syntax.
On macOS or linux, open a terminal and simply type "python". On Windows, bring up the
command prompt and type "py", or start an interactive Python session by selecting "Python
(command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI
which includes both an interactive mode and options to edit and run files.
Python Keywords
Keywords are predefined, reserved words used in Python programming that have special
meanings to the compiler. We cannot use a keyword as a variable name, function name, or
any other identifier. They are used to define the syntax and structure of the Python
language.
All the keywords except True, False and None are in lowercase and they must be written as
they are. The list of all the keywords is given below.
Python Identifiers
Identifiers are the name given to variables, classes, methods, etc. For example,
language = 'Python'.
Here, language is a variable (an identifier) which holds the value 'Python'.
We cannot use keywords as variable names as they are reserved names that are built-in to
Python. For example,
continue = 'Python'
The above code is wrong because we have used continue as a variable name.
It can have a sequence of letters and digits. However, it must begin with a letter
or _. The first letter of an identifier cannot be a digit.
It's a convention to start an identifier with a letter rather _.
Whitespaces are not allowed.
score @core
return_value return
name1 1name
Things to Remember
easier to figure out what it represents when you look at your code after a
long gap.
Multiple words can be separated using an underscore,
like this_is_a_long_variable.
Expression in Python?
Example :
x = 25 # a statement
x = x + 10 # an expression
print(x)
Output :
35
We have various types of expression in Python, let us discuss them along with
their respective examples.
1. Constant Expressions
Example :
x = 10 + 15
Output :
2. Arithmetic Expressions
x = 10
y=5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
Output :
3. Integral Expressions
Example :
x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the floating-point number into an integer or vice versa for
summation.
result = x + int(y)
Output :
4. Floating Expressions
Example :
x = 10 # an integer number
y = 5.0 # a floating point number
Output :
5. Relational Expressions
Example :
a = 25
b = 14
c = 48
d = 45
# The expression checks if the sum of (a and b) is the same as the difference of (c
and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)
Output :
6. Logical Expressions
Note :
In the table specified above, �x and �y can be values or another expression as
well.
Example :
x = (10 == 9)
y = (7 > 5)
and_result = x and y
or_result = x or y
not_x = not x
Output :
7. Bitwise Expressions
Example :
x = 25
left_shift = x << 1
right_shift = x >> 1
Output :
8. Combinational Expressions
Example :
x = 25
y = 35
result = x + (y << 1)
Output :
Result obtained: 95
Whenever there are multiple expressions involved then the expressions are
resolved based on their precedence or priority. Let us learn about the
precedence of various operators in the following section.
Variables
Python Variable is containers that store values. Python is not “statically typed”.
We do not need to declare variables before using them or declare their type. A
Python variable is a name given to a memory location.
Var = "Sapient"
print(Var)
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Output:
45
1456.8
John
Let‟s see how to declare the variable and print the variable.
Number = 100
# display
print( Number)
Output:
100
a = b = c = 10
print(a)
print(b)
print(c)
Output:
10
10
10
Python allows adding different values in a single line with “,” operators.
a, b, c = 1, 20.2, "Sapient"
print(a)
print(b)
print(c)
Output:
20.2
Sapient
Python Operators
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
Arithmetic Operators
Arithmetic operations between two operands are carried out using arithmetic
operators. It includes the exponent (**) operator as well as the + (addition), -
(subtraction), * (multiplication), / (divide), % (reminder), and // (floor division)
operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the
first operand is less than the second operand, the value results negative.
For example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b
(Multiplication) = 4 => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0
//(Floor It provides the quotient's floor value, which is obtained by dividing the
division) two operands.
Comparison operator
Comparison operators compare the values of the two operands and return a true
or false Boolean value in accordance. The following table lists the comparison
operators.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second
operand.
>= The condition is met if the first operand is greater than or equal to the second
operand.
> If the first operand is greater than the second operand, then the condition
becomes true.
< If the first operand is less than the second operand, then the condition becomes
true.
Assignment Operators
The right expression's value is assigned to the left operand using the
assignment operators. The following table provides a description of the
Operator Description
+= By multiplying the value of the right operand by the value of the left operand,
the left operand receives a changed value. For example, if a = 10, b = 20 =>
a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand
and assigns the modified value back to left operand. For example, if a = 20, b
= 10 => a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand
and assigns the modified value back to then the left operand. For example, if
a = 10, b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and
assigns the reminder back to the left operand. For example, if a = 20, b = 10
=> a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators.
Consider the case below.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same location
and) are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit
will be 1.
^ (binary If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the
next bit will be 1, and vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of
the value of the left operand.
>> (right The left operand is moved right by the number of bits present in the right
shift) operand.
Logical Operators
Operator Description
and The condition will also be true if the expression is true. If the two expressions
a and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators
The membership of a value inside a Python data structure can be verified using
Python membership operators. The result is true if the value is in the data
structure; otherwise, it returns false.
Operator Description
not in If the first operand is not present in the second operand, the evaluation is
true (list, tuple, or dictionary).
Operator Description
is not If the references on both sides do not point at the same object, it is
determined to be true.
Example: Solve
10 + 20 * 30
Code:
expr = 10 + 20 * 30
print(expr)
Output:
610
Code:
# Left-right associativity
# 100 / 10 * 10 is calculated as
print(100 / 10 * 10)
Output:
100
Please see the following precedence and associativity table for reference. This
table lists all operators from the highest precedence to the lowest precedence.
() Parentheses left-to-right
** Exponent right-to-left
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
or Logical OR left-to-right
= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
right-to-left
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
Data types
Data types are the classification or categorization of data [Link] following are the
standard or built-in data types in Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Binary Types( memory view, byte array, bytes)
Creating List :
Lists in Python can be created by just placing the sequence inside the square
brackets[].
Creating a Tuple
In Python, tuples are created by placing a sequence of values separated by a „comma‟
with or without the use of parentheses for grouping the data sequence. Tuples can
contain any number of elements and of any data type (like strings, integers, lists, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having
one element in the parentheses is not sufficient, there must be a trailing „comma‟ to
make it a tuple.
print(Tuple1)
Tuple1 = tuple('Geeks')
print(Tuple1)
defined
Set Data Type in Python
In Python, a Set is an unordered collection of data types that is iterable, mutable and
has no duplicate elements. The order of elements in a set is undefined though it may
consist of various elements.
# Creating a Set
set1 = set()
print(set1)
set1 = set("GeeksForGeeks")
print(set1)
Output:
Create a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly
{} braces, separated by „comma‟. Values in a dictionary can be of any datatype and can
be duplicated, whereas keys can‟t be repeated and must be immutable. The dictionary
can also be created by the built-in function dict(). An empty dictionary can be created
by just placing it in curly braces{}. Note – Dictionary keys are case sensitive, the same
name but different cases of Key will be treated distinctly.
Dict = {}
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Empty Dictionary:
{}
Python Indentation
Example
if 5 > 2:
print("Five is greater than two!")
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!"
Comments
Comments in Python are the lines in the code that are ignored by the interpreter
during the execution of the program. Comments enhance the readability of the code
and help the programmers to understand the code very carefully.
There are three types of comments in Python:
Single line Comments
Multiline Comments
Docstring Comments
# multiline comments
print("Multiline comments")
Docstring in Python
Python docstring is the string literals with triple quotes that are appeared right after
the function. It is used to associate documentation that has been written with Python
modules, functions, classes, and methods. It is added right below the functions,
modules, or classes to describe what they do. In Python, the docstring is then made
available via the __doc__ attribute.
Example:
return a*b
print(multiply.__doc__)
Output:
Multiplies the value of a and b
The interactive shell in Python is treated as a console. We can take the user
entered data the console using input() function.
Example
Output
If you run the above code, then you will get the following result.
Console Output
To print strings to console or echo some data to console output, use Python
inbuilt print() function.
print() function can take different type of values as argument(s), like string,
integer, float, etc., or object of a class type.
Hello World.
>>> print(10)
10
Type conversion is the transformation of a one type of data into another type
of data.
Implicit character data conversion is the term used in Python when a data type
conversion occurs whether during compilation or even during runtime. We do
not need to manually change the file format into some other type of data
because Python performs the implicit character data conversion
Without user input, the Programming language automatically changes one data
type to another in implicit shift of data types.
1. x = 20
2. print("x type:",type(x)
3. y = 0.6
4. print("y type:",type(y))
5. a=x+y
6. print(a)
7. print("z type:",type(z))
Output:
To change a number from a higher data type to a lower data type. Implicit type
conversion is ineffective in this situation, as we observed in the previous
section. Explicit type conversion, commonly referred to as type casting, now
steps in to save the day. Using built-in Language functions like str() to convert
to string form and int() to convert to integer type, a programmer can explicitly
change the data form of an object by changing it manually.
num_string = '12'
num_integer = 23
num_string = int(num_string)
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Run Code
Output
Python Libraries
Matplotlib
The plotting of numerical data is the responsibility of this library. It's for this
reason that it's used in analysis of data.
NumPy
Pandas
In the domain of data science, this well-known library is widely used. They're
mostly used for analysis, manipulation, and cleaning of data,
SciPy
Scikit- learn
Seaborn
Tens or Flow
Keras
Scrapy
Scrapy is a web scraping tool that scrapes multiple pages in under a minute.
Scrapy is also an open-source Python library framework for extracting data
from websites.
PyGame
This library provides a simple interface for the graphics, audio, and input
libraries of the Standard Direct media Library (SDL) which can work on any
platform. It's used to make video games with the Python programming
language and computer graphics and acoustic libraries.
PyBrain
PyBrain is a fast and simple machine learning library compared to the other
Python learning libraries. PyBrain is also an open-source library for ML
algorithms for every entry-level scholar in research from the available Python
libraries.
Statsmodels
Statsmodels is a Python library that helps with statistical model analysis and
estimation. The library is used to run statistical tests and other tasks, resulting
in high-quality results.
Importing Libraries
import module_name
When the import is used, it searches for the module initially in the local scope
by calling __import__() function. The value returned by the function is then
reflected in the output of the initial code.
import math
pie = [Link]
Output:
import module_name.member_name
In the above code module, math is imported, and its variables can be accessed
by considering it to be a class and pi as its object.
The value of pi is returned by __import__(). pi as a whole can be imported into
our initial code, rather than importing the whole module.
# pi directly.
print(pi)
Output:
3.141592653589793
In the above code module, math is not imported, rather just pi has been
imported as a variable. All the functions and constants can be imported using
*.
print(pi)
print(factorial(6))
Output
3.14159265359
720