0% found this document useful (0 votes)
30 views

Python UNIT1&2 24

Uploaded by

Shiva Prasanna
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)
30 views

Python UNIT1&2 24

Uploaded by

Shiva Prasanna
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
You are on page 1/ 50

UNIT-I

Introduction to Python: History, Features, Applications, First Python Program, Variables, Data
Types, Numbers, Operators, Input and Output statements, inbuilt functions

Introduction to Python:

• Python is a widely used general-purpose, high-level programming language.

History:

• Python was initially designed by Guido van Rossum in 1991 and developed by Python Software
Foundation.
• It was mainly developed for emphasis on code readability, and its syntax allows programmers to
express concepts in fewer lines of code.
• Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol- 68,
SmallTalk, and Unix shell and other scripting languages.
• Like Perl, Python source code is now available under the GNU General Public License (GPL).

Features:

Python provides many useful features which make it popular and valuable from the other
programming languages.

1) Easy to Learn and Use

Python is easy to learn as compared to other programming languages. Its syntax is straightforward
and much the same as the English language. There is no use of the semicolon or curly-bracket, the
indentation defines the code block. It is the recommended programming language for beginners.

2) Expressive Language

Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java
or C takes multiple lines.

3) Interpreted Language

Python is an interpreted language; it means the Python program is executed one line at a time. The
advantage of being interpreted language, it makes debugging easy and portable.

[Type here]
4) Cross-platform Language

Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh,
etc. So, we can say that Python is a portable language. It enables programmers to develop the
software for several competing platforms by writing a program only once.

5) Free and Open Source

Python is freely available for everyone. It is freely available on its official website
www.python.org. It has a large community across the world that is dedicatedly working towards
make new python modules and functions. Anyone can contribute to the Python community. The
open-source means, "Anyone can download its source code without paying any penny."

6) Object-Oriented Language

Python supports object-oriented language and concepts of classes and objects come into existence.
It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps
to programmer to write reusable code and develop applications in less code.

7) Extensible

It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in our Python code. It converts the program into byte code, and any platform can use
that byte code.

8) Large Standard Library

It provides a vast range of libraries for the various fields such as machine learning, web developer,
and also for the scripting. There are various machine learning libraries, such as Tensor flow,
Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for
Python web development.

9) GUI Programming Support

Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application.

10) Integrated

It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by
line like Java. It makes easy to debug the code.

11) Embeddable

The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language into

[Type here]
our code.

[Type here]
Applications:

Python is known for its general-purpose nature that makes it applicable in almost every domain
of software development. Python makes its presence in every emerging field. It is the fastest-
growing programming language and can develop any application.

Here, we are specifying application areas where Python can be applied.

1) Web Applications

We can use Python to develop web applications. It provides libraries to handle internet protocols
such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One
of Python web-framework named Django is used on Instagram. Python provides many useful
frameworks, and these are given below:

• Django and Pyramid framework(Use for heavy applications)


• Flask and Bottle (Micro-framework)
• Plone and Django CMS (Advance Content management)

[Type here]
2) Desktop GUI Applications

The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface. Some popular GUI
libraries are given below.

• Tkinter or Tk
• wxWidgetM
• Kivy (used for writing multitouch applications )
• PyQt or Pyside

3) Console-based Application

Console-based applications run from the command-line or shell. These applications are computer
program which are used commands to execute. This kind of application was more popular in the
old generation of computers. Python can develop this kind of application very effectively. It is
famous for having REPL, which means the Read-Eval-Print Loop that makes it the most suitable
language for the command-line applications.

Python provides many free library or module which helps to build the command-line apps. The
necessary IO libraries are used to read and write. It helps to parse argument and create console
help text out-of-the-box. There are also advance libraries that can develop independent console
apps.

4) Software Development

Python is useful for the software development process. It works as a support language and can be
used to build control and management, testing, etc.

• SCons is used to build control.


• Buildbot and Apache Gumps are used for automated continuous compilation and testing.
• Round or Trac for bug tracking and project management.

5) Scientific and Numeric

This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.

Implementing machine learning algorithms require complex mathematical calculation. Python has
many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc. If you
have some basic knowledge of Python, you need to import libraries on the top of the code. Few
popular frameworks of machine libraries are given below.

• SciPy

[Type here]
• Scikit-learn

[Type here]
• NumPy
• Pandas
• Matplotlib

6) Business Applications

Business Applications differ from standard applications. E-commerce and ERP are an example
of a business application. This kind of application requires extensively, scalability and readability,
and Python provides all these features.

Oddo is an example of the all-in-one Python-based application which offers a range of business
applications. Python provides a Tryton platform which is used to develop the business application.

7) Audio or Video-based Applications

Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. The
few multimedia libraries are given below.

• Gstreamer
• Pyglet
• QT Phonon

8) 3D CAD Applications

The CAD (Computer-aided design) is used to design engineering related architecture. It is used
to develop the 3D representation of a part of a system. Python can create a 3D CAD application
by using the following functionalities.

• Fandango (Popular )
• CAMVOX
• HeeksCNC
• AnyCAD
• RCAM

9) Enterprise Applications

Python can be used to create applications that can be used within an Enterprise or an Organization.
Some real-time applications are OpenERP, Tryton, Picalo, etc.

10) Image Processing Application

Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements. Some libraries of image processing are given below.

• OpenCV

[Type here]
• Pillow
• SimpleITK
The future of python
Python has huge user base that is constantly growing.it is the most preferred language of
companies ,such as Nokia,Google, and youtube,as well as NASA for its easy syntax.
It has bright future ahead of it supported by a huge community of OS developers.
Python is a high-speed dynamic language therefore it works well in applications like photo
development and has been embedded in programs such as GIMP and paint shop pro.

First Python Program

Python provides us the two ways to run a program:

• Using Interactive interpreter prompt


• Using a script file

Interactive interpreter prompt

• Python provides us the feature to execute the Python statement one by one at the interactive
prompt.
• It is preferable in the case where we are concerned about the output of each line of our Python
program.
• To open the interactive mode, open the terminal (or command prompt) and type python.
• After writing the print statement, press the Enter key.

Using a script file (Script Mode Programming)


• Using the script mode, we can write multiple lines code into a file which can be executed later.
• For this purpose, we need to open an editor like notepad, create a file named and save it with .py
extension, which stands for "Python".

Step - 1: Open the Python interactive shell, and click "File" then choose "New", it will open a
new blank script in which we can write our code.
[Type here]
Step -2: Now, write the code and press "Ctrl+S" to save the file.

Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It will display
the output to the shell.

Multi-line Statements
Multi-line statements are written into the notepad like an editor and saved it with .py extension. In
the following example, we have defined the execution of the multiple code lines using the Python
script.

Script: multiline.py

name = "Deepika"

branch = "AI & ML"

age = "32"

print("My name is: ", name ) print("My branch is : ", branch) print("My age is: ", age)

Output:
My name is: Deepika My branch is : AI & ML My age is: 32

Variables and Identifiers

• Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value.
• In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.
• Variable names can be a group of both the letters and digits, but they have to begin with a letter
or an underscore.
• It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.

Identifier Naming

Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.

• The first character of the variable must be an alphabet or underscore ( _ ).


• All the characters except the first character may be an alphabet of lower-case(a-z), upper- case
(A-Z), underscore, or digit (0-9).
• Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,*).

[Type here]
• Identifier name must not be similar to any keyword defined in the language.
• Identifier names are case sensitive; for example, my name, and MyName is not the same.
• Examples of valid identifiers: a123, _n, n_9, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.

Example:

name = "Devansh" age = 20


marks = 80.50 print(name) print(age) print(marks)

Output:

Devansh 20
80.5

Multiple Assignment

Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.

We can apply multiple assignments in two ways, either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Consider the following example.

1. Assigning single value to multiple variables Example:

x=y=z=50 print(x) print(y)

print(z)

Output:

50

50

[Type here]
50

2. Assigning multiple values to multiple variables:

Example:

a,b,c=5,10,15

print a print b print c Output:

10

15
Keywords:

And,assert,break,class,continue,def,del,elif,else,except,exec,finally,for,from,global,if,import,
in,is,lambda,not,or,pass,print,raise,return,try,while,with,yield.

Comments in python
Comments are non-executable statements in a program.they are just added to describe the
statements in the program code.
Program on comments:
# this is a comment
Print(“hello”)# to display hello
#program ends here
o/p
hello
Indentation:
Whitespace at the beginning of the line is called indentation. These whitespaces or
indentation is very important in python.in python indentation is used to associate and group
statements.
Program to show indentation errors.the level of indentation groups statements to form a
block of statements.this means that statements in a block must have the same indentation
level.
Age=21
Print(“you can vote”)#error-tab at the start of the line

Input and Output in Python


In Python, input and output operations (OI Operations) are performed using two
built-in functions. Following are the two built-in functions to perform output
operations and input operations.

• print( ) - Used for output operation.

[Type here]
• input( ) - Used for input operations.

Output Operations using print() function


The built-in function print( ) is used to output the given data to the standard output
device (Screen).

Displaying a message using print( ) function


In Python, using the print( ) function we can display a text message. The print( ) takes
a string as an argument and displays the same.
Example:

print('This message is displayed on the screen')


print("This message is also displayed on the screen")

When we use the print( ) function to display a message, the string can be enclosed
either in the single quotation or double quotation.

Displaying a variable value using print( ) function


In Python, the built-in function print( ) function is also used to display variables value.
The following example shows that how to display variable value using print( )
function.
Example:
num1 = 10 #variale num1 with value 10

print(num1)

#Output : 10

In the above example, we have created a variable num1 with a value 10. The value of
the variable num1 is displayed using the print( ) function.

Python print() with end Parameter

# print with end whitespace


print('Good Morning!', end= ' ')

[Type here]
print('It is tuesday ')
output:
Good Morning! It is tuesday

Python print() with sep parameter


print('New Year', 2023, 'See you soon!', sep= '. ')
New Year.2023.See you soon

Print Concatenated Strings


print('Programming is ' + 'awesome.')
output:
Programming is awesome

Here,

• the + operator joins two strings 'Programming is ' and 'awesome.'

• the print() function prints the joined string

Output formatting
Sometimes we would like to format our output to make it look attractive. This
can be done by using the str.format() method. For example,
• x=5
• y = 10

• print('The value of x is {} and y is {}'.format(x,y))


Here, the curly braces {} are used as placeholders. We can specify the order
in which they are printed by using numbers (tuple index).
To learn more about formatting the output, visit

[Type here]
# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers


sum = num1 + num2

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

The sum of 2 and 3 is 5

Input Operations using input() function


The Python provides a built-in function input( ) to perform input operations. The
input( ) function can be used either with some message or without a message.

When input( ) function is used without a message, it simply prompts for the input
value. When the user enters the input value it reads the entered value as a string
and assigns it to the left-hand-side variable.
Example

number_1 = input()
print('The number you have entered is {number_1}')

When we run the above piece of code, in the output screen simply it waits for the
user input without displaying anything.
When input( ) function is used with a message, it prompts with a given message for
the input value. When the user enters the input value it reads the entered value as a
string and assigns it to the left-hand-side variable.
# using input() to take user input

[Type here]
num = input('Enter a number: ')

print('You Entered:', num)

print('Data type of num:', type(num))


Enter a number: 10

In the above example, we have used the input() function to take input from the
user and stored the user input in the num variable.
It is important to note that the entered value 10 is a string, not a number.
So, type(num) returns <class 'str'> .

To convert user input into a number we can use int() or float() functions as:
Num = int(input(enter anumber))
Here, the data type of the user input is converted from string to integer .

Always the input( ) function reads input value as string value only.
To read the value of any other data type, there is no input function in Python.
Explicitly we need to convert to the required data type using type casting.

Data Types:
Variables can hold values, and every value has a data-type. Python is a dynamically typed
language; hence we do not need to define the type of the variable while declaring it. The interpreter
implicitly binds the value with its type.
Ex:
a=5
Python interpreter will automatically interpret variabl
es a as an integer type.
• Python enables us to check the type of the variable used in the program.
• Python provides us the type() function, which returns the type of the variable passed.
Ex:
a=10
b="Hi Python" c = 10.5

print(type(a)) print(type(b)) print(type(c))

[Type here]
Output:
<type 'int'>
<type 'str'>
<type 'float'>

Standard Datatypes:
• Python provides various standard data types that define the storage method on each of them.
• The data types defined in Python are given below.
• Numbers
• String
• list
• Tuple
• Dictionary

Numbers:(Int, Float, Complex)

• In Python, there are four types of numbers that can be assigned to a variable given as follows
• Int (signed Integer object) : they are the negative or non-negative numbers with no decimal
point. There is no limit on an integer in python. However, the size of the integer is constrained by
the amount of the memory our system has.
• float (floating point numbers) : The float type is used to store the decimal point (floating point)
numbers.
• Complex (complex numbers): Complex numbers are of the form a+bj where a is the real part of
the number and bj is the imaginary part of the number. It is not as much used in the
programming.

Program:

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

[Type here]
String

• The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.
• String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations on strings.
• In the case of string handling, the operator + is used to concatenate two strings as the operation
"hello"+" python" returns "hello python".
• The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.

Program:

str = "string using double quotes" print(str)

s = '''''A multiline string'''''

print(s)

Output:

string using double quotes A multiline

String

Program:

str1 = 'hello STUDENTS' #string str1

str2 = ' how are you' #string str2

print (str1[0:2]) #printing first two character using slice operator print (str1[4]) #printing 4th

character of the string

print (str1*2) #printing the string twice

print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he o
[Type here]
hello STUDENTS hello STUDENTS

hello STUDENTS how are you

List

• Python Lists are similar to arrays in C.


• However, the list can contain data of different types.
• The items stored in the list are separated with a comma (,) and enclosed within square brackets [].
• We can use slice [:] operators to access the data of the list.
• The concatenation operator (+) and repetition operator (*) works with the list in the same way as
they were working with the strings.

Program:

list1 = [1, "hi", "Python", 2] print (type(list1))

#Printing the list1 print (list1)

# List slicing print (list1[3:])

# List slicing print (list1[0:2])

# List Concatenation using + operator print (list1 + list1)

# List repetation using * operator print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]

[2]

[1, 'hi']

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple

• A tuple is similar to the list in many ways.


• Like lists, tuples also contain the collection of the items of different data types.

[Type here]
The items of the tuple are separated with a comma (,) and enclosed in parentheses ().
• A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

Program:

tup = ("hi", "Python", 2) # Checking type of tup print (type(tup))

#Printing the tuple print (tup)

# Tuple slicing print (tup[1:])


print (tup[0:1])

# Tuple concatenation using + operator print (tup + tup)

# Tuple repatation using * operator print (tup * 3)

# Adding value to tup. It will throw an error. t[2] = "hi"

Output:

<class 'tuple'> ('hi', 'Python', 2)

('Python', 2)

('hi',)

('hi', 'Python', 2, 'hi', 'Python', 2)

('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2) Traceback (most recent call last):

File "main.py", line 14, in <module> t[2] = "hi";

TypeError: 'tuple' object does not support item assignment

[Type here]
Dictionary

• Dictionary is an unordered set of a key-value pair of items.


• It is like an associative array or a hash table where each key stores a specific value.
• Key can hold any primitive data type, whereas value is an arbitrary Python object.
• The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.

Program:

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'} # Printing dictionary

print (d)

# Accesing value using keys print("1st name is "+d[1]) print("2nd name is "+ d[4]) print

(d.keys())

print (d.values())

Output:

1st name is Jimmy 2nd name is mike

{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}

dict_keys([1, 2, 3, 4]) dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean

• Boolean type provides two built-in values, True and False.


• These values are used to determine the given statement true or false.
• It denotes by the class bool.
• True can be represented by any non-zero value or 'T' whereas false can be represented by the 0 or
'F'.

[Type here]
Program:

# 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

Set

• Python Set is the unordered collection of the data.


• It is iterable, mutable(can modify after creation), and has unique elements.
• In set, the order of the elements is undefined.
• The set is created by using a built-in function set(), or a sequence of elements is passed in the
curly braces and separated by the comma.
• It can contain various types of values.

Program:

# Creating Empty set set1 = set()

set2 = {'James', 2, 3,'Python'} #Printing Set value

print(set2)

# Adding element to the set set2.add(10)

print(set2)

#Removing element from the set

[Type here]
set2.remove(2) print(set2) Output:

{3, 'Python', 'James', 2}

{'Python', 'James', 3, 2, 10}

{'Python', 'James', 3, 10}

Operators and Expressions

The operator can be defined as a symbol which is responsible for a particular operation between
two operands.

• Arithmetic operators
• Comparison operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators

Arithmetic Operators:

Arithmetic operators are used to perform arithmetic operations between two operands.

Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
It is used to subtract the second operand from the first operand. If the first
- (Subtraction) operand is less than the second operand, the value results negative. For
example, if a = 20, b = 10 => a - b = 10
It returns the quotient after dividing the first operand by the second operand.
/ (division)
For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b =10
(Multiplication) => a * b = 200
It returns the reminder after dividing the first operand by the second operand.
% (reminder)
For example, if a = 20, b = 10 => a%b = 0
It is an exponent operator represented as it calculates the first operand power to
** (Exponent)
the second operand.
// (Floor
It gives the floor value of the quotient produced by dividing the two operands.
division)

[Type here]
a = 10
b = 3
print("a + b =” ,a + b)
print("a - b =”,a - b)
print(“a * b = “,{a * b})
print(f"a / b = {a / b}")
print(f"a % b = {a % b}")
print(f"a ** b = {a ** b}")
print(f"a // b = {a // b}")

Comparison operators:

Comparison operators are used to comparing the value of the two operands and returns Boolean
true or false accordingly.

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.
If the first operand is less than or equal to the second operand, then the condition
<=
becomes true.
If the first operand is greater than or equal to the second operand, then the condition
>=
becomes true.
If the first operand is greater than the second operand, then the condition becomestrue.
>
< If the first operand is less than the second operand, then the condition becomes true.

a = 10
b = 3
print(a < b)
print(a <= b)
print(a > b)
print(a >= b)
print(a == b)
print(a != b)

[Type here]
Assignment Operators:

The assignment operators are used to assign the v+alue of the right expression to the left
operand.

Operator Description
= It assigns the value of the right expression to the left operand.
It increases 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 = 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.

[Type here]
a = 10
b = 3
a += b
print(f"a += b => {a}")
a -= b
print(f"a -= b => {a}")
a *= b
print(f"a *= b => {a}")
a /= b
print(f"a /= b => {a}")
a %= b
print(f"a %= b => {a}")
a **= b
print(f"a **= b => {a}")
a //= b
print(f"a //= b => {a}")

Bitwise Operators

The bitwise operators perform bit by bit operation on the values of the two operands.

Example:

if a = 7

b=6

then, binary (a) = 0111 binary (b) = 0110 hence, a & b = 0110

a | b = 0111 a ^ b = 0001

~ a = 1000

Operator Description
& (binary
If both the bits are 1, then the result is 1. Otherwise, 0.
and)
The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will
| (binary or)
be 1.

[Type here]
^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise, the resulting bit
will be 0.
It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting
~ (negation)
bit will be 1 and vice versa.

a = 10
b = 15
print(f"{bin(a)} & {bin(b)} = {bin(a & b)}")
print(f"{bin(a)} | {bin(b)} = {bin(a | b)}")
print(f"{bin(a)} ^ {bin(b)} = {bin(a ^ b)}")
print(f"~{bin(a)} = {bin(~a)}")

Logical Operators:

The logical operators are used primarily in the expression evaluation to make a decision.

Operator Description
If both the expression are true, then the condition will be true. If a and b are the two
and
expressions, a → true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a and b are the two

[Type here]
expressions, a → true, b → false => a or b → true.
not If an expression a is true, then not (a) will be false and vice versa.
a = 10
b = 3
c = 20
print(a < b and a > c)
print(a < b or a > c)
print(not a > b)

Membership Operators

• Python membership operators are used to check the membership of value inside a Python data
structure.
• If the value is present in the data structure, then the resulting value is true otherwise it
returns false.

Operator Description
It is evaluated to be true if the first operand is found in the second operand (list, tuple,
in
or dictionary).
It is evaluated to be true if the first operand is not found in the second operand (list,
not in
tuple, or dictionary).
list = [1, 4, 10, 40, 5]
a = 10
b = 3
print(a in list)
print(b in list)
print(a not in list)
print(b not in list)
print('s' in 'BSsmartclass')

Identity Operators:
The identity operators are used to decide whether an element certain class or type.

Operator Description
is It is evaluated to be true if the reference present at both sides point to the same object.
It is evaluated to be true if the reference present at both sides do not point to the same
is not
object.

[Type here]
Operator Precedence:

The precedence of the operators is essential to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in Python is given
below.

Operator Description
The exponent operator is given priority over all the others used in the
**
expression.
~+- The negation, unary plus, and minus.
* / % // The multiplication, divide, modules, reminder, and floor division.
+- Binary plus, and minus
>> << Left shift. and right shift
& Binary and.
^| Binary xor, and or
Comparison operators (less than, less than equal to, greater than, greater then
<= < > >=
equal to).
<> == != Equality operators.

[Type here]
Built in functions in python: The built-in functions are those functions that are pre-defined
in Python.

Python abs()
The abs() function returns the absolute value of the given number. If the number is a
complex number, abs() returns its magnitude.
Example
number = -20

absolute_number = abs(number)

print(absolute_number)

# Output: 20

Python any()
The any() function returns True if any element of an iterable is True. If not, it
returns False.
Example
boolean_list = ['True', 'False', 'True']

# check if any element is true


result = any(boolean_list)

print(result)

# Output: True
Python all()
The all() function returns True if all elements in the given iterable are true. If not, it
returns False.
Example
boolean_list = ['True', 'True', 'True']

# check if all elements are true


result = all(boolean_list)

print(result)

# Output: True
Python bin()
The bin() method converts a specified integer number to its binary representation and
returns it.
Example
number = 15
29
# convert 15 to its binary equivalent
print('The binary equivalent of 15 is', bin(number))

# Output: The binary equivalent of 15 is 0b1111


The bool() method takes a specified argument and returns its boolean value.
Example-
test = 1

# returns boolean value of 1


print(test, 'is', bool(test))

# Output: 1 is True
Python chr()
The chr() method converts an integer to its unicode character and returns it.
Example
print(chr(97))

# Output: a

print(chr(98))

# Output: b
Python len()
The len() function returns the number of items (length) in an object.
Example
languages = ['Python', 'Java', 'JavaScript']

# compute the length of languages


length = len(languages)

print(length)

# Output: 3

30
UNIT-II

Control Statements:

• Control Statements are used to transfer the control from one part of the program to another
depending on a condition.
• These statements are also called as conditional statements.

Conditional Statements:

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.

31
Syntax:

if expression: statement

Program:

num = int(input("enter thenumber"))


if num%2 == 0:
print("Number is even")

Output:

enter the number 10 Number is even


2) Write a program to determine the entered character
Char =input(“press any key:”)
If(char.isalpha()):
Print(“the user has entered a character”)
If(char.isdigit()):
Print(“the user has entered a digit”)
If(char.isspace())

Print(“the user has entered a space”)


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.

32
Syntax:
if condition:
#block of statements
else:
#another block of statements
Program:

age = int (input("Enter your age "))

if age>=18:

print("You are eligible to vote ")

else:

print("Sorry! you are not eligible")

Output:
Enter your age 90
You are eligible to vote

# write a program to enter any character,if the character is in lowercase then convert it into
uppercase and if it is an uppercase character,then convert it into lowercase.

ch = input("enter any character:")


if(ch >= 'A' and ch <= 'Z'):
ch = ch.lower()
print("the equivalent lowercase letter is:" +ch)
else:
ch = ch.upper()
print("the entered character was in lowercase,in uppercase it is:" + ch)

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.

33
Syntax:
if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements
Program:
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50")
elif number==100:
print("number is equal to 100")
else:
print("number is not equal to 10, 50 or 100")
Output:
Enter the number 15
number is not equal to 10, 50 or 100

#program on calculator

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
34
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(num1, "+", num2, "=", num1+ num2)

elif choice == '2':


print(num1, "-", num2, "=", num1-num2)

elif choice == '3':


print(num1, "*", num2, "=", num1*num2)

elif choice == '4':


print(num1, "/", num2, "=", num1/num2)

# check if user wants another calculation


# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
# write a program to calculate tax given in the following conditions.
If income is <1,50,000 then no tax
If taxable income is 1,50,000 – 3,00000 then charge 10%tax
If taxable income is 3,00,001 – 5,00000 then charge 20%tax
If taxable income is above 5,00000 then charge 30%tax

min1 = 150001
max1 = 300000
rate1 = 0.10
min2 = 300001
max2 = 500000
rate2 = 0.20
min3 = 500001
rate3 = 0.30

income = int(input("enter the income"))


taxable_income = income - 150000
if taxable_income == 0:
print("no tax")
35
elif(taxable_income>=min1 and taxable_income<max1):
tax = (taxable_income - min1) * rate1

elif(taxable_income>=min2 and taxable_income<max2):


tax = (taxable_income - min2) * rate2
else:
tax = tax = (taxable_income - min3) * rate3
print("TAX = ",tax)

A word on Indentation:
• For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code.
• In Python, indentation is used to declare a block.
• If two statements are at the same indentation level, then they are the part of the same block.
• Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.

Looping Statements:

• The programming languages provide various types of loops which are capable of repeating some
specific code several numbers of times.
• The looping simplifies the complex problems into the easy ones.

36
• For example, if we need to print the first 10 natural numbers then, instead of using the print
statement 10 times, we can print inside a loop which runs up to 10 iterations.

for Loop:

• The for loop in Python is used to iterate the statements or a part of the program several times.
• It is frequently used to traverse the data structures like list, tuple, or dictionary.

Syntax:

for iterating_var in sequence:

statement(s)

Program: Write a Python program to display characters of a string using for loop.

str='Hello'

for ch in str:

print(ch)

Output:

H
ello
Program: Write a program to print multiplication table of a given number

list = [1,2,3,4,5,6,7,8,9,10]
n = int(input[(“enter the number”)
for i in list:
c = n*i
print(c)
Output:

5
10
15
20
25
30
35
37
40
45

38
50
Program: Write a python program to print the sum of the given list.
list = [10,30,23,43,65,12]
sum = 0

for i in list:
sum = sum+i
print("The sum is:",sum)
Output:
The sum is: 183

For loop Using range() function:

• The range() function is used to generate the sequence of the numbers.


• If we pass the range(10), it will generate the numbers from 0 to 9.

Syntax:

range(start,stop,step size)

• The start represents the beginning of the iteration.


• The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1
to 4 iterations. It is optional.
• The step size is used to skip the specific numbers from the iteration. It is optional to use. By
default, the step size is 1.

Program: Python Program to print numbers in sequence.

for i in range(10):

print(i)

Output:

0
1
2
3
4
5
6
7
8
9
Program: Python Program to print even number using step size in range().
n = int(input("Enter the number "))
39
for i in range(2,n,2):

40
print(i)
Output:
Enter the number 20 2
4
6
8
10
12
14
16
18

Nested Loop:

• Python allows us to nest any number of for loops inside a for loop.
• The inner loop is executed n number of times for every iteration of the outer loop.
Syntax:
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements #Other statements
Program:

Print the following pattern

Write a program to print the following number pattern using a loop.

* *

***

print("Number Pattern ")

# Decide the row count. (above pattern contains 5 rows)


row = 5
# start: 1
41
# stop: row+1 (range never include stop number in result)
# step: 1
# run loop 5 times
for i in range(1, row + 1, 1):
# Run inner loop i+1 times
for j in range(1, i + 1):
print('*', end=' ')
# empty line after each row

print("\n")

3. Write a program to accept a number from a user and calculate the sum of all
numbers from 1 to a given number

For example, if the user entered 10 the output should be 55 (1+2+3+4+5+6+7+8+9+10)

s=0
n = int(input("Enter number "))
# run loop n times
# stop: n+1 (because range never include stop number in result)
for i in range(1, n + 1):

# add current number to sum variable


s += i
print("\n")
print("Sum is: ", s)

While Loop:



• The Python while loop allows a part of the code to be executed until the given condition returns
false.
• It is also known as a pre-tested loop.
• When we don't know the number of iterations then the while loop is most effective to use.
Syntax:
while expression: statements
• Here, the statements can be a single statement or a group of statements.
42
• The expression should be any valid Python expression resulting in true or false.
• The true is any non-zero value and false is 0.
Program:
count = 1
while (count < 3):
count = count+1
print("Hello Python")
Output:
Hello Python Hello Python Hello Python

The else Suite:


• In Python, it is possible to use 'else' statement along with for loop or while loop in the form
shown in Table:

for with else while with else


fofo r( var in sequence):
wwhile( condition ):

statements statements

else: else:

statements statements

• The else suite will be always executed irrespective of the statements in the loop are executed or
not.

Program:

for i in range(5):

print("Yes")

else:

print("No")

Output:

43
Yes Yes Yes Yes Yes No

Break Statement:
• The break is a keyword in python which is used to bring the program control out of the loop.
• The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the
inner loop first and then proceeds to outer loops.
• The break is commonly used in the cases where we need to break the loop for a given condition.
Program:
str = "python"
for i in str:
if i == 'o':
break
print(i)

Output:
pyth

Continue Statement:

• The continue statement skips the remaining lines of code inside the loop and start with the next
iteration.

Program:
str = "python"
for i in str:

if i == 'o':
continue
print(i);

44
Output:
pythn

Program:

i=0
while(i < 10):
i = i+1
if(i == 5):
continue print(i)
Output:
1
2
3
4
6
7
8
9
10

Pass:

• In Python, the pass keyword is used to execute nothing; it means, when we don't want to execute
code, the pass can be used to execute empty.
• If we want to bypass any code pass statement can be used.
• The difference between the comments and pass is that, comments are entirely ignored by the
Python interpreter, where the pass statement is not ignored.

Program:

values = {'P', 'y', 't', 'h','o','n'}

for val in values:


pass
print(“okay loop passed”)

45
Program:
for i in [1,2,3,4,5]:
if(i==4):
pass

46
print("This is pass block",i)
print(i)
Output:
1
2
3
This is pass block 4 4
5
• We can create empty class or function using the pass statement. # Empty Function
def function_name(args):
pass

#Empty Class class Python:


Pass
1. Write a program to display only those numbers from a list that satisfy the
following conditions

• The number must be divisible by five


• If the number is greater than 150, then skip it and move to the next number
• If the number is greater than 500, then stop the loop
Given:

• numbers = [12, 75, 150, 180, 145, 525, 50]


• # iterate each item of a list
• for item in numbers:
• if item > 500:
• break
• elif item > 150:
• continue
• # check if number is divisible by 5
• elif item % 5 == 0:
• print(item)

47
Count the total number of digits in a number

Write a program to count the total number of digits in a number using a while
loop.

num = int(input(“enter the number”)


count = 0
while num != 0:
# floor division
# to reduce the last digit from number
num = num // 10

# increment counter by 1
count = count + 1

print("Total digits are:", count)

Print the following pattern

Write a program to u

se for loop to print the following reverse number pattern3 2

n=5
k=5
for i in range(0,n+1):
for j in range(k-i,0,-1):
print(j,end=' ')

print()

Print list in reverse order using a loop

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


# reverse list
new_list = reversed(list1)
48
# iterate reversed lis
t
for item in new_list:
print(item)

Write a program to display all prime numbers within a


range

Note: A Prime Number is a number that cannot be made by multiplying other


whole numbers. A prime number is a natural number greater than 1 that is not a
product of two smaller natural numbers

Examples:

• 6 is not a prime mumber because it can be made by 2×3 = 6


• 37 is a prime number because no other whole numbers multiply together to
make it.
start = 25
end = 50
print("Prime numbers between", start, "and", end, "are:")

for num in range(start, end + 1):


# all prime numbers are greater than 1
# if number is less than or equal to 1, it is not prime
if num > 1:
for i in range(2, num):

# check for factors


if (num % i) == 0:
# not a prime number so break inner loop and
# look for next number
break
else:

• print(num)

49
• Fibonacci series

num1, num2 = 0, 1
print("Fibonacci sequence:")
# run loop 10 times
for i in range(10):
# print next number of a series
print(num1, end=" ")
# add last two numbers to get next number
res = num1 + num2

# update values
num1 = num2
num2 = res

Factorial of a given number

num = 5
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
# run loop 5 times
for i in range(1, num + 1):
# multiply factorial by current number
factorial = factorial * i
print("The factorial of", num, "is", factorial)

50

You might also like