[Go to site: main page, start]

0% found this document useful (0 votes)
25 views91 pages

Unit 1 PythonIntroduction

Python is a versatile, high-level programming language that supports multiple programming paradigms and is known for its clear syntax and ease of use. The language was named after the BBC comedy series 'Monty Python's Flying Circus' and has evolved through various versions, with Python 3 introducing significant changes over Python 2. Key features include dynamic typing, garbage collection, cross-platform compatibility, and a rich standard library, making it suitable for a wide range of applications.

Uploaded by

rajatmaurya7906
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views91 pages

Unit 1 PythonIntroduction

Python is a versatile, high-level programming language that supports multiple programming paradigms and is known for its clear syntax and ease of use. The language was named after the BBC comedy series 'Monty Python's Flying Circus' and has evolved through various versions, with Python 3 introducing significant changes over Python 2. Key features include dynamic typing, garbage collection, cross-platform compatibility, and a rich standard library, making it suitable for a wide range of applications.

Uploaded by

rajatmaurya7906
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

What is Python ?
Python is a general-purpose, dynamically typed, high-level, compiled and
interpreted, garbage-collected, and purely object-oriented programming
language that supports procedural, object-oriented, and functional
programming.

Why the Name Python?


There is a fact behind choosing the name Python. Guido van Rossum was
reading the script of a popular BBC comedy series "Monty Python's Flying
Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit
mysterious. So he decided to select naming Python after the "Monty Python's
Flying Circus" for their newly created programming language.
History of Python

• Python is derived from many other languages, including ABC,


Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and
other scripting languages.
Python 2 vs python 3
Python 2 Python 3
>>7 / 5 >>7/5
Results: 1 Results: 1.4
print “message” print (“Message”)
Xrange Range
Exception alias mentioned with , Alias mentioned with ‘as’
except NameError, err: except NameError as err:
In order to suppress a newline while printing, you in Python 3, you have to use the end
had to use a trailing comma in Python 2. keyword argument.
print 2, print 4 print(2, end =" ") print(4)
24 24
In Python 2, both != and <> used to work perfectly in python 3, the alternative of <> has been
fine as inequality operators. completely removed. Basically now there
is only one way of doing it. By using the !=
operator.
raw_input(), input both supported, The difference Python 3, the raw input() has been
was that, input() was able to read and store any removed. There is only the input() method
data type and store it as the same type. In order to and it parses the user input as string for
store every input as a string, you had to use every data type.
raw_input()
Python
• Python is a general-purpose language.
• Python is a Scripting Language
• Scripting language are written using high level
language constructs, which makes them easy to learn.
• It has wide range of applications from Web
development, scientific and mathematical computing
to desktop graphical user Interfaces.
• The syntax of the language is clean and length of the
code is relatively short.
• Python is Interactive − You can actually sit at a Python
prompt and interact with the interpreter directly to
write your programs.
Python Programming Cycle
• Relatively shorter than other language.
• There is no compile or link step while it is in
built step.
• Python interpreter internally does the
compilation
• Python program simply imports library at run
time and uses the objects.
Features of python
• Easy to use and Read - Python's syntax is clear and easy to read, making it
an ideal language for both beginners and experienced programmers. This
simplicity can lead to faster development and reduce the chances of
errors.
Example: print(“hello”)
• Dynamically Typed - The data types of variables are determined during
run-time. We do not need to specify the data type of a variable during
writing codes.
Example : x=10 print(x)
• High-level - High-level language means human readable code.
• Compiled and Interpreted - Python code first gets compiled into
bytecode, and then interpreted line by line. When we download the
Python in our system form org we download the default implementation
of Python known as CPython. CPython is considered to be Compiled and
Interpreted both.
Features of python
• Garbage Collected - Memory allocation and deallocation are
automatically managed. Programmers do not specifically need to
manage the memory.
• Purely Object-Oriented - It refers to everything as an object, including
numbers and strings.
• Cross-platform Compatibility - Python can be easily installed on
Windows, macOS, and various Linux distributions, allowing developers
to create software that runs across different operating systems.
• Rich Standard Library - Python comes with several standard libraries
that provide ready-to-use modules and functions for various tasks,
ranging from web development and data manipulation to machine
learning and networking.
• Open Source - Python is an open-source, cost-free programming
language. It is utilized in several sectors and disciplines as a result
Internal working of Python
Python directly doesn’t convert its code into machine code,
something that hardware can understand. It converts it into
something called bytecode. So within Python, compilation happens,
but it’s just not in a machine language. It is into byte code (.pyc or
.pyo) and this byte code can’t be understood by the CPU. So we need
an interpreter called the Python virtual machine to execute the byte
codes.

IDEs
Pycharm, Jupyter Notebook, Enthought Canopy, IDLE, Spyder
First Python Program
• The Python language has many similarities to Perl, C, and Java.
However, there are some definite differences between the
languages.

>>> print ("Hello, Python!" )


Hello, Python!

# Add two numbers


num1 = 3
num2 = 5
sum = num1+num2
print(sum)
Using input() function
• Reads data from user
• Parameter is optional string message/ expression
• Returns the data input as string representation

Using print() function


• The print() function in Python is used to display text or
any object to the console or standard output.

Example-

name = input("Enter your name: ")


print(“Hello”, name)
Python Identifiers
• A Python identifier is a name used to identify a
variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or
an underscore (_) followed by zero or more
letters, underscores and digits (0 to 9).
• Python does not allow punctuation characters
such as @, $, and % within identifiers.
• Python is a case sensitive programming language.
Python Keywords
Keywords in Python are reserved words that have special
meanings and serve specific purposes in the language syntax.
Python keywords cannot be used as the names of variables,
functions, and classes or any other identifier.
Value Keywords True, False, None

Operator Keywords and, or, not, in, is

if, else, elif, for, while, break, continue, pass,


Control Flow Keywords
try, except, finally, raise, assert

Function and Class def, return, lambda, yield, class

Context Management with, as

Import and Module import, from, as

Scope and Namespace global, nonlocal

Async Programming async, await


Lines and Indentation
• Python provides no braces to indicate blocks of code for class
and function definitions or flow control. Blocks of code are
denoted by line indentation, which is rigidly enforced.
• The number of spaces in the indentation is variable, but all
statements within the block must be indented the same
amount

Comments in Python
• A hash sign (#) that is not inside a string literal begins a
comment. All characters after the # and up to the end of the
physical line are part of the comment and the Python
interpreter ignores them.
Quotation in Python

• Python accepts single ('), double (") and triple ('''


or """) quotes to denote string literals, as long as
the same type of quote starts and ends the string.
• The triple quotes are used to span the string
across multiple lines. For example, all the
following are legal −
• word = 'word' sentence = "This is a sentence."
paragraph = """This is a paragraph. It is made up
of multiple lines and sentences."""
Multi-Line Statements

• Statements in Python typically end with a new


line. Python does, however, allow the use of the
line continuation character (\) to denote that the
line should continue. For example −
total = item_one + \ item_two + \ item_three
• Statements contained within the [], {}, or ()
brackets do not need to use the line continuation
character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
INTRODUCTION OF PYTHON VARIABLES

• Variable is a name that is used to refer to the memory location


• Python variable is also known as identifier to used to hold the
value
• Python variable names can be group of both of letter and digits
• Use lower case letter and upper case letter are different like
RAHUL and rahul
• They use the underscore like the variable (_a) & (a_)
Variable Naming Rules
• The first character of variable must be an alphabet or
underscore(_)
• All the character except the first character may be an alphabet
of lower case like(a-z),upper case like(A-Z) and they use the
digits(0-9)
• Identifier name must not use any white space and special
character (!,@,#,%)
• Identifier name must not be similar any keyword
• Identifier name are case sensitive for example :- NAME and
name are the different name not a same variable
• Example of valid identifier name is :- _a, a123 etc.
Declaring Variables
• Python does not bind us to declare a variable before
using the validation
• It allow to create a variable at the required time
• We don’t need to declare explicitly variable
• We assign any value to the variable that variable
declared
• The equal (=) operator is used to assign the value of
variable
• Example :- A=10
A is a variable name and (=) use the assign the value
and 10 is a value of A
Example of Python Variables
First Declare variable Name=“sourav”
Second add next variable Age=23
Finally print the variable Salary=21500
values print(Name)
print(Age)
A=10 print(Salary)
B=10 Or
C=A+B print(Name,Age,Salary)
print(C)
Multiple Assignment
• Python allows us to assign a value to multiple variable in a single statement It is
known as Multiple Assignment
• We can apply multiple assignment in two ways
• Either by assigning a single value to multiple variables or assigning a multiple
value in multiple variables

Assigning single value to multiple variables


Example:-
a=b=c=100
print(a)
print(b)
print(c)

User assign the single value to multiple variable Like a and b and c variables value is
100 and next step is print all the values
Assigning Multiple Values To Multiple Variables

Example:-
a,b,c=10,20,30
print(a)
print(b)
print(c)

User assign multiple value to multiple variables and


second step print all the values
Deleting variables
We can delete the variable use del keyword
Syntax:-
del<variable_name>

Example :-
x=5
print(x)
del x
print(x) #NameError

Assign the value to variable x and print the value


After printing the value Delete the variable x and then print it
Python Operators

● The operator can be defined as a symbol which is responsible for a


particular operation between two operands.
● Operators are the pillars of a program on which the logic is built in a
specific programming language.
Operators

1. Arithmetic operators
2. Comparison operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic Operators

● Arithmetic operators are used to perform arithmetic operations between two


operands.
● It includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder),
//(floor division), and exponent (**) operators.
● Example of Arithmetic operators:-
● a=20
● b=10
● c=a+b
● Print(c)
Python Operators
% operator General Concept
General formula of modulus
Mod(a, n)= a-n*floor(a/n)
• -1%8= mod(-1,8)=-1-8*floor(-1/8)=-1-8*-1=-1+8=7
Add denominator to numerator till we get 0 or positive
number
• 1%-8= ,mod(1,-8)=1-(-8)*floor(1/-8)=1+8*-1=1-8=-7
Add denominator to numerator till we get 0 or negative
number
• -1%-8= ,mod(-1,-8)=-1-(-8)*floor(-1/-8)=-1+8*0=-1+0=-1
Result is negative of normal result if not 0
• 1%8= ,mod(1,8)=1-(8)*floor(1/8)=1-8*0=1+0=1
Normal case
Comparison operator
● The name itself is explaining that this operator is used to compare different things or
values with one another.
● In Python, the Comparison operator is used to analyze either side of the values and
decides the relation between them.
● Comparison operator is also termed as a relational operator because it explains the
connection between them.
Comparison operator
● Comparison operators are used to comparing the value of the two operands
and returns Boolean true or false accordingly. Example a=10, b=20
Assignment Operators
● The assignment operators are used to assign the value of the right
expression to the left operand. For example: a=10, b=20
Logical Operators
● In Python, Logical operators are used on conditional statements (either True
or False). They perform Logical AND, Logical OR, and Logical NOT
operations.
Bitwise Operators
● The bitwise operators perform bit by bit operation on the values of the two
operands.
Bitwise Operators
It performs logical AND operation on the integer value after converting an integer
to a binary value and gives the result as a decimal value it returns true only if
both operands are true otherwise it returns false
Example of Bitwise AND operators:-
a=7
b=4
c=5
Print(a&b)
Print(a&c)
Print(b&c)
Bitwise Operators
● Bitwise or operators:-
It performs logical OR operation on the integer value after converting integer value
to binary value and gives the result a decimal value . It returns false only if both
operands are true otherwise it returns true.
Example of Bitwise OR operators:-
a=7
b=4
c=5
print(a | b)
print(a | c)
print(b| c)
Bitwise Operators

● Bitwise XOR operators:-


It performs logical XOR operation on the binary value of a integer and gives the
result as a decimal value.
Example of a Bitwise XOR operators:-
a=7
b=4
c=5
print( a ^ c)
print(b ^ c)
Bitwise Operators

● Bitwise 1’s complement ~:-


● It performs 1’s complements operation it invert each bit of binary value and
returns the bitwise negation of a value as a result.
Example of Bitwise 1’st complements:-
a=7
b=4
c=3
print(~a, ~b, ~c)
Bitwise Operators

● Bitwise left-shift << operators:-


The left-shift << operators performs a shifting bit of a value by a given number of the
place and fills 0’s to new positions.
Example of Bitwise left-shift << operators:-

print(4 << 2)
print(5 << 3)
Bitwise Operators

● Bitwise right-shift >>


The left-shift >> operator performs sifting a bit of value to the right by a given
Number of places.

Example of Bitwise right-shift >> operators:-

print(4 >> 2)
print(5 >> 2)
Membership operators

● Membership operators:- python membership operators are used to check for


membership of objects in sequence ,
● such as string , list , tuple. It checks whether the given value or variable is
present in a given sequence.
● If present it will return true else false.
● Python there are two membership operators IN and NOT IN
Membership operators

● IN operator:- it returns a result as true. If it finds a given object in the


sequence. Otherwise it return false.
● Example of IN OPERATORS:-
list =[11,15,21,29,50,70]
num=15
If num in list:
print(“number in present”)
else:
print(“number not in present”)
Membership operators

● NOT IN OPERATOR:-it returns true if the object is not present in a given sequence.
● Otherwise it return false.
● Example of NOT In OPERATOR:-
Tuple =(11,15,21,29,50,70)
num=15
If num not in tuple:
print(“number is present”)
else:
print(“number is not present”)
IDENTITY OPERATORS

● Identity operators check whether the value of two variable is the same or
not.
● This operator is known as reference - quality operators.
● Because the identity operators compares value according to two variable
memory addresses
● Python has 2 identity operators is and is not
IDENTITY OPERATORS

● IS OPERATOR:- this operator return Boolean True or False.


● It return true if the memory address first value is equal to the second value
otherwise it return false.
● Example of is operators:-
x=10
y=11
z=10
print(x is y)
print(x is z)
IDENTITY OPERATORS
● IS NOT OPERATORS: the is not operators return Boolean value either true
or false.
● It return true if the first value is not equal to the second value
● Otherwise it return false.
Example of is not operator:
x=10
y=11
z=10
print(x is not y)
print(x is not z)
Precedence and Associativity of Operators in
Python
Precedence :
Precedence is the order in which different operators in an expression are evaluated.
Operators with higher precedence are executed before those with lower precedence, which
ensures that expressions are processed according to the rules of operator priority.

Associativity:

Associativity defines the order in which operators of the same precedence level are
evaluated in an expression. It determines whether operations are performed from left to
right or right to left.
Example:

1. exp= 100 + 200 / 10 - 3 * 10


print(exp)

2. result = (4 + 6) * (2 ** 3) / 5 - 7 % 3
print(result)

3. result = not (True and False) or (False or True)


print(result)

4. result = 5.0 * 2 + 3.0 ** 2 - 8.0 / 4


print(result)

5. result = 8 * 3 + 2 - 12 // 4 ** 2 // (5 % 3) + 1 - 6 - 2 * 1 + 1 ** 2
print(result)
Answers:

1.90.0
2.15.0
[Link]
4.17.0
5.20
Python Objects
• Everything in python is object.
• Every object specifically data has three properties
type, id and value
• ID remains same once data is created.
• Objects whose value can change after creation is
called mutable and whose value can't be changed
is called immutable
• Mutable examples: list, set, dictionary
• Immutable examples: int, float, decimal, bool,
string, tuple, and range.
Python Data Types

● Data types are the classification or categorization of data items. It represents the kind of value that tells
what operations can be performed on a particular data.

● Since everything is an object in Python programming, data types are actually classes and variables are
instances (objects) of these classes.
Python Data Types

a=5
The variable a holds integer value five and we did not define its type.
Python interpreter will automatically interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program.
Python provides us the type() function, which returns the type of the variable
passed.
NUMERIC DATA TYPE
Numeric Data Type

● Number stores numeric values.


● The integer, float, and complex values belong to a Python Numbers
data-type.
● Python provides the type() function to know the data-type of the variable.
● Similarly, the isinstance() function is used to check an object belongs to
a particular class.
Numbers

Python supports three types of numeric data.


1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150
etc. Python has no restriction on the length of an integer. Its value
belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2,
etc. It is accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where
x and y denote the real and imaginary parts, respectively. The complex
numbers like 2.14j, 2.0 + 2.3j, etc.
Output
Numbers
The type of a <class 'int'>
a=5 The type of b <class 'float'>
The type of c <class 'complex'>
print("The type of a", type(a)) c is complex number: True
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
String Data Type
String
Python string is the collection of the characters surrounded by single quotes, double quotes,
or triple quotes.
Syntax:
str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
print(type(str)) #then it will print a string (str).
In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type;
instead, a single character written as 'p' is treated as the string of length 1.
String

#Using single quotes #Using triple quotes

str1 = 'Hello Python' str3 = '''''Triple quotes are


generally used for represent the
print(str1) multiline or docstring'''
#Using double quotes print(str3)
str2 = "Hello Python"
print(str2)
Strings indexing and splitting
Strings indexing and splitting

the slice operator [] is used to access


the individual characters of the
string.

However, we can use the : (colon)


operator in Python to access the
substring from the given string.
Strings indexing and splitting

We can do the negative slicing in the string; it starts from the rightmost character,
which is indicated as -1.

The second rightmost index indicates -2,

and so on.
String Concatenation

a = "Hello"
To add a space between them, add a " ":
b = "World" a = "Hello"
c=a+b b = "World"
c=a+""+b
print(c) print(c)
LIST
Python List

● A list in Python is used to store the sequence of various types of data.


● Python lists are mutable type its mean we can modify its element after it created.
● A list can be defined as a collection of values or items of different types.
● The items in the list are separated with the comma (,) and enclosed with the square
brackets [].

A list can be defined as below

1. L1 = ["John", 102, "USA"]


2. L2 = [1, 2, 3, 4, 5, 6]
List is a collection which is ordered and changeable.

Allows duplicate members.


List indexing and splitting
List indexing and splitting

Unlike other languages, Python provides the flexibility to use the negative indexing also.
The negative indices are counted from the right.
Tuple

● Tuples are used to store multiple items in a single variable.


● A tuple is a collection which is ordered and unchangeable.
● Tuples are written with round brackets.

Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple

● Tuple items are ordered, unchangeable, and allow duplicate values.


● Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
● When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.
● Tuples are unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created. (Immutable)
● Allow Duplicates : they can have items with the same value:
Tuple
T1 = (101, "Peter", 22)

T2 = ("Apple", "Banana", "Orange")

T3 = 10,20,30,40,50

T4 = (10,)

T5 = ()
Tuple indexing and slicing

The indexing and slicing in the tuple are similar to lists.

The indexing in the tuple starts from 0 and goes to length(tuple) - 1.

The items in the tuple can be accessed by using the index [] operator.

Python also allows us to use the colon operator to access multiple items in the
tuple.
Tuple indexing and slicing
Boolean

● A Boolean data type is a data type that can hold one of two built-in values: True
or False. These values represent truth values, where True indicates something is
correct or exists, and False indicates the opposite. In Python, Boolean values are
represented by the bool class.

Note:True and False must begin with a capital T and F respectively;


otherwise, Python will raise a syntax error.
Set
● Set is an unordered collection of data types that is unindexed,iterable,
immutable, and has no duplicate elements.

● The order of elements in a set is undefined though it may consist of various


elements.

● Set can be created by placing the sequence inside curly braces, separated by a
‘comma’.

● The type of elements in a set need not be the same, various mixed-up data type
values can also be passed to the set.

● Sets can also be created by using the built-in set() function


Dictionary
● Dictionary in Python is an unordered collection(till python 3.6 version) , ( from python
3.7 onwards Dictionary is ordered) of data values, used to store data values like a map,
which unlike other Data Types that hold only single value as an element, Dictionary holds
key:value pair.

● Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a
Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.

● 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.

● Dictionary can also be created by the built-in function dict()

Note:Dictionary keys are case sensitive, same name but different cases of Key will be
treated distinctly.
Type Conversion Functions:
int() – converts any data type into integer type
float() – converts any data type into float type
str() – Converts any var. value/Constant into string type
ord() – converts characters into integer
hex() – converts integers to hexadecimal
oct() – converts integer to octal
Many other will see in future
Reading binary octal and hex number
Converting Decimal to non decimal

You might also like