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

PYTHON Unit6

Uploaded by

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

PYTHON Unit6

Uploaded by

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

Python

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

Instagram

Quora, cisco, Mozilla, Youtube


How to Install Python
 Python develops new versions with changes
periodically and releases them according to version
numbers. Python is currently at version 3.11.3.

 Visit the link https://www.python.org to download


the latest release of Python. In this process, we will
install Python 3.11.3 on our Windows operating
system.
Step - 1: Select the Python's version to download.
Click on the download button to download the exe file of
Python.
Step - 2: Click on the Install Now
Double-click the executable file, which is
downloaded.

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

My First Python Program


•Open a terminal window
and type “python”
•If on Windows open a
Python IDE like IDLE
•At the prompt type ‘hello
world!’
20

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.

False await else import pass


None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Python Identifiers
 Identifiers are the name given to variables, classes, methods, etc.
 Rules for writing Identifiers in Python
 The identifier is a combination of character digits and underscore
and the character includes letters in lowercase (a-z), letters in
uppercase (A-Z), digits (0-9), and an underscore (_).
 An identifier cannot begin with a digit. If an identifier starts with a
digit, it will give a Syntax error.
 In Python, keywords are the reserved names that are built-in to
Python, so a keyword cannot be used as an identifier - they have a
special meaning and we cannot use them as identifier names.
 Special symbols like !, @, #, $, %, etc. are not allowed in identifiers.
 Python identifiers cannot only contain digits.
 There is no restriction on the length of identifiers.
 Identifier names are case-sensitive.
Python Valid Identifiers Example
 abc123
 abc_de
 _abc
 ABC
 Abc
Python Invalid Identifiers Example
 123abc
 abc@
 123
 for
Python Variables
 Variable is a name that is used to refer to memory
location. Python variable is also known as an
identifier and used to hold value.
 Variable value can change later in the program.
 In Python, we don't need to specify the type of
variable because Python is a infer language and
smart enough to get variable type.
Declaring Variable and
Assigning Values
 Python does not bind us to declare a variable before using
it in the application. It allows us to create a variable at the
required time.
 When we assign any value to the variable, that variable is
declared automatically.
 The equal (=) operator is used to assign value to a
variable.
 In Python, variables are a symbolic name that is a
reference or pointer to an object. The variables are used
to denote objects by that name.
 Example: x = 5
y = "John"
print(x)
print(y)
 Output: 5
 John
a=50
b=a
The variable b refers to the same object that a points to because Python
does not create another object.
 Object Identity
In Python, every created object identifies uniquely in Python.The built-in id() function, is
used to identify the object identifier. Consider the following example.
a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a))
Output:
140734982691168
140734982691168
2822056960944
Get the Type

You can get the data type of a variable with


the type() function.
Example
x =5
y = "John"
print(type(x)) or type("john")
print(type(y))
<class ‘int’>
<class ‘str’>
Multiple assignments
 Many Values 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)
 One Value to Multiple Variables
you can assign the same value to multiple variables in
one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Python Variable Types

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

 Global variables can be used throughout the program, and


its scope is in the entire program. We can use global
variables inside or outside the function.
 A variable declared outside the function is the global
variable by default.
 Python provides the global keyword to use global variable
inside the function.
 If we don't use the global keyword, the function treats it as
a local variable.
 Let's understand the following example.
Example

# Declare a variable and initialize it


x = 101

# Global variable in function


def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Javatpoint'
print(x)

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

 Python Data Types are used to define the type of a variable.


 It defines what type of data we are going to store in a variable.
 Python numeric data types store numeric values.
 Python supports different numerical types −
 int (signed integers)
 float (floating point real values)
 complex (complex numbers)
Example:
a=1
b=5.6
c= 3.5j
 Python offers the type() function to determine a variable's
data type.
EXAMPLE:
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Type Conversion in Python
 Python defines type conversion functions to directly
convert one data type to another which is useful in
day-to-day and competitive programming.
There are two types of Type Conversion in Python:
 Implicit Type Conversion
 Explicit Type Conversion
Implicit Type Conversion
 In Implicit type conversion of data types in Python, the
Python interpreter automatically converts one data
type to another without any user involvement.

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

 the data type is manually changed by the user


as per their requirement. With explicit type
conversion, there is a risk of data loss since we
are forcing an expression to be changed in some
specific data type.
➢ We use the built-in functions like int(), float(), str(), etc to
perform explicit type conversion.
Example

 num_string = '12'
 num_integer = 23

 print("Data type of num_string before Type Casting:",type(num_string))

 # explicit type conversion


 num_string = int(num_string)

 print("Data type of num_string after Type Casting:",type(num_string))

 num_sum = num_integer + num_string

 print("Sum:",num_sum)
 print("Data type of num_sum:",type(num_sum))
result
Data type of num_string before Type Casting: <class 'str'>

Data type of num_string after Type Casting: <class 'int'>

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

 Each individual character in a string can be accessed using a


technique called indexing.
 The index of the first character (from left) in the string is 0 and
the last character is n-1 where n is the length of the string.

Example:
str= 'Hello world'
print(str [1] ) # output is 'e'
print( str [-4] ) # output is 'r'
Reassigning Strings

 Updating the content of the strings is as easy as


assigning it to a new string. The string object
doesn't support item assignment i.e., A string can
only be replaced with new string since its content
cannot be partially replaced. Strings are
immutable in Python.

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

List[Start : Stop : Stride]


Example
list= [50,70,30,20,90,10,50]
print(list[0:6])
print(list[1:6:2])
print(list[-1:-5:-2])

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

#Printing the tuple


print (tup)

# Tuple slicing
print (tup[1:])
print (tup[0:1])

# Tuple concatenation using + operator


print (tup + tup)

# Tuple repatation using * operator


print (tup * 3)

# Adding value to tup. It will throw an error.


t[2] = "hi"
)

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

+ (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

* (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

** (Exponent) As it calculates the first operand's power to the second operand, it


is an exponent operator.
// (Floor division) It provides the quotient's floor value, which is obtained by dividing
the two operands.
Example
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('Addition of two numbers:',a+b)
print('Subtraction of two numbers:',a-b)
print('Multiplication of two numbers:',a*b)
print('Division of two numbers:',a/b)
print('Reminder of two numbers:',a%b)
print('Exponent of two numbers:',a**b)
print('Floor division of two numbers:',a//b)
Output:
Addition of two numbers: 38
Subtraction of two numbers: 26
Multiplication of two numbers: 192
Division of two numbers: 5.333333333333333
Reminder of two numbers: 2
Exponent of two numbers: 1073741824
Floor division of two numbers: 5
Comparison Operator
Operator Description Example

If the values of two operands are equal, then


== (a == b) is not true.
the condition becomes true.

If values of two operands are not equal,


!=
then condition becomes true. a!=b is true

If the value of left operand is greater than the value


> (a > b) istrue.
of right operand, then condition becomestrue.

If the value of left operand is less than the value of


< (a < b) is not true.
right operand, then condition becomestrue.

If the value of left operand is greater than or equal to the (a >=


>=
value of right operand, then condition becomestrue. b) is true.

If the value of left operand is less than or equal to (a <=


<= the value of right operand, then condition becomes b) is not
true. true.
Example
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('Two numbers are equal or not:',a==b)
print('Two numbers are not equal or not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to b:',a>=b)
print('a is greater b:',a>b)
print('a is less than b:',a<b)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Two numbers are equal or not: False
Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False
Assignment Operators
Operator Description
= It assigns the value of the right expression to the left operand.
+= 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.
//= 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 Expression Example


When both
operands are True
and a>b and a>c
,result will be True
When both
operands are False
or a>b or a>c
result will be False

Invert the result


not not a>b
Example
a=5 # initialize the value of a
print(Is this statement true?:',a > 3 and a < 5)
print('Any one statement is true?:',a > 3 or a < 5)
print('Each statement is true then return False and vice-
versa:',(not(a > 3 and a < 5)))
Output:
Is this statement true?: False
Any one statement is true?: True
Each statement is true then return False and vice-versa: True
Identity Operators
Operator Description

is If the references on both sides point to the same


object, it is determined to be true.
is not If the references on both sides do not point at the
same object, it is determined to be true.
Example
a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
c=a
print(a is c)
print(a is not c)
print(a == b)
Output:
True
False
True
Membership Operators

Operator Description

in If the first operand cannot be found in the


second operand, it is evaluated to be true (list,
tuple, or dictionary).
not in If the first operand is not present in the second
operand, the evaluation is true (list, tuple, or
dictionary).

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

<> == != Equality operators.


= %= /= -= += Assignment operators
*=
is is not Identity operators
in not in Membership operators
not or and Logical operators
Example
a = 20 b = 10 c = 15 d = 5
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
e = (a + b) * (c / d); # (30) * (15/5)
print "Value of (a + b) * (c / d) is ", e
Output:
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Assignment
1. How is Python an interpreted language?
2. What type of language is python?
3. What is the difference between list and tuples in Python?
4. In some languages, every statement ends with a semi-colon (;).
What happens if you put a semi-colon at the end of a Python
statement?
5. Mention five benefits of using Python.
6. Write short notes with example: Elements of Python, Type
Conversion in Python, Operator Precedence
7. Write the Popular Applications Built Using Python and python
features.

You might also like