PYTHON Unit6
PYTHON Unit6
Programming
(MCACA1104)
DR.PRIYANKA YADAV
ASSISTANT PROFESSOR(FCE)
Unit 1
1. Introduction of unit
2. Installing and Working with Python
3. Understanding Python variables, Operators
4. Declaring and using Numeric data types: int, float,
complex
5. Using string data type and string operation
6. Defining List and list slicing
7. Use of Tuple data type
8. Conclusion of unit
What is Python
Python is a high-level, general-purpose, and very popular
programming language.
Python programming language is being used in web
development, Machine Learning applications, along with
all cutting-edge technology in Software Industry.
Python language is being used by almost all tech-giant
companies like – Google, Amazon, Facebook, Instagram,
Dropbox, Uber… etc.
It is a multipurpose programming language because it
can be used with web, enterprise, 3D CAD, etc.
Python makes development and debugging fast because
no compilation step is included in Python development,
and the edit-test-debug cycle is very fast.
Python Features
1) Easy to Learn and Use
Python is easy to learn as compared to other programming
languages. Its syntax is straightforward and much the same as
the English language.
2) GUI Programming Support: Python provides several GUI
frameworks, such as Tkinter and PyQt, allowing developers to
create desktop applications easily.
3) Interpreted Language
Python is an interpreted language; it means the Python program
is executed one line at a time. The advantage of being
interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows,
Linux, UNIX, and Macintosh, etc. So, we can say that Python is a
portable language.
5) Free and Open Source
Python is freely available for everyone. It is freely available on its
official website www.python.org. It has a large community across
the world that is dedicatedly working towards make new python
modules and functions. The open-source means, "Anyone can
download its source code without paying any penny."
6) Large Standard Library
It provides a vast range of libraries for the various fields such as
machine learning, web developers such as Tensor flow, Pandas,
Numpy, Keras, and Pytorch, etc.
Python Applications
Applications of python
Data Science: Data Science is a vast field, and Python is an
important language for this field because of its simplicity,
ease of use, and availability of powerful data analysis and
visualization libraries like NumPy, Pandas, and Matplotlib.
Desktop Applications: PyQt and Tkinter are useful libraries
that can be used in GUI - Graphical User Interface-based
Desktop Applications. There are better languages for this
field, but it can be used with other languages for making
Applications.
Console-based Applications: Python is also commonly used
to create command-line or console-based applications
because of its ease of use and support for advanced
features such as input/output redirection and piping.
Software Development: Python is considered one of the
best software-making languages. Python is easily
compatible with both from Small Scale to Large Scale
software.
Artificial Intelligence: AI is an emerging Technology, and
Python is a perfect language for artificial intelligence and
machine learning because of the availability of powerful
libraries such as TensorFlow, Keras, and PyTorch.
Web Applications: Python is commonly used in web
development on the backend with frameworks like Django
and Flask and on the front end with tools like JavaScript
and HTML.
Enterprise Applications: Python can be used to develop
large-scale enterprise applications with features such as
distributed computing, networking, and parallel processing.
3D CAD Applications: Python can be used for 3D
computer-aided design (CAD) applications through
libraries such as Blender.
Machine Learning: Python is widely used for machine
learning due to its simplicity, ease of use, and
availability of powerful machine learning libraries.
Computer Vision or Image Processing
Applications: Python can be used for computer vision
and image processing applications through powerful
libraries such as OpenCV and Scikit-image.
10
Google, Microsoft
Who Uses
Facebook, spotify
Python
NASA
Library of Congress
Click on the Add Path check box, it will set the Python
path automatically.
Customize installation
Step - 3 Installation in
Process
After the installation is complete, click Disable path length limit
and then Close. Disabling the path length limit means we can
use more than 260 characters in a file path.
Now go to windows and type IDLE.
This is Python Interpreter also called Python Shell. I printed Hello
geeks, python is working smoothly.
The three greater than >>> sign is called Python command
prompt, where we write our program and with a single enter key,
it will give result so instantly.
19
Interacting with Python Programs
Print
Statement
Elements separated
by commas print with a
space between them .
A comma at the end of
the statement (print
‘hello’,) will not print a
newline character.
Python Keywords
Keywords in Python are reserved words that can not
be used as a variable name, function name, or any
other identifier.
You'll get a message of SyntaxError if you attempt to
do the same.
Local Variable
Local variables are the variables that declared inside the function and
have scope within the function. Let's understand the following example.
Example -
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)
# Calling a function
add()
Output:
The sum is: 50
Global Variables
mainFunction()
print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Python Block
In Python, a block is a group of statements that are
indented together. Blocks are used to define the
scope of variables and to control the flow of
execution.
Python uses indentation to indicate a block of
code.
You have to use the same number of spaces in the
same block of code
if condition:
# This is another block of statements
# indented by four spaces
y = 20
print(y)
Rules for Python block
syntax
The most common way to comment out a block of code
in Python is using the # character. Any line of code starting
with # in Python is treated as a comment and gets ignored
by the compiler.
Statements in a block must be indented by the same
amount of space.
The scope of a variable in a block is limited to the block
itself.
Python Data Types
Numeric Data Type
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
x is of type: <class 'int'> print("z is of type:",type(z))
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
Explicit Type Conversion
num_string = '12'
num_integer = 23
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
result
Data type of num_string before Type Casting: <class 'str'>
Sum=35
Data type of num_sum: <class 'int'>
String Data Type
The sequence of characters in the quotation marks can be
used to describe the string.
A string can be defined in Python using single, double, or
triple quotes.
Example
print("Hello")
print('Hello')
Assign String to a Variable
Assigning a string to a variable is done with the variable name
followed by an equal sign and the string:
Example
a = "Hello"
print(a)
Accessing Characters in a String
Example:
str= 'Hello world'
print(str [1] ) # output is 'e'
print( str [-4] ) # output is 'r'
Reassigning Strings
str = "HELLO"
print(str)
str = "hello"
print(str)
Output:
HELLO
hello
String Operations
Operator Description
+ It is known as concatenation operator used to join the strings given either side of
the operator.
* It is known as repetition operator. It concatenates the multiple copies of the same
string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
[:] It is known as range slice operator. It is used to access the characters from the
specified range.
in It is known as membership operator. It returns if a particular sub-string is present in
the specified string.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need
to print the actual meaning of escape characters such as "C://python". To define any
string as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in
C programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.
Example
1.str = "Hello"
2.str1 = " world"
3.print(str*3) # prints HelloHelloHello
4.print(str+str1)# prints Hello world
5.print(str[4]) # prints o
6.print(str[2:4]); # prints ll
7.print('w' in str) # prints false as w is not present in str
8.print('wo' not in str1) # prints false as wo is present in str1.
9.print(r'C://python37') # prints C://python37 as it is written
10.print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
O
ll
False
False
C://python37
The string str : Hello
Python List
List in python is implemented to store the sequence of
various type of data. It uses square brackets [] to create a
list.
Python contains six data types that are capable to store
the sequences but the most common and reliable type is
list.
Example:
list1 = [1, "hi", "Python", 2]
#Printing the list1
print (list1)
Output:
[1, "hi", "Python", 2]
Indexing in Python List
Positive Indexes
In the case of Positive Indexing, the first element of the list has the index
number 0, and the last element of the list has the index number N-1,
where N is the total number of elements in the list (size of the list).
list= [50,70,30,20,90,10,50]
print(list[2])
print(list[5])
Output:
30
10
Negative Indexing
In negative indexing, the indexing of elements starts from the end of the
list. That is the last element of the list is said to be at a position at -1 and
the previous element at -2 and goes on till the first element.
Example:
list= [50,70,30,20,90,10,50]
print(list[-2])
print(list[-7])
Output:
10
50
List Slicing
As mentioned earlier list slicing in Python is a common practice and
can be used both with positive indexes as well as negative indexes. T
Syntax
Output:
[50, 70, 30, 20,90,10,50]
[70,20,10]
[50,90]
Tuple in Python
Python Tuple is a collection of objects separated by
commas.
In some ways, a tuple is similar to a Python list in
terms of indexing, nested objects, and repetition
but the main difference between both is Python
tuple is immutable, unlike the Python list which is
mutable.
Creating Python Tuples
To create a tuple we will use () operators.
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
Example
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
# Tuple slicing
print (tup[1:])
print (tup[0:1])
output
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Traceback (most recent call last): File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Python Operators
An operator is a symbol that usually represents an action or
process.
Operators required operands to perform their job.
Python divides the operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
Arithmetic Operators
Operator Description
/ (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
* (Multiplication) It is used to multiply one operand with the other. For example, if a
= 20, b = 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
-= 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.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Example
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('a=b:', a==b)
print('a+=b:', a+b)
print('a-=b:', a-b)
print('a*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a//=b:', a//b)
Output:
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
Bitwise Operators
Operator Description
& (binary and) A 1 is copied to the result if both bits in two operands at the same
location 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 xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (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 shift) The left operand is moved right by the number of bits present in the
right operand.
Example
a=5 # initialize the value of a
b=6 # initialize the value of b
print('a&b:', a&b)
print('a|b:', a|b)
print('a^b:', a^b)
print('~a:', ~a)
print('a<<b:', a<<b)
print('a>>b:', a>>b)
Output:
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0
Logical Operators
Operator Description
Example
x = ["Rose", "Lotus"]
print(' Is value Present?', "Rose" in x)
print(' Is value not Present?', "Riya" not in x)
Output
Is value Present? True
Is value not Present? True
Operator Precedence
Operator Description
** the exponent operator is given precedence.
~+- the minus, unary plus, and negation.
* / % // division of the floor, the modules, the division, multiplication.
+- Binary plus, and minus
>> << Left shift. and right shift
& Binary and.
^| Binary xor, and or
<= < > >= Comparison operators