0% found this document useful (0 votes)
26 views21 pages

Pgdca Python Notes

This document provides an introduction to Python, covering its definition, applications, features, installation, and basic programming concepts. It explains Python's syntax, data types, variables, and operators, along with examples of how to create and run Python programs. Additionally, it outlines the importance of indentation and syntax rules in Python programming.

Uploaded by

kush.arun0599
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)
26 views21 pages

Pgdca Python Notes

This document provides an introduction to Python, covering its definition, applications, features, installation, and basic programming concepts. It explains Python's syntax, data types, variables, and operators, along with examples of how to create and run Python programs. Additionally, it outlines the importance of indentation and syntax rules in Python programming.

Uploaded by

kush.arun0599
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 NOTES

UNIT-1 Introduction to Python

What is Python?

Python is a general-purpose, high-level, interpreted, object-oriented programming language


used for various applications.

Python was developed by Guido Van Rossum in 1990 while working at National Research
Institute in the Netherlands. But officially, Python was made available to the public in 1991.

Python code syntax uses English keywords, making it easy to understand. Therefore, Python
is recommended as the first programming language for beginners.

Applications of Python
We can use Python everywhere because Python is known for its general-purpose nature, which
makes it applicable in almost every domain of software development. The most common application
areas are:

 Desktop Applications
 Web Applications
 Database Applications
 Network Programming
 Games
 Data Analysis Applications
 Machine Learning
 Artificial Intelligence Applications

Features of Python
1) Simple & Easy to Learn

 Python syntax is close to English language


 Less code compared to C, C++ or Java

2) Interpreted Language

 Python code runs line by line


 No need to compile first
 Easy to debug errors

3) High-Level Language

 No need to manage memory manually


 Focus on logic, not hardware details

4) Dynamically Typed

 No need to declare data type

a = 10
a = "Python"
 Type is decided at runtime

5) Object-Oriented

 Supports Class & Object


 Also supports procedural and functional programming

6) Platform Independent

 Same Python code runs on:


o Windows
o Linux
o macOS

7) Large Standard Library


 Ready-made modules available:
o math
o random
o datetime
o os

8) Extensive Third-Party Libraries

 Used in different fields:


o Data Science → NumPy, Pandas
o Machine Learning → TensorFlow, Scikit-Learn
o Web Development → Django, Flask
o Automation → Selenium

Install Python
Installing or updating Python on your computer is the first step to programming in Python.
There are multiple installation methods, such as installing Python using an installer or a
source code (.zip file)

Download the latest version of Python from [Link]. Once you’ve downloaded the
installer as per the operating system, Next run an installer by double-clicking on the
downloaded file and following the steps.
After installation is completed, we will get a setup successfully install message.

Let’s open the command line or terminal and type the below command to check the version
of Python.

python --version

Create and Run Your First Python Program


We can run Python by using the following three ways

 Run Python using IDLE


 Run Python interactively using the command line in immediate mode
 Executing Python File
Run Python Using IDLE
IDLE is an integrated development environment (IDE) for Python. The Python
installer contains the IDLE module by default. Thus, when you install Python,
IDLE gets installed automatically.

Go to launchpad (for mac) and start icon (for Windows) and type IDLE, to open
it. IDLE is an interactive Python Shell where you can write python commands
and get the output instantly.

IDLE Python Editor

Let’s see how to print ‘hello world’ in Python using IDLE. Type print('Hello,
World') and hit enter.

Hello world in Python

IDLE has features like coding hinting, syntax highlighting, checking, etc.

Also, we can create a new file, write Python code, and save it with
the .py extension. The .py is the python file extension which denotes this is the
Python script.

Let’s see how to create a Python script using IDLE.

 Go to the File Menu and select the new file option


 Type the same code (hello world message) in it
 Next, Go to the File menu to save it as [Link]

Create Python script

Next, To run the script, go to the Run > Run Module or simply click F5.

Run Python script in IDLE

Run Python on Command Line

We can also run Python on the command line.

 Type python command on the command line or terminal to run Python


interactively. It will invoke the interpreter in immediate mode.
 Next, type Python code and press enter to get the output.
Please find the below image for demonstration.
Run Python on the command line
To exit this mode, type quit() and press enter.

Execute Python File


Python is an interpreted programming language in which we create a code file
( .py with extension) and pass it to the Python interpreter to execute
whenever required.

Open any text editor and type the below code in it, and save it as a [Link]

print('Hello, World')
Now, open the terminal or command line and use the below command to
execute the [Link]. You need to change the directory where this file is
present before executing it.

python [Link]
Here python is the command and [Link] is the file name you want to execute.

Python script using command line


Syntax and Indentation in Python
Syntax is the structure of language or a set of rules that defines how a Python
program will be written and interpreted.

Using Blank Lines in code


A line containing only white space, possibly with a comment or within a code,
is known as a blank line, and Python ignores it.

End-of-Line to Terminate a Statement


In Python end of the line terminate the statement. So you don’t need to write
any symbol to mark the end of the line to indicate the statement termination.
For example, in other programming languages like Java and C, the statement
must end with a semicolon (;).

Example

a = 20
Python statement ends with the token NEWLINE character (\n). But we can
extend the statement over multiple lines using line continuation character ( \).
This is known as an explicit continuation.

addition = 10 + 20 + \
30 + 40 + \
50 + 60 + 70
print(addition)

Semicolumn to Separate Multiple Statements

In Python, we can add multiple statements on a single line separated by


semicolons, as follows:

# two statements in a single


l = 2; b = 6

# statement 3
print('Area of rectangle:', l * b)

Indentation
Python indentation tells a Python interpreter that the group of statements
belongs to a particular block of code. The indentation makes the code look
neat, clean, and more readable.
A block is a combination of all multiple statements. Inside a code block, we
group multiple statements for a specific purpose.

In other programming languages like C or Java, use curly braces { } to define a


block of code. Python uses indentation to denote the code block.

Whitespace is used for indentation in Python to define the indentation level.


Ideally, we should use 4 spaces per indentation level. In Python, indented
code blocks are always preceded by a colon (:) on the previous line.

Take the example of the if-else statement in Python.

num1 = 50
num2 = 100
if num1 > num2:
print(num1, 'is greater than', num2)
elif num2 > num1:
print(num2, 'is greater than', num1)
else:
print('Both numbers are equal')

Python Data Types


Data types specify the different sizes and values that can be stored in the variable.
For example, Python stores numbers, strings, and a list of values using different data
types.
Here are mainly four types of basic/primitive data types available in Python

 Numeric: int, float, and complex


 Sequence: String, list, and tuple
 Set
 Dictionary (dict)
To check the data type of variable use the built-in function type() and isinstance().

 The type() function returns the data type of the variable


Data type Description Example

int To store integer values n = 20

float To store decimal values n = 20.75

complex To store complex numbers (real and n = 10+20j

imaginary part)

str To store textual/string data name = 'Jessa'

bool To store boolean values flag = True

list To store a sequence of mutable data l = [3, 'a', 2.5]

tuple To store sequence immutable data t =(2, 'b', 6.4)

dict To store key: value pair d = {1:'J', 2:'E'}

set To store unorder and unindexed s = {1, 3, 5}

values

frozenset To store immutable version of the set f_set=frozenset({5,7})

range To generate a sequence of number numbers = range(10)


bytes To store bytes values b=bytes([5,10,15,11])

Python Data Types

Python Variables
Variable is an identifier or a name, which is used to pointout or represent a memory location.

Python variables are created automatically when you assign a value to them.

OR

Variable are the named memory location.

Creating a Variable
x = 10
name = "Python"
price = 99.5

No Data Type Declaration Needed

Wrong (C-style)

int a = 5

Correct (Python):

a=5

Types of Values Stored in Variables

a = 10 # int
b = 3.14 # float
c = "Hello" # string
d = True # boolean
e = 2 + 3j # complex

Rules for creating variables

• Every variable name should start with alphabets or underscore (_).


• No spaces are allowed in variable declaration.
• Except underscore ( _ ) no other special symbol are allowed in the middle of the variable
declaration
• A variable is written with a combination of letters, numbers and special characters _
(underscore)
• No Reserved keyword

Examples
Do
 A
 A
 Name
 name15
 _city
 Full_name

Don’t
 And
 15name
 $city
 Full$Name
 Full Name

Multiple Assignment
Same value to multiple variables
a = b = c = 100
Different values to multiple variables
x, y, z = 1, 2, 3

Immutable Variables in Python

Immutable variables are variables whose values cannot be changed after creation.
If you try to modify them, Python creates a new object instead of changing the existing one.

Example with Integer (Immutable)

a = 10

print(id(a))

a=a+5

print(id(a))

Python Operators
Operators are special symbols that perform specific operations on one or more
operands (values) and then return a result. For example, you can calculate the sum of
two numbers using an addition (+) operator.

The following image shows operator and operands


Python has seven types of operators that we can use to perform different operation
and produce a result.

1. Arithmetic operator
2. Relational operators
3. Assignment operators
4. Logical operators
5. Membership operators
6. Identity operators
7. Bitwise operators

Arithmetic operator
Arithmetic operators are the most commonly used. The Python programming
language provides arithmetic operators that perform addition, subtraction,
multiplication, and division. It works the same as basic mathematics.

There are seven arithmetic operators we can use to perform different mathematical
operations, such as:

1. + (Addition)
2. - (Subtraction)
3. * (Multiplication)
4. / (Division)
5. // Floor division)
6. ℅ (Modulus)
7. ** (Exponentiation)

Arithmetic operator
Arithmetic operators are the most commonly used. The Python programming
language provides arithmetic operators that perform addition, subtraction,
multiplication, and division. It works the same as basic mathematics.

There are seven arithmetic operators we can use to perform different mathematical
operations, such as:

1. + (Addition)
2. - (Subtraction)
3. * (Multiplication)
4. / (Division)
5. // Floor division)
6. ℅ (Modulus)
7. ** (Exponentiation)

Operator Name Example Result


+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 5 / 2 2.5
% Modulus 5 % 2 1
// Floor Division 5 // 2 2
** Exponent 2 ** 3 8

Floor division //

Floor division returns the quotient (the result of division) in which the digits
after the decimal point are removed. In simple terms, It is used to divide one value by
a second value and gives a quotient as a round figure value to the next smallest
whole value.
It works the same as a division operator, except it returns a possible integer.
The // symbol denotes a floor division operator.

Note:

 Floor division can perform both floating-point and integer arithmetic.


 If both operands are int type, then the result types. If at least one operand type,
then the result is a float type.
Example

x=2
y=4
z = 2.2

# normal division
print(y / x)
# Output 2.0

# floor division to get result as integer


print(y // x)
# Output 2

# normal division
print(y / z) # 1.81

# floor division.
# Result as float because one argument is float
print(y // z) # 1.0
Membership operators
Python’s 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.

In Python, there are two membership operator in and not in

In operator
It returns a result as True if it finds a given object in the sequence. Otherwise, it
returns False.

Not in operator

It returns True if the object is not present in a given sequence. Otherwise, it


returns False

Identity operators
Use the Identity operator to check whether the value of two variables is the same or
not. This operator is known as a reference-quality operator because the identity
operator compares values according to two variables’ memory addresses.

Python has 2 identity operators is and is not.

is operator

The is operator returns Boolean True or False. It Return True if the memory address
first value is equal to the second value. Otherwise, it returns False.

Here, we can use is() function to check whether both variables are pointing to the
same object or not.

is not operator

The is not the operator returns boolean values either True or False. It Return True if the
first value is not equal to the second value. Otherwise, it returns False.
Bitwise Operators
In Python, bitwise operators are used to performing bitwise operations on integers.
To perform bitwise, we first need to convert integer value to binary (0 and 1) value.

The bitwise operator operates on values bit by bit, so it’s called bitwise. It always
returns the result in decimal format. Python has 6 bitwise operators listed below.

1. & Bitwise and


2. | Bitwise or
3. ^ Bitwise xor
4. ~ Bitwise 1’s complement
5. << Bitwise left-shift
6. >> Bitwise right-shift

Bitwise and &

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

a=7
b=4
c=5
print(a & b)
print(a & c)
print(b & c)
Here, every integer value is converted into a binary value. For example, a =7, its
binary value is 0111, and b=4, its binary value is 0100. Next we performed logical
AND, and got 0100 as a result, similarly for a and c, b and c
Following diagram shows AND operator evaluation.
Bitwise or |

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

a=7
b=4
c=5
print(a | b)
print(a | c)
print(b | c)
Here, every integer value is converted into binary. For example, a =7 its binary value is
0111, and b=4, its binary value is 0100, after logical OR, we got 0111 as a result.
Similarly for a and c, b and c.

Bitwise xor ^
It performs Logical XOR ^ operation on the binary value of a integer and gives the
result as a decimal value.

Example: –

a=7
b=4
c=5
print(a ^ c)
print(b ^ c)
Here, again every integer value is converted into binary. For example, a =7 its binary
value is 0111 and b=4, and its binary value is 0100, after logical XOR we got 0011 as a
result. Similarly for a and c, b and c.
Bitwise 1’s complement ~

It performs 1’s complement operation. It invert each bit of binary value and returns
the bitwise negation of a value as a result.

Example

a=7
b=4
c=3
print(~a, ~b, ~c)
# Output -8 -5 -4

Bitwise left-shift <<


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

Example: –

print(4 << 2)
# Output 16
print(5 << 3)
# Output 40
Bitwise right-shift >>
The left-shift >> operator performs shifting a bit of value to the right by a given
number of places. Here some bits are lost.
print(4 >> 2)
# Output
print(5 >> 2)
# Output

Assignment Operators
Assignment operators are used to perform arithmetic operations while assigning a
value to a variable.

Operator Example Equivalent Expression (m=15) Result

= y = a+b y = 10 + 20 30

+= m +=10 m = m+10 25

-= m -=10 m = m-10 5

*= m *=10 m = m*10 150

/= m /=10 m = m/10 1.5

%= m %=10 m = m%10 5

**= m**=2 m = m**2 or 225

//= m//=10 m = m//10 1


Ternary Operator (Conditional Expression)

The ternary operator is used to write a simple if–else in one line.

Syntax:
value_if_true if condition else value_if_false

Example:
a = 10
b = 20
max = a if a > b else b
print(max)

Increment and Decrement Operator

Python does not support ++ and -- operators (like C/C++).

Increment

x=5
x=x+1 # or
x += 1

Decrement

x=5
x=x-1 # or
x -= 1

Python Operators Precedence


In Python, operator precedence and associativity play an essential role in solving the
expression. An expression is the combination of variables and operators that evaluate
based on operator precedence.

We must know what the precedence (priority) of that operator is and how they will
evaluate down to a single value. Operator precedence is used in an expression to
determine which operation to perform first.

Example: –

print((10 - 4) * 2 +(10+2))
# Output 24
In the above example. 1st precedence goes to a parenthesis(), then for plus and
minus operators. The expression will be executed as.

(10 - 4) * 2 +(10+2)

6 * 2 + 12
12 + 12

The following tables shows operator precedence highest to lowest.

Precedence level Operator Meaning

1 (Highest) () Parenthesis

2 ** Exponent

3 +x, -x ,~x Unary plus, Unary Minus, Bitwise negation

4 *, /, //, % Multiplication, Division, Floor division, Modulus

5 +, - Addition, Subtraction

6 <<, >> Bitwise shift operator

7 & Bitwise AND

8 ^ Bitwise XOR

9 | Bitwise OR

10 ==, !=, >, >=, <, <= Comparison

11 is, is not, in, not in Identity, Membership

12 not Logical NOT

13 and Logical AND

14 (Lowest) or Logical OR

Comments in Python
Comments in programming are used to hide the code or the code which we
don’t want to show the interpreter to execute the code.

Single-Line Comment

# This is a single-line comment

x = 10 # Assigning value to x

Multi-Line Comment
Uses triple quotes (''' or """)
Mainly used for documentation, not regular comments.
"""
This program
adds two numbers
"""
a = 10
b = 20
print(a + b)

Understanding error messages.


An error is a mistake in a program that causes it to produce incorrect output or prevents it
from executing properly.
OR
In Python, an error occurs when the interpreter detects a mistake in syntax, logic, or during
program execution, leading to abnormal program behavior.

There are basically three types of errors

Compile-time errors: These are syntactical errors found -in the code, due to which a
program fails to compile.

Logical errors: These errors represent flaws in the logic of the program. The programmer
might using a wrong formula or the design of the program itself is wrong.

Run-time errors: These errors represent inefficiency of the computer system to execute the
particular statement. For example, insufficient memory to store something or inability of the
microprocessor to execute some statement due to lack of resources like-memory, permission,
Busy IO devices are come under run-time errors.

You might also like