0% found this document useful (0 votes)
17 views27 pages

Introduction to Python Programming Basics

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)
17 views27 pages

Introduction to Python Programming Basics

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

UNIT-I
Basics of Python

Syllabus:

Introduction: History of Python, Need of Python Programming, Applications Basics of Python


Programming using the REPL(Shell), Running Python Scripts, Variables, Assignment, Keywords,
Input-Output, Indentation.
Types, Operators and Expressions: Types - Integers, Strings, Booleans; Operators- Arithmetic
Operators, Comparison (Relational) Operators, Assignment Operators, Logical Operators,
Bitwise Operators, Membership Operators, Identity Operators, Expressions and order of
evaluations Control Flow- if, if-elif-else, for, while, break, continue, pass.

Learning Outcomes:
At the end of this unit, the student will be able to
1. Understand the programming in Python using the REPL(Shell).
2. Categorize the types, operators and expressions in python programming.

Introduction:
Python is a widely used programming language that offers several unique features and
advantages compared to languages like Java and C++.
In the late 1980s, Guido van Rossum dreamed of developing Python. The first version
of Python 0.9.0 was released in 1991. Since its release, Python started gaining popularity.
According to reports, Python is now the most popular programming language among
developers because of its high demands in the tech realm.
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.
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.
• 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.
• 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 implement of Python known as CPython. CPython is considered to
be Complied and Interpreted both.
• Garbage Collected - Memory allocation and de-allocation 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.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 1


Python Programming

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

History of Python
Python was created by Guido van Rossum. In the late 1980s, Guido van Rossum, a Dutch
programmer, began working on Python while at the Centrum Wiskunde & Informatica (CWI) in
the Netherlands. He wanted to create a successor to the ABC programming language that
would be easy to read and efficient.
In February 1991, the first public version of Python, version 0.9.0, was released. This
marked the official birth of Python as an open-source project. The language was named after
the British comedy series "Monty Python's Flying Circus".

Why learn Python?


Python provides many useful features to the programmer. These features make it the most
popular and widely used language. We have listed below few-essential features of Python.
• Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike
traditional languages like C, C++, Java, etc., making it easy for beginners to learn.
• Expressive Language: It allows programmers to express complex concepts in just a few
lines of code or reduces Developer's Time.
• Interpreted Language: Python does not require compilation, allowing rapid
development and testing. It uses Interpreter instead of Compiler.
• Object-Oriented Language: It supports object-oriented programming, making writing
reusable and modular code easy.
• Open-Source Language: Python is open-source and free to use, distribute and modify.
• Extensible: Python can be extended with modules written in C, C++, or other languages.
• Learn Standard Library: Python's standard library contains many modules and
functions that can be used for various tasks, such as string manipulation, web
programming, and more.
• GUI Programming Support: Python provides several GUI frameworks, such
as Tkinter and PyQt, allowing developers to create desktop applications easily.
• Integrated: Python can easily integrate with other languages and technologies, such as
C/C++, Java, and . NET.
• Embeddable: Python code can be embedded into other applications as a scripting
language.
• Dynamic Memory Allocation: Python automatically manages memory allocation,
making it easier for developers to write complex programs without worrying about
memory management.
• Wide Range of Libraries and Frameworks: Python has a vast collection of libraries
and frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a
wide range of problems.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 2


Python Programming

• Versatility: Python is a universal language in various domains such as web


development, machine learning, data analysis, scientific computing, and more.
• Large Community: Python has a vast and active community of developers contributing
to its development and offering support. This makes it easy for beginners to get help and
learn from experienced developers.
• Career Opportunities: Python is a highly popular language in the job market. Learning
Python can open up several career opportunities in data science, artificial intelligence,
web development, and more.
• High Demand: With the growing demand for automation and digital transformation,
the need for Python developers is rising. Many industries seek skilled Python developers
to help build their digital infrastructure.
• Increased Productivity: Python has a simple syntax and powerful libraries that can
help developers write code faster and more efficiently. This can increase productivity
and save time for developers and organizations.
• Big Data and Machine Learning: Python has become the go-to language for big data
and machine learning. Python has become popular among data scientists and machine
learning engineers with libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and
more.
Where is Python used?
Python is a general-purpose, popular programming language, and it is used in almost every
technical field. The various areas of Python use are given below.
• 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.
• Mobile Applications: While Python is not commonly used for creating mobile
applications, it can still be combined with frameworks like Kivy or BeeWare to create
cross-platform mobile applications.
• 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 HTML and CSS.
• Enterprise Applications: Python can be used to develop large-scale enterprise
applications with features such as distributed computing, networking, and parallel
processing.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 3


Python Programming

• 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.
• Speech Recognition: Python can be used for speech recognition applications through
libraries such as SpeechRecognition and PyAudio.
• Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced
numerical computing capabilities for tasks like data analysis, machine learning, and
more.
• Education: Python's easy-to-learn syntax and availability of many resources make it an
ideal language for teaching programming to beginners.
• Testing: Python is used for writing automated tests, providing frameworks like unit
tests and pytest that help write test cases and generate reports.
• Gaming: Python has libraries like Pygame, which provide a platform for developing
games using Python.
• IoT: Python is used in IoT for developing scripts and applications for devices
like Raspberry Pi, Arduino, and others.
• Networking: Python is used in networking for developing scripts and applications for
network automation, monitoring, and management.
• DevOps: Python is widely used in DevOps for automation and scripting of infrastructure
management, configuration management, and deployment processes.
• Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial
modeling and analysis.
• Audio and Music: Python has libraries like Pyaudio, which is used for audio processing,
synthesis, and analysis, and Music21, which is used for music analysis and generation.
• Writing scripts: Python is used for writing utility scripts to automate tasks like file
operations, web scraping, and data processing.
Python Popular Frameworks and Libraries
Python has wide range of libraries and frameworks widely used in various fields such as
machine learning, artificial intelligence, web applications, etc. We define some popular
frameworks and libraries of Python as follows.
• Web development (Server-side) - Django Flask, Pyramid, CherryPy
• GUIs based applications - Tkinter, PyGTK, PyQt, PyJs, etc.
• Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
• Mathematics - NumPy, Pandas, etc.
• BeautifulSoup: a library for web scraping and parsing HTML and XML
• Requests: a library for making HTTP requests
• SQLAlchemy: a library for working with SQL databases
• Kivy: a framework for building multi-touch applications
• Pygame: a library for game development
• Pytest: a testing framework for Python Django
• REST framework: a toolkit for building RESTful APIs

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 4


Python Programming

• FastAPI: a modern, fast web framework for building APIs


• Streamlit: a library for building interactive web apps for machine learning and data
science
• NLTK: a library for natural language processing

Using the REPL (Shell)


Python Interpreter: Shell/REPL
Python is an interpreter language. It means it executes the code line by line. Python provides a
Python Shell, which is used to execute a single Python command and display the result. It is also
known as REPL (Read, Evaluate, Print, Loop), where it reads the command, evaluates the
command, prints the result, and loop it back to read the command again.
To run the Python Shell, open the command prompt or power shell on Windows or terminal
window on mac, write python and press enter. A Python Prompt comprising of three greater-
than symbols >>> appears, as shown below.

Now, you can enter a single statement and get the result. For example, enter a simple expression
like 3 + 2, press enter and it will display the result in the next line, as shown below.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 5


Python Programming

Python Variables
A variable is the name given to a memory location. Since Python is an infer language that is
smart enough to determine the type of a variable, we do not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both
letters and digits. The name of the variable should be written in lowercase. Python is case-
sensitive language.

Rules to be followed for using variables:


• The variable's first character must be an underscore or alphabet (_).
• White space and special characters (!, @, #, %, etc.) are not allowed in the identifier
name.
• Names of identifiers are case-sensitive; for instance, myname, and MyName isn't similar.
• Examples of valid identifiers: a123, _n, n_9, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values


• In Python, we don't have to explicitly declare variables. The variable is declared
automatically whenever a value is added to it.
• The equal (=) operator is utilized to assign worth to a variable.

The multi-word keywords can be created by the following method.


Camel Case - In the camel case, each word or abbreviation in the middle of begins with a
capital letter. There is no intervention of whitespace.
Example: nameOfStudent, valueOfVaraible, etc.
Pascal Case - It is the same as the Camel Case, but here the first word is also capital.
Example: NameOfStudent, etc.
Snake Case - In the snake case, Words are separated by the underscore.
Example: name_of_student, etc.
Determining the type of a variable

The function type() is used to know the data type of a variable.

Ex:1 Ex:2
type(“SRIT”) type(252)
Output: <class 'str'> Output: <class 'int'>

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 6


Python Programming

Multiple Assignment

Multiple assignments, also known as assigning values to multiple variables in a single statement,
is a feature of Python.

1. Assigning single value to multiple variables


Ex: x=y=z=50

2. Assigning multiple values to multiple variables:

Ex: a, b, c = 5,10,15
The values will be assigned in the order in which variables appear.

Comments in Python

Comments are textual descriptions that are ignored by python interpreter. Python supports
three style of comments

• Single-line Comments
• Multi-line Comments
• Documentation Strings

Single-Line Comments

A single-line comment of Python is the one that has a hashtag # at the beginning of it and
continues until the finish of the line. If the comment continues to the next line, add a hashtag to
the subsequent line.

Ex: # This is python programming single-line comment

Multi-Line Comments

Python does not provide the facility for multi-line comments. In Python, we may use hashtags
(#) multiple times to construct multiple lines of comments.

Documentation Strings (Docstrings)

The strings enclosed in triple quotes that come immediately after the defined function are called
Python docstring. It's designed to link documentation developed for Python modules, methods,
classes, and functions together. It's placed just beneath the function, module, or class to explain
what they perform. The docstring is then readily accessible in Python using the __doc__
attribute.

Ex: “”” This is a documentation string “””

Python Keywords

Every scripting language has designated words or keywords, with particular definitions and
usage guidelines. Python is no exception. The fundamental constituent elements of any Python
program are Python keywords.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 7


Python Programming

Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions.

The following table shows some keywords for the reference, some keywords are added or
deleted according to the versions.

FALSE class from or

None continue global pass

TRUE def if raise

and del import return

as elif in try

assert else is while

async except lambda with

await finally nonlocal yield

break for not

How to Identify Python Keywords

To retrieve the collection of keywords in the version you are working on.

Import keyword

print([Link])

OR

By calling help(), you can retrieve a list of currently offered keywords:

help(“keywords”)

Input and Output in Python

In this we will see different ways of reading input from the user and displaying output to the
user

How to Take Input from User in Python

The input() function is used to take user input at some point in the program.

Syntax:

import(‘prompt’)

Here prompt is an optional string that is displayed on the string at the time of taking input.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 8


Python Programming

How to Display Output in Python

Python provides the print() function to display output to the standard output devices.

Syntax:

print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)

Parameters:
value(s): Any value, and as many as you like. Will be converted to string before printed
sep=’separator’: (Optional) Specify how to separate the objects, if there is more than one.
Default :’ ‘
end=’end’: (Optional) Specify what to print at the end. Default : ‘\n’
file : (Optional) An object with a write method. Default :[Link]
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False

Example 1: Python script to get user input and display with a message

# Taking input from the user


name = input("Enter your department name: ")
# Output
print("Hello, " + name)
print(type(name))
Output:
Enter your department name: CSD
Hello, CSD
<class 'str'>

Example 2: Reading integer input in Python

Python takes all the input as a string input by default. To convert it to any other data type we
have to convert the input explicitly. For example, to convert the input to int or float we have to
use the int() and float() method respectively.

# Taking input from the user as integer


num = int(input("Enter a number: "))

add = num + 1

# Output
print(add)

Output:
Enter a number: 45
46

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 9


Python Programming

How to take Multiple Inputs in Python:

We can take multiple inputs of the same data type at a time in python, using map() method in
python.

# splitting the integers using split() method and mapped to 3


variables.
a, b, c = map(int, input("Enter the Numbers : ").split())
print("The Numbers are : ",end = " ")
print(a, b, c)
Output :

Enter the Numbers : 2 3 4


The Numbers are : 2 3 4

Example: Python Print Output

# Python program to demonstrate


# print() method
print("Programming")

# code for disabling the softspace feature


print(“Programming”, “Language”)

Output:

Programming
Programming Language

Example: Python Print output with custom sep and end parameter

# Python program to demonstrate print() method


print("Python", end = "@")

# code for disabling the softspace feature


print('P', 'y', 't', ‘h’, ‘o’, ‘n’, sep="#")

Output:
Python@P#y#t#h#o#n

Python Indentation

Indentation is a very important concept of Python because without properly indenting the
Python code, you will end up seeing IndentationError and the code will not get compiled.

Python indentation refers to adding white space before a statement to a particular block of code.
In another word, all the statements with the same space to the right, belong to the same code
block.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 10


Python Programming

Python indentation is a way of telling a Python interpreter that the group of statements belongs
to a particular block of code. A block is a combination of all these statements. Block can be
regarded as the grouping of statements for a specific purpose. Most programming languages
like C, C++, and Java use braces { } to define a block of code.

Whitespace is used for indentation in Python. All statements with the same distance to the right
belong to the same block of code. If a block has to be more deeply nested, it is simply indented
further to the right.

Example:

Animals
--------- Domestic Animals
------------------- Cat
------------------- Dog
---------- Wild Animals
------------------- Tiger
------------------- Lion
------------------- Deer

Python Data Types

A variable can contain a variety of values. The following is a list of the Python-defined data
types.

• Numbers
• Sequence Type
• Boolean
• Set
• Dictionary

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 11


Python Programming

Numbers

Numeric values are stored in numbers. The whole number, float, and complex qualities have a
place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. When a number is assigned to a variable, Python generates Number
objects.
Python supports three kinds of numerical data.

• int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so
on.
• float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to
within 15 decimal places.
• complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify
the real and imaginary parts separately. The complex numbers like 2.14j, 2.0 + 2.3j, etc.

Example:
a=5
print("The type of a", type(a))

b = 40.5
print("The type of b", type(b))

c = 1+3j
print("The type of c", type(c))

Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
Boolean

True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or invalid. The class bool indicates this. False can be
represented by the 0 or the letter "F," while true can be represented by any value that is non-
zero.

Example:

# Python program to check the boolean type


print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 12


Python Programming

Sequence Type

There are 3 types of sequence types


• String
• List
• Tuple

Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the
curly braces and separated by a comma to create the set or the built-in function set() is used to
create the set. It can contain different kinds of values.

Operators in Python

The operator is a symbol that performs a specific operation between two operands, according to
one definition. Python has some operators, and these are given below –

• Arithmetic operators
• Comparison operators (Relational Operators)
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators

Arithmetic Operators

Arithmetic operators used between two operands for a particular operation. It includes the
exponent (**), + (addition), - (subtraction), * (multiplication), / (divide), % (reminder), and //
(floor division) operators.

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description
It is used to add two operands.
+ (Addition)
For example, if a = 10, b = 10 => a+b = 20
It is used to subtract the second operand from the first operand.
- (Subtraction)
For example, if a = 20, b = 5 => a - b = 15
It returns the quotient after dividing the first operand by the second operand.
/ (divide)
For example, if a = 25, b = 2 => a/b = 12.5
It is used to multiply one operand with the other.
* (Multiplication)
For example, if a = 20, b = 4 => a * b = 80
It returns the reminder after dividing the first operand by the second
% (reminder) operand.
For example, if a = 20, b = 10 => a%b = 0

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 13


Python Programming

It calculates the first operand's power to the second operand, it is an


** (Exponent) exponent operator.
For example, if a = 4, b = 2 => a**b = 16
It provides the quotient's floor value, which is obtained by dividing the two
// (Floor division) operands.
For example, if a = 25, b = 12 => a//b = 2

Write a python script to illustrate Arithmetic operators in python.

Source Code:

a = int(input(“Enter first number:”))


b = int(input(“Enter second number:”))
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:

Enter first number: 25


Enter first number: 2
Addition of two numbers: 27
Subtraction of two numbers: 23
Multiplication of two numbers: 50
Division of two numbers: 12.5
Reminder of two numbers: 1
Exponent of two numbers: 625
Floor division of two numbers: 12

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 14


Python Programming

Comparison operators (Relational Operators)

Comparison operators mainly use for comparison purposes. Comparison operators compare the
values of the two operands and return a true or false Boolean value.
Consider the following table for a detailed explanation of comparison operators.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

The condition is met if the first operand is smaller than or equal to the
<=
second operand.
The condition is met if the first operand is greater than or equal to the
>=
second operand.
If the first operand is greater than the second operand, then the condition
>
becomes true.
If the first operand is less than the second operand, then the condition
<
becomes true.

Write a python script to illustrate comparison operators in python.

Source Code:
a = int(input(“Enter first number:”))
b = int(input(“Enter Second number:”))
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:
Enter first number: 32
Enter first number: 6
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

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 15


Python Programming

Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand.
There are some examples of assignment operators like =, +=, -=, *=, %=, **=, //=.
Consider the following table for a detailed explanation of assignment operators.

Operator Description
It assigns the value of the right expression to the left operand.
=
For example, a = 10
By adding the value of the right operand to 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.

Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of
Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift
(<<), and Right shift (>>). Consider the case below.

Operator Description
A 1 is copied to the result if both bits in two operands at the same location
& (binary and)
are 1. If not, 0 is copied.
The resulting bit will be 0 if both the bits are zero; otherwise, the resulting
| (binary or)
bit will be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
The operand's bits are calculated as their negations, so if one bit is 0, it will
~ (negation)
change to 1, and vice versa.
The left operand is moved left by the number of shifts given in the right
<< (left shift)
operand.
The left operand is moved right by the number of shifts given in the right
>> (right shift)
operand.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 16


Python Programming

Logical Operators

The assessment of expressions to make decisions typically uses logical operators. The
examples of logical operators are and, or, and not. Python supports the following logical
operators. Consider the following table for a detailed explanation of logical operators.

Operator Description

and The condition will be True, if both expressions are True only.

or The condition will be true if at least one expression is True.

not If an expression is true, then not (a) will be false and vice versa.

Membership Operators

The membership of a value inside a Python data structure can be verified using Python
membership operators. The result is true if the value is in the data structure; otherwise, it
returns false.

Operator Description
If the first operand is a member of the second operand, it is evaluated to be true
in
(list, tuple, or dictionary).
If the first operand is not a member of the second operand, the evaluation is
not in
true (list, tuple, or dictionary).

Write a python script to illustrate membership operators.

Source Code:
fruits = [“Apple”, “Mango”, “Banana”]
print("Orange" in fruits)
print("Orange" not in fruits)
print("Mango" in fruits)
print("Mango" not in fruits)

Output:

False
True
True
False

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 17


Python Programming

Identity Operators

These operators are used to compare the references to an object.

Operator Description
If the references on both sides point to the same object, it is determined to
is
be true.
If the references on both sides do not point at the same object, it is
is not
determined to be true.

Write a python script to illustrate identity operators.

Source Code:
names1 = ["Raju","Ravi","Rani"]
names2 = ["Raju","Ravi","Rani"]
names3 = names1
print(names3 is names1)
print(names1 is names2)
print(names1 is not names2)
print(names3 is not names1)

Output:
True
False
True
False

Control Statements in Python


Decision making is the most important aspect in all programming languages, it allows us to run
a particular block of code for a particular decision. The decisions are made on the validity of the
particular conditions.

In python, decision making is performed by the following statements.

Statement Description
The if statement is used to test a specific condition. If the condition is
if Statement
true, a block of code (if-block) will be executed.
The if-else statement is similar to if statement except that, it also
provides the block of the code for the false case of the condition to be
if - else
Statement checked. If the condition provided in the if statement is false, then the
else statement will be executed.
Nested if statements enable us to use if - else statement inside an
Nested if
statement outer if statement.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 18


Python Programming

Indentation in Python

For the ease of programming, python doesn't allow the use of parentheses for the block level
code. It is the most used part of the python language since it declares the block of code. All the
statements of one block are intended at the same level indentation.
The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.

The syntax of the if-statement is given below.


if expression:
statement

Example 1:
# Simple Python program to understand the if statement
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
Output:
enter the number: 10
The Given number is an even number

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 19


Python Programming

Example 2: Program to print the largest of the three numbers.


a = int (input("Enter a: "))
b = int (input("Enter b: "))
c = int (input("Enter c: "))
if a>b and a>c:
print ("From the above three numbers given a is largest")
if b>a and b>c:
print ("From the above three numbers given b is largest")
if c>a and c>b:
print ("From the above three numbers given c is largest")
Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition. If the condition is true, then the if-block is executed.
Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.


if condition:
#block of statements
else:
#another block of statements (else-block)

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 20


Python Programming

Example 1 : Program to check whether a person is eligible to vote or not.


age = int (input("Enter your age: "))
if age>=18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!")
Output:
Enter your age: 90
You are eligible to vote !!
Example 2: Program to check whether a number is even or not.
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
else:
print("The Given Number is an odd number")
Output:
enter the number: 10
The Given number is even number

The elif statement


The elif statement enables us to check multiple conditions and execute the specific block
of statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional. The elif
statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.

The syntax of the elif statement is given below.

if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 21


Python Programming

Example 1
number = int(input("Enter the number?"))
if number==10:
print("The given number is equals to 10")
elif number==50:
print("The given number is equal to 50")
elif number==100:
print("The given number is equal to 100")
else:
print("The given number is not equal to 10, 50 or 100")
Output:
Enter the number?15
The given number is not equal to 10, 50 or 100
Example 2
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 22


Python Programming

print("You scored grade B ...")


elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")
Output:
Enter the marks? 89
Congrats ! you scored grade A ...

Looping Statements in Python

The following looping statements are available in the Python programming language.
S. No. Name of the loop Loop Type & Description
Repeats a statement or group of statements while a given
1 while loop condition is TRUE. It tests the condition before executing the
loop body.
This type of loop executes a code block multiple times and
2 for loop
abbreviates the code that manages the loop variable.
3 Nested loops We can iterate a loop inside another loop.

Loop Control Statements

Statements used to control loops and change the course of iteration are called control
statements.
Python provides the following loop control statements.

Name of the
S. No. Description
control statement

This command terminates the loop's execution and transfers


1 break statement
the program's control to the statement next to the loop.

This command skips the current iteration of the loop. The


2 continue statement statements following the continue statement are not executed
once the Python interpreter reaches the continue statement.

The pass statement is used when a statement is syntactically


3 pass statement
necessary, but no code is to be executed.

The for Loop


Python's for loop is designed to repeatedly execute a code block while iterating through
a list, tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence
is known as iteration.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 23


Python Programming

Syntax of the for Loop

for value in sequence:


body of the loop

In this case, the variable value is used to hold the value of every item present in the sequence
before the iteration begins until this particular iteration is completed. Loop iterates until the
final item of the sequence are reached.
Code
# Python program to show how the for loop works
numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
square = 0
squares = []
for value in numbers:
square = value ** 2
squares. append(square)
print("The list of squares is", squares)

Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

The range() Function


With the help of the range() function, we may produce a series of numbers.
range(10) will produce values between 0 and 9. (10 numbers).
We can give specific start, stop and step size values in the manner range(start, stop, step size). If
the step size is not specified, it defaults to 1.

Code
# Python program to show the working of range() function
print(list(range(15)))
print(list(range(4, 9)))
print(list(range(5, 25, 4)))

Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 24


Python Programming

To iterate through a sequence of items, we can apply the range() method in for loops. We can
use indexing to iterate through the given sequence by combining it with an iterable's len()
function.
Code
# Python program to iterate over a sequence with the help of indexing
tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
# iterating over tuple_ using range() function
for iterator in range(len(tuple_)):
print(tuple_[iterator].upper())
Output:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
While Loop
While loops are used in Python to iterate until a specified condition is met. The while loop is
terminated once the condition changes to false.
Syntax of the while loop is:
while <condition>:
{ code block }
Code
# Python program to show how to use a while loop
counter = 0
# Initiating the loop
while counter < 10: # giving the condition
counter = counter + 3
print("Python Loops")
Output:
Python Loops
Python Loops
Python Loops
Python Loops

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 25


Python Programming

Loop Control Statements


continue statement
It returns the control to the beginning of the loop. It is used to skip the selected iterations and
continues the execution of remaining iterations.
Code
# Python program to show how the continue statement works
# Initiating the loop
for string in "Python Loops":
if string == "o" or string == "p" or string == "t":
continue
print('Current Letter:', string)
Output:
Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s
Break Statement
It is used to terminate the loop abnormally.
Code
# Python program to show how the break statement works
# Initiating the loop
for string in "Python Loops":
if string == 'L':
break
print('Current Letter: ', string)
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 26


Python Programming

pass statement
Pass statements are used to create empty loops. Pass statement is also employed for classes,
functions, and empty control statements.
Code
# Python program to show how the pass statement works
for string in "Python Loops":
pass
print( 'Last Letter:', string)
Output:
Last Letter: s

*****

Srinivasa Ramanujan Institute of Technology, Ananthapuramu Page 27

You might also like