[Go to site: main page, start]

0% found this document useful (0 votes)
3 views39 pages

Unit 1 Python Programming Notes

This document provides an introduction to Python, covering its features, applications, and installation process. It discusses Python's syntax, data types, variables, and control structures, along with examples of simple programs. Additionally, it highlights the differences between interactive and script modes, as well as the use of identifiers, keywords, and input/output operations.

Uploaded by

jndka09
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)
3 views39 pages

Unit 1 Python Programming Notes

This document provides an introduction to Python, covering its features, applications, and installation process. It discusses Python's syntax, data types, variables, and control structures, along with examples of simple programs. Additionally, it highlights the differences between interactive and script modes, as well as the use of identifiers, keywords, and input/output operations.

Uploaded by

jndka09
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

Unit – 1

Introduction to Features and Applications of Python; Python Versions; Installation of Python;


Python Command Line mode and Python IDEs; Simple Python Program. Identifiers;
Keywords; Statements and Expressions; Variables; Operators; Precedence and Association;
Data Types; Indentation; Comments; Built-in Functions- Console Input and Console Output,
Type Conversions; Python Libraries; Importing Libraries with Examples. Python Conditional
Statements- Conditional Statements, if, else, elif, while loop, break, continue statements, for
loop Statement; range () and exit () functions. Arrays: Definition, syntax, accessing the
elements of an arrays, array methods.

What is Python?
Python is a high-level, cross-platform, and open-sourced programming language.

Introduction to Python
Python is a general-purpose, high-level, interpreted programming language that supports multiple
programming paradigms, including procedural, object-oriented, and functional programming, and is widely
used among the developers’ community. Python was mainly developed for emphasis on code readability,
and its syntax allows programmers to express concepts in fewer lines of code. It was developed by Guido
van Rossum during 1985- 1990. Python got its name from “Monty Python’s flying circus”. Python was
released in the year 2000.

 Python is interpreted: Python is processed at runtime by the interpreter. You do not need to compile
your program before executing it.
 Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly
to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique of programming that
encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginner- level programmers
and supports the development of a wide range of applications.

Why to use Python:

The following are the primary factors to use python in day-to-day life:
 Python is object-oriented: Structure supports such concepts as polymorphism, operation overloading
and multiple inheritance.
 Indentation: Indentation is one of the greatest feature in python.
 It’s free (open source): Downloading python and installing python is free and easy.
 It’s Powerful: Dynamic typing, Built-in types and tools Library utilities, Third party utilities (e.g.
Numeric, NumPy, sciPy) Automatic memory management.
 It’s Portable: Python runs virtually every major platform used today. As long as you have a compatible
python interpreter installed, python programs will run in exactly the same manner, irrespective of
platform.
 It’s easy to use and learn: No intermediate compile, Python Programs are compiled automatically to
an intermediate form called byte code, which the interpreter then reads. This gives python the
development speed of an interpreter without the performance loss inherent in purely interpreted
languages. Structure and syntax are pretty intuitive and easy to grasp.
 Interpreted Language: Python is processed at runtime by python Interpreter.
 Interactive Programming Language: Users can interact with the python interpreter directly for
writing the programs.
 Straight forward syntax: The formation of python syntax is simple and straight forward which also
makes it popular.

1|Pa ge
Features of Python

 Readability: Python’s syntax is clear and easy to understand.


 Extensive Libraries: A rich set of libraries and frameworks (e.g., NumPy, Pandas, Flask).
 Cross-Platform: Works on various operating systems (Windows, macOS, Linux).
 Dynamic Typing: Variables do not require explicit declaration.
 Community Support: A large community offers extensive documentation and support.

Applications of Python

 Web Development: Frameworks like Django and Flask.


 Data Science: Libraries like Pandas, NumPy, and Matplotlib.
 Machine Learning: Libraries like TensorFlow and Scikit-learn.
 Automation/Scripting: Automating repetitive tasks.
 Game Development: Libraries like Pygame.

Python Versions
Python has several major versions, with the most notable being:
 Python 2.x: Legacy version; officially discontinued in January 2020.
 Python 3.x: Current version with many improvements and features; recommended for all new
projects.

2|Pa ge
Installation of Python

The Installation Procedure of Python:


1. Download: Visit the official Python website. ([Link]
2. Choose Version: Select and download the appropriate version for your operating system.
3. Run Installer: Follow the installation instructions, ensuring you check the box to add Python to your
PATH.
4. Verify Python Was Installed On Windows.
5. Verify Pip Was Installed.
Add Python Path to Environment Variables (Optional)

Python Command Line and IDEs Mode


Command Line Mode (Interactive mode)
 Open a terminal or command prompt.
 Type python or python3 to enter the interactive shell.
 You can execute Python commands directly.

Advantages:
 Python, in interactive mode, is good enough to learn, experiment or explore.
 Working in interactive mode is convenient for beginners and for testing small pieces of code.

Drawback:
 We cannot save the statements and have to retype all the statements once again to re-run them.

3|Pa ge
Integrated Development Environments (IDEs) (Script mode)

 PyCharm: A powerful IDE for Python with many features.


 Visual Studio Code: A lightweight editor with Python support through extensions.
 Jupyter Notebook / Jupyter Lab: Ideal for data analysis and visualization.
 IDLE: Comes pre-installed with Python; suitable for beginners.

Simple Python Program


Here’s a simple Python program that prints "Hello, World!” is
# Simple Python Program
print("Hello, World!")

Running the Program


1. Save the code in a file named [Link].
2. Open the command line and navigate to the directory where the file is saved.
3. Run the program using the command: python [Link]
This will output:Hello, World!

Interactive mode Script mode


A way of using the Python interpreter by A way of using the Python interpreter to read and
typing commands and expressions at the execute statements in a script.
prompt.
Cant save and edit the code Can save and edit the code
If we want to experiment with the code, we If we are very clear about the code, we can use
can use interactive mode. script mode.

we cannot save the statements for further use we can save the statements for further use and we
and we have to retype all the statements to re- no need to retype all the statements to re-run
run them. them.
We can see the results immediately. We cant see the code immediately.

Python Basics

Identifiers:
 Definition: Identifiers in Python are names used to identify variables, functions, classes, modules,
and other objects in the code.
 Rules to write an identifier:
 Must start with a letter (a-z, A-Z) or an underscore ( _ ).
 Can contain letters, digits (0-9), and underscores.
 Case-sensitive (e.g., myVar and myvar are different).
 Cannot be a Python Keyword
 No special characters are allowed

Keywords:
 Definition: 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.
Examples:
True False None And

or not is If

4|Pa ge
else elif for while

break continue pass try

except finally raise assert

def return lambda yield

class import from in

as del global with

nonlocal Async Await

Statements and Expressions:

 Statement: A line of code that performs an action (e.g., assignments, function calls).
 Expression: A combination of values and operators that evaluates to a value (e.g., 3 + 4).

Variables:

In Python, variables are containers, which is used to store data values. Python supports various datatypes,
including integers, floats, strings, and booleans. It represents the kind of value that tells what operations
can be performed on a particular data. Variables are created when we assign a value to them, using the
assignment operator (=).

Example:
var = "Saradavilas"
print(var)

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals
or characters in these variables.
Output:
Rules for Python variables:
 A variable name must start with a letter or the
Saradavilas underscore (_) character
college,Mysore
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)

5|Pa ge
 Variables Assignment in Python/Declaration and Initialization of Variables:

# 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

 Redeclaring variables in Python:

We can re-declare the Python variable once we have declared the variable already.

# declaring the var


Number = 100

# display
print("Before declare: ", Number)

# re-declare the var


Number = 120.3
print("After re-declare:", Number)

Output:

Before declare: 100


After re-declare: 120.3

6|Pa ge
Types of Variables:

There are two types of variables: Global variables and Local variables.

The scope of global variables is the entire program whereas the scope of local variable is limited to the
function where it is defined.

Example
def func():
x = "Python"
s = "test"
print(x)
print(s)
s = "BCA"
print(s)
func()
print(x)

Output:

In above program- x is a local variable whereas s is a global variable, we can access the
local variable only within the function it is defined (func() above) and trying to call local variable outside its
scope(func()) will through an Error as shown below −

Python
test
BCA

Traceback (most recent call last):


File "[Link]", line 9, in <module>
print(x)
NameError: name 'x' is not defined
However, we can call global variable anywhere in the program including functions (func()) defined in the
program.

 Local variables:

Local variables can only be reached within their scope(like func() above). Like in below program-
there are two local variables – x and y.

Example

def sum(x,y):
sum = x + y return sum print(sum(5, 10))

Output

The variables x and y will only work/used inside the function sum() and they don’t exist outside of the
function. So trying to use local variable outside their scope, might through NameError.
So obviously below line will not work.
7|Pa ge
File "[Link]", line 2 sum = x + y
^
IndentationError: expected an indented block

 Global variables

A global variable can be used anywhere in the program as its scope is the entire program.
Let’s understand global variable with a very simple example

Example

z = 25
def func():
global z
print(z)
z=20
func()
print(z)

Output
25
20

A calling func(), the global variable value is changed for the entire program.
Below example shows a combination of local and global variables and function parameters –

def func(x, y):


global a
a = 45
x,y = y,x
b = 33
b = 17
c = 100
print(a,b,x,y)
a,b,x,y = 3,15,3,4
func(9,81)
print (a)

Output

45 17 81 9
3

8|Pa ge
Assigning Values to Variables:
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used
to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.
For example −
a= 100
b = 1000.0
c = "John" print (a) print (b) print (c)

# An integer assignment
# A floating point
# A string

This produces the following result −


100
1000.0
John

Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.

For example:
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.

For example:
a,b,c = 1,2,"saradavilas“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.

Output Variables:
The Python print statement is often used to output variables. Variables do not need to be
declared with any particular type and can even change type after they have been set.
x=5
x = "saradavilas "
print(x)
# x is of type int
# x is now of type str
Output
Saradavilas

Input and Output in Python

Understanding input and output operations is fundamental to Python programming.


With the print() function,
we can display output in various formats, while the input() function enables interaction with users
by gathering input during program execution.

Taking input in Python


Python's input() function is used to take user input. By default, it returns the user input in form
of a string.

Example:
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")

Output
Enter your name: GeeksforGeeks
Hello, GeeksforGeeks ! Welcome!

The code prompts the user to input their name, stores it in the variable "name" and
then prints a greeting message addressing the user by their entered name.

Printing Output using print() in Python

At its core, printing output in Python is straightforward, thanks to the print() function.
This function allows us to display text, variables and expressions on the console.
Let's begin with the basic usage of the print() function:

In this example, "Hello, World!" is a string literal enclosed within double quotes.
When executed, this statement will output the text to the console.
print("Hello, World!")

Output

Hello, World!

Printing Variables

We can use the print() function to print single and multiple variables. We can print
multiple variables by separating them with commas.

Example:

s = "Brad"
print(s)
s = "Anjelina"
age = 25
city = "New York"
print(s, age, city)

Output
Brad
Anjelina 25 New York

Take Multiple Input in Python

We are taking multiple input from the user in a single line, splitting the values entered
by the user into separate variables for each value using the split() method. Then,
it prints the values with corresponding labels, either two or three, based on the number
of inputs provided by the user.

x, y = input("Enter two values: ").split()


print("Number of boys: ", x)
print("Number of girls: ", y)

x, y, z = input("Enter three values: ").split()


print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)

Output
Enter two values: 5 10
Number of boys: 5
Number of girls: 10

Enter three values: 5 10 15


Total number of students: 5
Number of boys is : 10
Number of girls is : 15

Expressions:

An expression is a combination of values, variables, and operators.


An expression is evaluated using the assignment operator.
Or
An expression is a combination of operators and operands that is interpreted to produce some
other value. In any programming language, an expression is evaluated as per the precedence of its operators.

Examples:
Y = x + 17
>>> x = 10
>>> z = x + 20
>>> z
30
>>> x = 10
>>> y = 20
>>> c = x + y
>>> c 30
A value all by itself is a simple expression, and so is a variable.
>>> y = 20
>>> y 20
Python also defines expressions only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or object
is an identifier.

Literals: These are language-independent terms in Python and should exist independently in any
programming language. In Python, there are the string literals, byte literals, integer literals,
floating point literals, and imaginary literals.

Generator expression:

Syntax: ( compute(var) for var in iterable )


>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object
<genexpr> at 0x02AAD710>

The result of a tuple comprehension is not a tuple: it is actually a generator.


The only thing that you need to know now about a generator now is that you can
iterate over it, but ONLY ONCE

.
Conditional expression:

Syntax: true_value if Condition else false_value


>>> x = "1" if True else "2"
>>> x
'1'

Types of Python Expressions:

1. Constant Expressions: These are the expressions that have constant values only.
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators,
and sometimes parenthesis. The result of this type of expression is also a numeric value. The operators
used in these expressions are arithmetic operators like addition, subtraction, etc. Here are some
arithmetic operators in Python:

3. Integral Expressions: These are the kind of expressions that produce only integer results
after all computations and type conversions.

4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.

5. Relational Expressions: In these types of expressions, arithmetic expressions are written on


both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first,
and then compared as per relational operator and produce a boolean output in the end. These
expressions are also called Boolean expressions.

6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is
not correct, so it will return False. Studying logical expressions, we also come across some logical operators
which can be seen in logical expressions most often. Here are some logical operators in Python:
7. Bitwise Expressions: These are the kind of expressions in which computations
are performed at bit level.

8. Combinational Expressions: We can also use different types of expressions in a


single expression, and that will be termed as combinational expressions .

Python Operators:
Operators are special symbols that perform some operation on
operands and returns the result. For example, 5 + 6 is an expression where
+ is an operator that performs arithmetic add operation on numeric left
operand 5 and the right side operand 6 and returns a sum of two operands
as a result.

Python includes the following categories of operators:

 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Identity Operators
 Membership Test Operators
 Bitwise Operators

Arithmetic Operators:
Arithmetic operators perform the common mathematical operation on the
numeric operands.

The arithmetic operators return the type of result depends on the type of
operands, as below.

1. If either operand is a complex number, the result is


converted to complex;
2. If either operand is a floating point number, the
result is converted to floating point;
3. If both operands are integers, then the result is an integer
and no conversion is needed.

The following table lists all the arithmetic operators in Python:

14 | P a g e
Assume variable a holds 10 and variable b holds 20, then

Example:
a = 21
b = 10
c=0

c=a+b
print "Line 1 - Value of c is ", c

c=a–b
print "Line 2 - Value of c is ", c

c=a*b
print "Line 3 - Value of c is ", c

c=a/b
print "Line 4 - Value of c is ", c

c=a%b
print "Line 5 - Value of c is ", c

a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c

a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c

Output:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2

Assignment Operators:
These operators are used to assign values to the variables.

15 | P a g e
Assume variable a holds 10 and variable b holds 20, then –
Example :
a = 21
b = 10
c=0

c=a+b
print "Line 1 - Value of c is ", c

c += a
print "Line 2 - Value of c is ", c

c *= a
print "Line 3 - Value of c is ", c

c /= a
print "Line 4 - Value of c is ", c

c = 2 c %= a
print "Line 5 - Value of c is ", c

c **= a
print "Line 6 - Value of c is ", c

c //= a
print "Line 7 - Value of c is ", c
16 | P a g e
Output:
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Comparison Operators:

These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then –

Example:
a = 21
b = 10
c=0

if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"

if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"

if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
17 | P a g e
print "Line 3 - a is equal to b"

if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"

if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"

a = 5;
b = 20;

if ( a <= b ):
print "Line 6 - a is either less than or equal to b"
else:
print "Line 6 - a is neither less than nor equal to b"

if ( b >= a ):
print "Line 7 - b is either greater than or equal to b"
else:
print "Line 7 - b is neither greater than nor equal to b"

Output:
Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not equal to b
Line 4 - a is not less than b
Line 5 - a is greater than b
Line 6 - a is either less than or equal to b
Line 7 - b is either greater than or equal to b

Logical Operators :
The logical operators and, or and not are also referred to as boolean operators.
While and as well as or operator needs two operands, which may evaluate to true or false, not
operator needs one operand evaluating to true or false.

Boolean and operator returns true if both operands return true.

>>> a=50
>>> b=25
>>> a>40 and b>40

>>> a>100 and b<50

>>> a==0 and b==0

>>> a>0 and b>0

Boolean or operator returns true if any one operand is true

>>> a=50
>>> b=25

18 | P a g e
>>> a>40 or b>40

>>> a>100 or b<50

>>> a==0 or b==0

>>> a>0 or b>0

The not operator returns true if its operand is a false expression and returns false if it is true.
>>> a=10
>>> a>10

>>> not(a>10)

Identity Operators:
Identity operators compare the memory locations of two objects.
There are two Identity operators as explained below –

Example:
a = 20
b = 20

if ( a is b ):
print "Line 1 - a and b have same identity"
else:
print "Line 1 - a and b do not have same identity"

if ( id(a) == id(b) ):
print "Line 2 - a and b have same identity"
else:
print "Line 2 - a and b do not have same identity"

b = 30
if ( a is b ):
print "Line 3 - a and b have same identity"
else:
print "Line 3 - a and b do not have same identity"

if ( a is not b ):
print "Line 4 - a and b do not have same identity"
else:
print "Line 4 - a and b have same identity"

Output:
19 | P a g e
Line 1 - a and b have same identity
Line 2 - a and b have same identity
Line 3 - a and b do not have same identity
Line 4 - a and b do not have same identity

Membership Test Operators:

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below −

Example:
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];

if ( a in list ):
print "Line 1 - a is available in the given list"
else:
print "Line 1 - a is not available in the given list"

if ( b not in list ):
print "Line 2 - b is not available in the given list"
else:
print "Line 2 - b is available in the given list"

a=2
if ( a in list ):
print "Line 3 - a is available in the given list"
else:
print "Line 3 - a is not available in the given list"

Output:
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list

Bitwise operators: these operators perform operations on binary (bit-level)


Representation of integers,
There are following Bitwise operators supported by Python language.

20 | P a g e
Example:
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c

c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c

c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c = ~a; # -61 = 1100 0011


print "Line 4 - Value of c is ", c

c = a << 2; # 240 = 1111 0000


print "Line 5 - Value of c is ", c

c = a >> 2; # 15 = 0000 1111


print "Line 6 - Value of c is ", c

Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

21 | P a g e
Statements:
A statement is an instruction that the Python interpreter can execute. We have normally
two basic statements, the assignment statement and the print statement.
Some other kinds of statements that are if statements, while statements, and for statements
generally called as control flows.

Examples:
An assignment statement creates new variables and gives them values: x=10
expression is evaluated.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first multiplies 3*2 and then adds into 7.

Example 1:
>>> 3+4*2 11
Multiplication gets evaluated before the addition operation
>>> (10+10)*2
40
Parentheses () overriding the precedence of the arithmetic operators

Example 2:
a = 20
b = 10
c = 15
d=5
e=0
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) e = a + (b * c) / d; # 20 + (150/5)
print("Value of a + (b * c) / d is ", e)

output

Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0

Precedence and Association:

 Precedence: Determines the order of operations in expressions.


 Association: Defines the direction in which operations are performed
(left-to-right or right-to-left).

Example:
result = 3 + 4 * 2 # result is 11 (multiplication has higher precedence)

22 | P a g e
Data Types:

Python 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. The following are the standard or built-in data
types in Python:

 Numeric – int, float, complex


 Sequence Type – string, list, tuple
 Mapping Type – dict
 Boolean – bool
 Set Type – set, frozenset
 Binary Types – bytes, bytearray, memoryview

a=5
print(type(a))

b = 5.0
print(type(b))

c = 2 + 4j
print(type(c))

Output:
<class 'int'>
<class 'float'>
<class 'complex'>

23 | P a g e
The data stored in memory can be of many types. For example, a student roll number is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python has
various standard data types that are used to define the operations possible on them and the
storage method for each of them.

Numeric Data Types in Python

 Integers – This value is represented by int class.


 Float – This value is represented by the float class.
 Complex Numbers – A complex number is represented by a complex class.
For example – 2+3j

 Int:

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10

24 | P a g e
>>> print(a)
10

# To verify the type of any object in Python, use the type() function:

>>> type(10)
<class 'int'>

>>> a=11
>>> print(type(a))
<class 'int'>

 Float:

Float, or "floating point number" is a number, positive or negative, containing one or more
decimals. Float can also be scientific numbers with an "e" to indicate the power of 10.

>>> y=2.8
>>> y 2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>

>>> type(.4)
<class 'float'>

>>> 2.
2.0

Example:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))

Output:
<class 'float'>
<class 'float'>
<class 'float'>

 Boolean:

Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>

25 | P a g e
>>> type(False)
<class 'bool'>

 String:

Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes.

 'hello' is the same as "hello".


 Strings can be output to screen using the print function. For example: print("hello").

>>> print("svc college") svc college


>>> type("svc college")
<class 'str'>
>>> print('svc college') svc college
>>> ""
''

If you want to include either type of quote character within the string, the simplest way is to
delimit the string with the other type. If a string is to contain a single quote, delimit it with
double quotes and vice versa:
>>> print("svc is an autonomous (') college") svc is an autonomous (') college
>>> print('svc is an autonomous (") college') svc is an autonomous (") college

Suppressing Special Character:

Specifying a backslash (\) in front of the quote character in a string “escapes” it and causes
Python to suppress its usual special meaning. It is then interpreted simply as a literal single
quote character:

>>> print("svc is an autonomous (\') college") svc is an autonomous (') college


>>> print('svc is an autonomous (\") college') svc is an autonomous (") college

The following is a table of escape sequences which cause Python to suppress the usual special
interpretation of a character in a string:
>>> print('a\ b')
ab
>>> print('a\b\c') abc
>>> print('a \n b') a b
>>> print("svc\n college") svc college

In Python (and almost all other common computer languages), a tab character can be specified
by the escape sequence \t:

26 | P a g e
>>> print("a\tb") a b

Python List Data Type

Python Lists are the most versatile compound data types. A Python list contains items
separated by commas and enclosed within square brackets ([]). To some extent, Python lists
are similar to arrays in C. One difference between them is that all the items belonging to a
Python list can be of different data type where as C array can store elements related to a
particular data type.

The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+)
sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example

list=['abcd', 786,2.23,'john',70.2]
tinylist =[123, 'john']
print (list) # Prints complete list
print (list[0])# Prints first element of the list
print (list[1:3])# Prints elements starting from 2 nd to 3rd
print (list[2:] print elements starting from 3rd element
print (tinylist * 2)# Prints list two times print (list+ tinylist) # Prints concatenated
lists

Output:
['abcd', 786, 2.23, 'john', 70.2]
abcds [786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuple Data Type
Python tuple is another sequence data type that is similar to a list. A Python tuple
consists of a number of values separated by commas. Unlike lists, however, tuples
are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought
of as read-only lists. For example –

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john')

print (tuple) # Prints the complete tuple

print (tuple[0]) # Prints first element of the tuple

27 | P a g e
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice

print (tuple + tinytuple) # Prints concatenated tuples

Output:

('abcd', 786, 2.23, 'john', 70.2)

abcd

(786, 2.23)

(2.23, 'john', 70.2)


(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

Python Dictionary

Python dictionaries are kind of hash table type. They work like associative arrays
or hashes found in Perl and consist of key-value pairs. A dictionary key can be
almost any Python type, but are usually numbers or strings. Values, on the other
hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]). For example

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'
print (dict['one']) # Prints value for 'one' key

print (dict[2]) # Prints value for 2 key


print (tinydict) # Prints complete dictionary

print ([Link]()) # Prints all the keys


print ([Link]()) # Prints all the values
Output:
This is one This is two

28 | P a g e
{'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name']
['sales', 6734, 'john']
Python dictionaries have no concept of order among elements. It is incorrect to
say that the elements are "out of order"; they are simply unordered

Escape Usual Interpretation of


Sequence Character(s) After Backslash “Escaped” Interpretation
\' Terminates string with single quote opening delimiter Literal single quote (') character
\" Terminates string with double quote opening delimiter Literal double quote (") character
\newline Terminates input line Newline is ignored
\\ Introduces escape sequence Literal backslash (\) character

Indentation:
 Definition: Whitespace at the beginning of a line that indicates a block of code.
 Importance: Indentation is crucial in Python; it defines the scope of loops,
functions, and conditional statements.
Example
if x > 0:
print("Positive")

Comments:
 Single-line Comments: Use # to comment a single line.
Example: # This is a comment
 Multi-line Comments: Use triple quotes (''' or """).

Example:

29 | P a g e
Built-in Functions:
 Console Input: Use input() to take user input.
Example:
name = input("Enter your name: ")
 Console Output: Use print() to display output.
Example:
print("Hello, " + name)

Python Type Conversions:

In programming, type conversion is the process of converting data of one type to


another. For example: converting int data to str.

Convert between types using built-in functions:


 int(): Converts to integer.
 float(): Converts to float.
 str(): Converts to string.

Example:
x = "10"
y = int(x) + 5 # y is now 15

There are two types of type conversion in Python.

• Implicit Conversion - automatic type conversion


• Explicit Conversion - manual type conversion

Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to another. This is known
as implicit type conversion.

Example:
x = 20
print("x type:",type(x) y = 0.6
print("y type:",type(y)) a = x + y
print(a)
print("z type:",type(z))

Output:
x type: <class 'int'>
y type: <class 'float' >20.6
a type: <class 'float'>

30 | P a g e
Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to


required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit
type conversion.
This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.

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

Output:
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'>

Python Libraries:

A Python library is a reusable chunk of code that you may want to include in our
programs/ projects.

Python Standard Library

The Python Standard Library is a collection of exact syntax, token, and


semantics of Python.

Examples:
 Pandas - This library is used for structured data operations, like
import CSV files, create dataframes, and data preparation

31 | P a g e
 Numpy - This is a mathematical library. Has a powerful
N-dimensional array object, linear algebra, Fourier
transform, etc.
 Matplotlib - This library is used for visualization of data.
 SciPy - This library has linear algebra modules

Importing Libraries:
We can import and use modules across different programs using keyword import.

Modules in the Python standard library need no installing and therefore importing them at the
top of our programs is enough to get started. A common example of such libraries is the math
library. The math library provides access to common mathematical functions. Using these
functions, we can perform various mathematical expressions such as finding the square root
of a number.
Using the keywords from…import we can import specific items from a library or module.
These may include functions or classes within that specific library. This is important
especially when you do not intend to use only a specific function in a module and therefore it
is needless to import the entire module.

Example:
1) # import standard math module import math
# use [Link] to get value of pi print("The value of pi is", [Link])

Output:
The value of pi is 3.141592653589793

2) # import only pi from math module from math import pi


print(pi)

Output:
3.141592653589793

Python Control Flow


Types of Control Flow:

Python supports the following types of control flow:


1. Sequential Flow: Statements are executed in the order they appear in the code.
2. Conditional Flow: Execution of code depends on certain conditions.
3. Iterative Flow: Execution of a block of code is repeated multiple times.

Control Flow Statements

32 | P a g e
1. if-else Statements
 if statement: Executes a block of code if a condition is true.
 else statement: Executes a block of code if the if condition is false.
 elif statement: Allows for multiple conditions to be checked.

if – elif – else Statement Flowchart:

Example:
x = 10
if x > 0:
print("Positive") elif x < 0:
print("Negative") else:
print("Zero")

1. while Loop
 Executes a block of code as long as a condition is true.
 Can be used to implement various types of loops, such as counting
loops, infinite loops, and nested loops.
 Loops are either infinite or conditional. Python while loop keeps
reiterating a block of code defined inside it until the desired condition
is met.
 The while loop contains a boolean expression and the code inside
the loop is repeatedly executed as long as the boolean expression is
true.
 The statements that are executed inside while can be a single line of code or
a block of multiple statements

33 | P a g e
Syntax:

while(expression):
Statement(s)

Flowchart

Example:
count = 0
while count < 5:
print(count)
count += 1

1. break Statement

 Terminates the current loop and transfers execution to the statement immediately
following the loop.
Example:
while True:
user_input = input("Enter a number (or 'q' to quit): ") if user_input == 'q':
break
print("You entered:", user_input)

2. continue Statement
 Skips the current iteration of the loop and moves to the next iteration.
Example:
for i in range(1, 11): if i % 2 == 0:
continue print(i)

34 | P a g e
[Link] Loop
 Iterates over the elements of a sequence (such as a list, tuple, or string).
 Can be used to implement various types of loops, such as counting
loops, iterating over collections, and nested loops.
Example:
fruits = ["apple",
"banana", "cherry"]
for fruit in fruits:
print(fruit)
Flowchart:

range() Function

 Generates a sequence of numbers.


 Can be used in for loops to iterate over a specific range of numbers.
The range () function has three types such as single parametric, two parametric
and three parametric.

Example 1: for Single parametric


for i in
range(5): #
range(upto)
print(i) #
Output:
0, 1, 2, 3, 4

Example 2: for Two parametric

35 | P a g e
for i in range(1,5):
#
range(start,upto)
print(i) #
Output: 1, 2,
3,4

Example 3: for Three parametric


for i in range(1,5,2): #
range(start,upto,step)
print(i) # Output: 1, 3
exit() Function

 Terminates the Python program and returns control to the operating system.

Example:
if user_input == 'q': # if user input is q then
terminate the execution. exit()

Below are clear, exam-ready Python notes on Arrays covering definition,


syntax, accessing elements, and array methods.

Arrays in Python

Definition of Array

An array is a data structure that stores multiple values of the same data type in a single
variable. Each value is stored at a specific index position.

In Python, arrays can be implemented using:


• List (most commonly used)
• array module (for strictly same data type)

Array Using List (Most Common in Python)

Syntax
array_name = [element1, element2, element3, ...]

Example
numbers = [10, 20, 30, 40, 50]

Accessing Elements of an Array


Indexing

36 | P a g e
• Index starts from 0
• Negative indexing starts from -1

numbers = [10, 20,30,40,50]

print(numbers[0]) #output: 10
print(numbers[2]) #output:30
print(numbers[-1]) #output: 50

Slicing

print(numbers[1:4]) # Output: [20, 30, 40]


print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[2:]) # Output: [30, 40, 50]

Modifying Array Elements

numbers[1] = 25

print(numbers)# [10, 25, 30, 40, 50]

Array Methods (List Methods)

append()
Adds an element at the end.
[Link](60)

insert()
Adds an element at a specified index. [Link](2, 15)

remove()
Removes a specific element. [Link](40)

pop()
Removes and returns element at given index.
[Link]() # Removes last element
[Link](1) # Removes element at index 1

index()
Returns index of an element. [Link](30)

count()
Counts occurrences of an element.
[Link](20)

37 | P a g e
sort()
Sorts the array in ascending order.
[Link]()

reverse()
Reverses the array.
[Link]()

clear()
Removes all elements.
[Link]()

Array Using array Module

Syntax

import array

arr = [Link]('i', [10, 20, 30, 40])

Common Type Codes


Code Data Type

i Integer

f Float

d Double

Accessing Elements

print(arr[1])

# Output: 20

Advantages of Arrays

 Stores multiple values efficiently


 Easy to access using index
 Saves memory compared to multiple variables

Disadvantages of Arrays

38 | P a g e
 Fixed size (in array module)
 Stores only same data type
 Insertion and deletion can be slow

39 | P a g e

You might also like