0% found this document useful (0 votes)
4 views111 pages

Module2 Myown

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

Module2 Myown

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

DR.R.

KANNIGA DEVI
BCSE 101E- Computer Programming: ASSOCIATE PROFESSOR
Python SCHOOL OF COMPUTER SCIENCE
Module -2 AND ENGINEERING
VIT CHENNAI
Syllabus

Module:2 Python Programming Fundamentals

Introduction to python – Interactive and Script Mode – Indentation – Comments – Variables – Reserved
Words – Data Types – Operators and their precedence – Expressions – Built-in Functions – Importing from
Packages.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Introduction to Python

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


History of Python

Created in 1989 by Guido van Rossum


• Both scripting and programming language
• Named after the British comdy troupe Monty Python
• By programming language, it means a high-level, general-purpose
programming language consists of multiple scripts and modules
which can be used to develop a wide range of applications, from web
development to data analysis, artificial intelligence, and more. It
supports object-oriented, procedural, and functional programming
paradigms, making it versatile for different types of software
development.
• By scripting language, it means a small and simple program written to
automate repetitive tasks, such as file manipulation, data extraction,
or running repetitive jobs. Scripts are often interpreted rather than
compiled and can be run directly without the need for a compilation
step.
DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI
History of Python

Released publicly in 1991


• Growing community of Python developers
• Evolved into well-supported programming language

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Why Python

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Notable Features

• Easy to learn – Normal English-based syntaxes with interactive compilation


• Supports quick development. – Supports wide variety of packages
• Cross-platform – Capable of executing in any OS
• Open Source – Freely usable and distributable, even for commercial use
• Extensible – easily extensible with C/C++/Java code, and easily embeddable in applications
• Embeddable – can be used in embedded, small or minimal hardware devices
• Large standard library and active community – Image Processing (opencv), machine learning (sklearn),
deep learning (tensorflow), among others
• Useful for a wide variety of applications

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Program Translations

Two approaches for program translation:

• interpretation

• compilation

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Program Translations: Interpretation Approach
Interpretation approach

• uses a program known as interpreter

• reads one high-level code statement at a time

- immediately translates and executes the statement before processing the


next one

• examples: Python

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Program Translation: Compilation Approach

Compilation approach
• uses a program called compiler

• reads and translates the entire high-level language program


(source) code into its equivalent machine-language instructions in
an executable file
• the resulting machine-language instructions can then be
executed directly on the computer when the program is
launched
• examples: C and C++

It is also possible to use the combination of both translation


techniques

• example: Java DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Program Translation in Python : Interpreter

Python is primarily an interpreted language. The Python interpreter is called “CPython” and it's written in the C
programming language. This is the default implementation for Python.

Interpreted Language
•Execution: Python code is executed line by line by an interpreter at runtime. The Python interpreter reads the code,
interprets it, and executes it directly.
•Flexibility: This allows for greater flexibility and ease of testing, as you can run and test portions of the code
interactively without needing to compile the entire program.

Compilation in Python
Although Python is generally considered an interpreted language, there is an intermediate compilation step:
•Bytecode Compilation: When you run a Python program, the Python interpreter first compiles the source code (.py
files) into bytecode (.pyc files). This bytecode is a lower-level, platform-independent representation of the source
code.
•Execution: The bytecode is then interpreted by the Python Virtual Machine (PVM), which is the actual interpreter
that executes the bytecode.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Interactive and Script mode

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Types of modes
•Python can be used in two modes:

Each mode serves different purposes and is suitable for different tasks.

• Script mode :
Script mode is used to run Python programs that are saved in files with a .py extension.

These programs can be executed by the Python interpreter in one go.

Use Case: This mode is ideal for writing larger, more complex programs that you want to save,
modify, and run multiple times.

Eg: use some IDE like VScode (after installing python extension in VScode)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Types of modes
•Interactive mode
• Interactive mode allows you to execute Python commands one at a time in a live, interactive
session.
• This mode is often used for testing, debugging, and experimenting with code snippets.

• Use Case: This mode is useful for learning Python, trying out new ideas, and performing quick
calculations or operations.

Eg: Jupyter Notebook

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Interactive mode

Now
set t we are
o
pyth practic
o n☺ e
☺☺

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Types of modes
•Script mode in Jupyter Notebook : (it also allows us to run scripts)
To create a script file :
Jupyter 🡪New🡪text file🡪 (menu🡪 language🡪 python) 🡪 type python code 🡪 save as “test.py”
To run the script file:
Jupyter🡪 new🡪 Python 3 (ipykernel)🡪 type “%run test.py “ in jupyter interface 🡪 see the output

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Indentation

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Indenting Requirements

•Indentation means the spaces at the beginning


of a statement.
•The indentation in Python needs to be if 3 > 1:
print(“Three is greater than one")
followed strictly whereas in other
programming languages the indentation in
code is just for enhancing the readability Indentation

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Indenting Requirements

• Syntax error if indentation is skipped

if 3 > 1:
print(“Three is greater than one")

No Indentation
raises syntax
error

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Indenting Requirements

• The number of spaces is up to the coder, but


it has to be minimum one.
if 3 > 1:
print(" Three is greater than one ")
if 3 > 1:
One Indentation print(" Three is greater than one ")
space

More than one


Indentation
spaces

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Indenting Requirements

• Same number of spaces need to be given in


the same block of code
•Otherwise Python will show an error if 3 > 1:
print(" Three is greater than one ")
print(" Three is greater than one ")
Syntax error for
different
indentation in each
statement

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Comments

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Comments

• Start comments with #, rest of line is ignored


• Can include a “documentation string” as the first line of a new function or class you define
• Development environments, debugger, and other tools use it: it’s good style to include one
Example:
#initialization of variables
Commented
line
a=10
b=20

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Variables

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Identifier in Python & its Rules

Identifier: a name given to an entity in Python


• Helps in differentiating one entity from another
• Name of the entity must be unique to be identified during the execution of the
program

Rules for writing IDENTIFIERS


• Uppercase and lowercase letters A through Z
WHAT (26 * 2 = 52)
CAN BE •The underscore, '_’ (1)
USED • The digits 0 through 9, except for the first
character (10)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Identifier rules in Python

• Must begin with a letter or _ • Upper case and lower case letters
are different
• ‘abc123’ and ‘_abc123’ are ok
• ‘123abc’ is not allowed • ‘abc123’ is not ‘ Abc123’

• May contain letters, digits, and • Python is Case Sensitive


underscores
• Can be of any length
• this_is_an_identifier_123
• Names starting with _ have special
• Should not use keywords meaning
Don’ts : Not to start with numbers; not to use keywords; case sensitive

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Identifier- Summary

Identifier names should start with a letter (a-z, A-Z) or an underscore (_), followed by letters,
digits (0-9), or underscores.

Variable names are case-sensitive.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Variable Objects

Operations
• Once a variable is created, we can store, retrieve, or modify the value
associated with the variable name.

• Subsequent assignments can update the associated value.

3.14 Name Value


x = 3.14
x 3.14
X

Name Value
x = 5.16 5.16
x 5.16

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Dynamic Typing in python

Python variables are dynamically typed, which means you don't need to declare their type
explicitly.

Instead, the type is determined based on the value assigned to the variable.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Variable- Example
1. Basic Assignment
3.Changing Variable Values
x = 10 # An integer variable
x = 20 # x now holds the value 20
y = 3.14 # A floating-point variable x = "Python" # x now holds a string value "Python"
name = "Alice" # A string variable
is_valid = True # A boolean variable
4. Multiple Assignments
2. Printing Variables a, b, c = 1, 2, 3
print(a, b, c) # Output: 1 2 3
print(x) # Output: 10
print(y) # Output: 3.14 # Swapping values
print(name) # Output: Alice a, b = b, a
print(is_valid) # Output: True print(a, b) # Output: 2 1

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Variable- Example

Variable Types:
You can use the type() function to check the type of a variable.
print(type(x)) # Output: <class 'str'>
print(type(y)) # Output: <class 'float'>
print(type(name)) # Output: <class 'str'>
print(type(is_valid)) # Output: <class 'bool'>

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Variable- Example

Example of a Variable in Use


Here's a simple program that uses variables to calculate the area of a rectangle:
# Define the dimensions
length = 5
width = 3
Output:
# Calculate the area The area of the rectangle is: 15

area = length * width

# Print the result


print("The area of the rectangle is:", area)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Reserved words

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Reserved words or Keywords
• Special words reserved in Python
• Programmers should not use keywords to name things
• They must be spelled exactly as written here
and del global or False
as def import pass None
await else in raise True
assert elif if return
async except is try
break finally lambda while
class for nonlocal with
continue from not yield

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Data Types

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Data types

Numerical Data types:

● Integers: Python supports integer data types. They are often called int and are positive or negative or
whole numbers without decimal points. They are represented by class int.
● Float: Python support floating-point data type. They are often called float .They represent real
numbers and are written with a decimal point separating the integral and fractional part. They are
represented by class float

String Data types:

● In python, strings are arrays of one or more characters, represented in single or double quotes.
● They are represented by class str.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Data types

The boolean data type is either True or False. In Python, boolean variables are defined by the True and
False keywords. The output <class 'bool'> indicates the variable is a boolean data type.

Note: The built in function type(variable) returns the class of the datatype.

Type
s of v
are s ariables
throu pecified
Output: gh wr
a
class pper
es

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Data types- Example

int: Integer values


x = 10

float: Floating-point values


y = 3.14

str: String values


greeting = "Hello, World!"

bool: Boolean values, True or False.


is_valid = True

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Conversion of datatypes
Type Conversion Example 1 : integer to float
num_int = 123
The process of converting the value of one data type num_flo = 1.23
(integer, string, float, etc.) to another data type is called num_new = num_int + num_flo
type conversion. Python has two types of type conversion print("datatype of num_int:",type(num_int))
1.Implicit Type Conversion (Type coercion) print("datatype of num_flo:",type(num_flo))
2.Explicit Type Conversion (Type casting) print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
Implicit/automatic Type Conversion
• In Implicit type conversion, Python automatically Note:
Conversion of the lower data type (integer)
converts one data type to another data type.
• This process doesn't need any user involvement. to the higher data type (float) to avoid data
loss.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


'

Conversion of datatypes
Example 2 Example : String to integer

num_int = 123 In this example


num_str = "456" •We add two variables
num_int and num_str
print("Data type of num_int:",type(num_int)) print("Data •As we can see from the output, we
type of num_str:",type(num_str)) got TypeError
•Python is not able to use Implicit
Conversion in such conditions.
print(num_int+num_str) •However, Python has a solution for
Output these types of situations which is
known as Explicit Conversion.
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'> Note:
Traceback (most recent call last): File "python", line 7, in Conversion of the higher data type
<module> TypeError: unsupported operand type(s) for +: (String) to the lower data type
(integer) is not implicit.
'int' and 'str

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


'

Conversion of datatypes
Explicit Type Conversion
Syntax
• In Explicit Type Conversion, users convert the data type of an
object to required data type. <required_datatype>(expression)
• We use the predefined 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.
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str)) Example 3 : String to Integer
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str)) What is the output of this
num_sum = num_int + num_str programme
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


'

Conversion of datatypes
Key Points to Remember
1.Type Conversion is the conversion of object
from one data type to another data type.
Output of Example 3
2.Implicit Type Conversion is automatically
performed by the Python interpreter.
Data type of num_int: <class 'int'>
3.Python avoids the loss of data in Implicit
Data type of num_str before Type Casting: <class 'str'>
Type Conversion.
Data type of num_str after Type Casting: <class 'int'>
4.Explicit Type Conversion is also called Type
Sum of num_int and num_str: 579
Casting, the data types of objects are
Data type of the sum: <class 'int'>
converted using predefined functions by the
user.
5.In Type Casting, loss of data may occur as
we enforce the object to a specific data type.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Conversion of datatypes

Type conversion
made simpler

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Conversion of data types

Types of Type Conversion


1.Implicit Type Conversion: Automatically done by Python.
2.Explicit Type Conversion: Manually done by the programmer using built-in functions.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Conversion of data types

Implicit Type Conversion


Python automatically converts one data type to another when performing operations that mix types.

Example:
# Implicit type conversion
x = 10 # int
y = 3.14 # float

result = x + y # x is implicitly converted to float


print(result) # Output: 13.14
print(type(result)) # Output: <class 'float'>

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Conversion of data types

Implicit Type Conversion


It occurs when Python automatically converts a lower precision (or smaller) data type to a higher
precision (or larger) data type during an operation to prevent data loss.
This process ensures that the resulting data type can represent the value accurately.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Conversion of data types

Explicit Type Conversion


It involves converting a higher precision (or larger) data type to a lower precision (or smaller) data type.
This type of conversion is done manually by the programmer using built-in functions.
Explicit conversion can sometimes lead to a loss of data or precision, which is why it is called "explicit"—
the programmer must explicitly request it.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Conversion of data types

Explicit Type Conversion


Explicit type conversion requires the use of built-in functions.
Common Conversion Functions
•int(): Converts a value to an integer.
•float(): Converts a value to a float.
•str(): Converts a value to a string.
•bool(): Converts a value to a boolean.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Conversion of data types

Examples: # Int to float # Int to bool


# Float to int e = 10 aa = 0
a = 3.14 f = float(e) bb = bool(aa)
print(f) # Output: 10.0 print(bb) # Output: False
b = int(a)
print(b) # Output: 3 # String to float # String to bool
g = "3.14" cc = "hello"
# String to int h = float(g) dd = bool(cc)
c = "123" print(h) # Output: 3.14 print(dd) # Output: True
d = int(c)
print(d) # Output: 123

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Conversion of data types

To convert between data types:

x = 10
y = float(x) # Convert int to float
s = str(x) # Convert int to string

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Input/Output

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


'

Simple Output
Example : integer to float
Syntax
print("Python is fun.")
print(*objects, sep=' ', end='\n', file=sys.stdout) a = 5 # Two objects are passed
Purpose of each parameter print("a =", a)
b = a # Three objects are passed
• objects - object to the printed. * indicates that there print('a =', a, '= b')
may be more than one object
• sep - objects are separated by sep. Default value: ' ' a=5
• end - end is printed at last print("a =", a, sep='00000', end='\n\n\n')
• file - must be an object with write(string) method. If print("a =", a, sep='0', end='')
omitted it, sys.stdout will be used which prints objects
on the screen sourceFile = open('python.txt', 'w')
print('Pretty cool, huh!', file = sourceFile)
sourceFile.close()

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


.
'

Simple Input
Syntax Example
num=input('Enter a number')
input([prompt]) num1=input('Enter second number')
print(num+num1)
• Here, we can see that the entered value 10
and 20 is a string, not a number. To convert Enter a number10
this into a number we can Enter second number20
use int() or float() functions 1020

num=input('Enter a number')
• Here, we converted both num and num1 to num1=input('Enter second number')
integer and the result we get is integer print(int(num)+int(num1))

Enter a number10
Enter second number20
30

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


.
'

Simple Input

• eval()
It evaluates the expression given as a
string and returns integer
Example

>>> int('2+3') >>> s=eval('2+3')


Traceback (most recent call last): File >>> print(s)
"<string>", line 301, in runcode File 5
"<interactive input>", line 1, in <module> >>> type(s)
ValueError: invalid literal for int() with <class 'int'>
base 10: '2+3‘ >>>
>>> eval('2+3')
5

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Input

The input() function reads a line from the input (usually from the user via the keyboard) and returns it
as a string.

Example:
name = input("Enter your name: ")
print("Hello, " + name + "!") # here, + is a concatenation operator
Output

The print() function can take multiple arguments, and by default, it adds a space between arguments
and ends with a newline.

Example:
print("Hello, World!")

You can also customize the separator and end characters using the sep and end parameters.
print("Hello", "World", sep="-", end="!")
# Output: Hello-World!
Input

Reading Numeric Input:


Since the input() function returns a string, you need to convert it to the appropriate numeric type (e.g.,
int or float) if you want to handle numbers.
Example:
age = input("Enter your age: ")
age = int(age) # Convert the input to an integer
print("You are", age, "years old.")
Input/Output

Formatted String Literals


name = "Alice"
age = 30
print(f"Hello, {name}! You are {age} years old.")

str.format():
name = "Alice"
age = 30
print("Hello, {}! You are {} years old.".format(name, age))
Operators and their precedence

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Basic Operations

Basic Operations in python:


Addition operation(+):

output:
7

Output:

S
co nc tr i ng
a ten
a ti o n

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Arithmetic Operations

Simple Arithmetic Operations in Numerical Data types.


• Addition operation +
• Subtraction operation -
• Multiplication operation *
• exponentiation operation **
• Division /
• floor division(returns only the integral part of the division) //
• Modulus operator (returns only the remainder part of the division) %

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Arithmetic Operations

Let’s have an exercise on these arithemetic operators:

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Arithmetic Operations

Example:
a = 10
b=3
print(a / b) # Output: 3.3333333333333335
print(a // b) # Output: 3

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Repetition operator

Multiplication (*) operator between Strings and integer(repetition):


When * operator is used between a string(a) and a integer(n) datatype , then the result would be repetition
of the string (a) n times and the result is also a string.

* With strings
performs
repetition
Output:

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Relational operators
Relational operators are otherwise known as comparison operators. These operators are used to
compare two values

List of relational operators:


•Equals: •Greater than:
• x == y • x>y
•Not Equals: •Greater than or equal to:
• x != y • x >= y
•Less than:
• x<y
•Less than or equal to:
• x <= y

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Relational operators

•Equals:

Example: returns False


x=7 because 7 is not
equal to 3
y=3
print(x == y)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Relational operators

•Not Equals:

Example: returns True


x=7 because 7 is not
equal to 3
y=3
print(x != y)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Relational operators

•Less than:

Example: returns False


x=7 because 7 is not
less than 3
y=3
print(x < y)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Relational operators

•Greater than:

Example: returns True


x=7 because 7 is
greater than 3
y=3
print(x > y)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Relational operators

•Less than or equal to:

Example: returns False


because 7 is not
x=7 less than or equal
y=3 to 3
print(x <= y)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Relational operators

•Greater than or equal to:

Example: returns True


because 7 is
x=7 greater than or
y=3 equal to 3
print(x >= y)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Logical Operators

Logical operators are used to join conditional statements


Types of operators are:
•and
• a < 4 and a < 5
•or
• a < 4 or a < 5
•not
• not(a < 4 and a < 5)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Logical Operators

•and
returns True
because 7 is greater
than 2 AND 7 is less
Example: than 12
a=7
print(a > 2 and a < 12)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Logical Operators

•or returns True because


one of the conditions
are true (7 is greater
than 2, but 7 is not less
Example: than 1)
a=7
print(a > 2 or a < 1)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Logical Operators

•not returns False because


not is used to reverse
the result

Example:
a=7
print(not(a > 4 and a < 12))

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Bitwise Operators

•Bitwise operators are used to compare binary numbers


•Types of operators are:
and - &
or - |
not - !
XOR - ^
left shift - <<
right shift - >>

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Bitwise Operators

•and - &

Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0 value of z is
12
z = x & y; # 12 = 0000 1100
print ("Value of z is ", z)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Bitwise Operators

•or - |

Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0
value of z is 61
z = x | y; # 61 = 0011 1101
print ("Value of z is ", z)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Bitwise Operators

•not - ~
•It is unary and has the effect of inverting all the bits

Example:
x = 60 # 60 = 0011 1100
z=0
value of z is
195
z = ~x ; # 195 = 1100 0011
print ("Value of z is ", z)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Bitwise Operators

•XOR - ^
• Sets each bit to 1 if only one of two bits is 1

Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0 value of z is
49
z = x ^ y; # 49 = 0011 0001
print ("Value of z is ", z)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Bitwise Operators

•Left shift - <<


•The left operand’s value is moved left by the number of bits specified by the
right operand.

Example:
x = 60 # 60 = 0011 1100
z=0 value of z is 240

z = x << 2; # 240 = 1111 0000


print ("Value of z is ", z)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Bitwise Operators

•Right shift - >>


•The left operand’s value is moved right by the number of bits specified by the
right operand.

Example:
x = 60 # 60 = 0011 1100
z=0
value of z is 15
z = x >> 2; # 15 = 0000 1111
print ("Value of z is ", z)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Assignment Operator

Assignment operators are used to assign values to variables.


Symbol is =

Eg:
a=4
a += 5
a -= 5

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Operator Precedence

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Operator Precedence

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Operator Associativity

For example, in 3 + 4 - 2, Python will first add 3 + 4 to get 7 and then subtract 2 to yield 5.

For example, in the expression 3 ** 2 ** 1, Python first calculates 2 ** 1 to get 2 and then computes 3
** 2 to give 9.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Expressions

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Expression

It is a combination of values, variables, and operators that the interpreter can evaluate to a single value.
x=2+3

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Expression

Types:
Arithmetic expression
Logical Expression
Bitwise expression
Assignment expression
Relational or Comparison expression
Compound expression

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Expression

Types:
Types:
Compound expression
Arithmetic expression
a = 10
a = 10
b=5
b=5
c=2
result1 = a + b # Addition
result1 = (a + b) * c # Parentheses ensure addition is done first

print(result1) # Output: 30

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Built-in Functions

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Built-in functions

These are the pre-defined function in Python that allows using the basic properties of string and
numbers in your rules. Here listed a few:
Function Description
abs() Returns the absolute value of a number
bool() Returns the boolean value of the specified object
len() Returns the length of an object
max() Returns the largest item in an iterable
min() Returns the smallest item in an iterable
pow() Returns the value of x to the power of y
print() Prints to the standard output device
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Built-in functions

Some examples:

result = abs(-10)

result = max(1, 2, 3)

result = sum([1, 2, 3])

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


range() function

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It
generates arithmetic progressions. It returns a sequence of numbers that starts at 0 and increments by 1
(by default) and stops before a specified number.

range(end) range(start, end) range(start, end, step)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


range()

Example:
Generate a sequence of numbers from 0 to 6:
n = range(7)
for x in n:
print(x) Prints
0,1,2,3,4,5,6

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


range()

Example:
Generate a sequence of numbers from 3 to 6:
n = range(3, 6)
for x in n:
print(x) Prints 2,3,4,5

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


range()

Example:
Generate a sequence of numbers from 2 to 8,
increment by 2:
n = range(2, 9,2)
for x in n: Prints 2,4,6,8
print(x)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Reverse range()

Example:
Generate a sequence of numbers from 5 to 1,
decrement by 1:
n = range(5, 0,-1)
for x in n: Prints 5,4,3,2,1
print(x)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Negative range()

Example:
Generate a sequence of numbers from -1 to -5,
decrement by 1:
n = range(-1, -6,-1)
for x in n: Prints -1,-2,-3,-4,-5
print(x)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


range() function

To iterate over the indices of a sequence, you can combine range() and len() as follows:

Output:
Accessing all
elements of list

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Importing from Packages

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Importing packages

•A package is a container that contains various functions to perform specific tasks.


•For example, the math package includes the sqrt() function to perform the square root of a number.
•While working on big projects, we have to deal with a large amount of code, and writing everything
together in the same file will make our code look messy.
•Instead, we can separate our code into multiple files by keeping the related code together in packages.
•Now, we can use the package whenever we need it in our projects. This way we can also reuse our code.

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Importing packages

# 1. Basic Import
import <module-name>

# 2. Import with Alias


import <module-name> as <alt-name>

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Importing packages

import math
print(math.sqrt(16)) # Output: 4.0

------------
import numpy as np
print(np.array([1, 2, 3])) # Output: [1 2 3]

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Importing packages

3. Import Specific Functions or Classes


from <module-name> import <name(s)>
Eg:
from math import sqrt, pi
print(sqrt(16)) # Output: 4.0
print(pi) # Output: 3.141592653589793

from <module-name> import <name> as <alt-name>

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Importing packages

# 4. Import All Names


from math import *
print(sqrt(16)) # Output: 4.0
print(pi) # Output: 3.141592653589793

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Lab exercises- Operators

1. Basic calculator
2. Simple interest calculation
3. Area of a rectangle
4. perimeter of a rectangle
5. Temperature conversion
6. Quadratic equation solver
7. BMI calculator
8. Sum of Natural Numbers
9. Discount Calculation
10. Salary Calculation with Tax Deduction

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Lab exercises- built-in functions

1. Converting Strings to Upper and Lower Case


2. Finding the Length of a String

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Lab exercises
# Expressions and built-in functions

# Using built-in functions


numbers = [1, 2, 3, 4, 5] //list

# Sum of the list


sum_numbers = sum(numbers)

# Maximum and minimum values


max_number = max(numbers)
min_number = min(numbers)

# Length of the list


length_numbers = len(numbers)

print("Sum of numbers:", sum_numbers)


print("Maximum number:", max_number)
print("Minimum number:", min_number)
print("Length of the list:", length_numbers)
DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI
Lab exercises

# Combining data types, operators, expressions, built-in functions, and importing from packages

import math

# Data types print("Result of the expression:", expression_result)


integer_value = 20 print("Maximum value in the list:", max_value)
float_value = 25.5 print("Length of the string:", string_length)
string_value = "Python Programming" print("Rounded float value:", rounded_value)
boolean_value = False
list_value = [10, 20, 30, 40, 50]

# Operators and expressions


expression_result = (integer_value + float_value) * math.sqrt(len(list_value))

# Using built-in functions


max_value = max(list_value)
string_length = len(string_value)
rounded_value = round(float_value)

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI


Thank You!

DR.R.KANNIGA DEVI, SCOPE, VIT CHENNAI

You might also like