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

PYTHON PROGRAMMING Unit 2

Python programming for bcom bba bca

Uploaded by

abaivox009
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

PYTHON PROGRAMMING Unit 2

Python programming for bcom bba bca

Uploaded by

abaivox009
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

PYTHON PROGRAMMING

UNIT II
Evaluating Expressions

Python eval() function parse the expression argument and


evaluate it as a Python expression and runs Python
expression (code) within the program.

Syntax:
eval(expression, globals=None, locals=None)

Parameters:
expression: String is parsed and evaluated as a Python
expression
globals [optional]: Dictionary to specify the available
global methods and variables.
locals [optional]: Another dictionary to specify the
available local methods and variables.
Contd..
Uses
Python eval() is not much used due to security reasons.
Still, it comes in handy in some situations.
eval() is also sometimes used in applications needing to
evaluate math expressions.
This is much easier than writing an expression parser.

print(eval('1+2')) Output:
print(eval("sum([1, 2, 3, 4])")) 310
Contd..
Example:

def function_creator():
# expression to be evaluated
expr = input("Enter the function(in
terms of x):")
# variable used in expression
x = int(input("Enter the value of
x:"))
# evaluating expression Output:
y = eval(expr) Enter the function(in terms
of x):x*(x+1)*(x+2)
# printing evaluated result Enter the value of x:3
print("y =", y) y = 60
if __name__ == "__main__":
function_creator()
Operators and Operands

Operators and Operands are fundamental concepts when


performing operations or computations.

Operators:

Operators in Python are special symbols or keywords


that perform operations on one or more operands.
Python supports various types of operators. They are
Contd..

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators
7. Membership Operators
8. Ternary Operator
Contd..

1.Arithmetic Operators: Used for basic mathematical operations.


•Addition (+), Subtraction (-), Multiplication (*), Division (/),
Floor Division (//), Modulus (%), Exponentiation (**).
2.Comparison Operators: Used to compare values.
•Equal to (==), Not equal to (!=), Greater than (>), Less than
(<), Greater than or equal to (>=), Less than or equal to (<=).
3.Logical Operators: Used to combine conditional statements.
•Logical AND (and), Logical OR (or), Logical NOT (not).
Contd..

4.Bitwise Operators: Used to perform bitwise operations on


integers.
•Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^), Bitwise
NOT (~), Left Shift (<<), Right Shift (>>).
5.Assignment Operators: Used to assign values to variables.
•Assignment (=), Addition assignment (+=), Subtraction
assignment (-=), Multiplication assignment (*=), etc.
Contd..

6.Identity Operators: Used to compare the memory locations of


two objects.
•is, is not.
7.Membership Operators: Used to test whether a value or
variable is found in a sequence.
•in, not in.
8.Ternary Operator: A conditional expression that evaluates to
one of two values depending on a condition.
•value_if_true if condition else value_if_false.
OPERANDS
Operands are the values or variables on which operators act. For
example:
•In 3 + 5, 3 and 5 are operands, and + is the operator.
•In a > b, a and b are operands, and > is the operator.
Operands can be literals (like 3, 5) or variables (like a, b).
Depending on the operator, the number of operands can vary. For
instance:
•Unary operators like -x have one operand (x).
•Binary operators like x + y have two operands (x and y).
Contd..
Example:
# Arithmetic operators
result = 10 + 5 # Addition
print(result) # Output: 15
result = 10 * 5 # Multiplication
print(result) # Output: 50

# Comparison operators
a = 10
b=5
print(a > b) # Output: True
Contd..

# Logical operators
x = True
y = False
print(x and y) # Output: False

# Assignment operators
c = 10
c += 5 # Equivalent to: c = c + 5
print(c) # Output: 15
Contd..

# Identity operators
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 is list2) # Output: False
(different objects)

# Membership operators
print(2 in list1) # Output: True

# Ternary operator
a=5
b = 10
max_value = a if a > b else b
print(max_value) # Output: 10
Order of Operations

Operator precedence is a set of rules that govern the


order in which operators are evaluated when
performing an operation.
It's essential to understand these rules to avoid
ambiguity in expressions, which could lead to
unexpected results.
Contd..

Category Operators
Arithmetic Operators **, *, /, +, -
Comparison Operators ==, !=, <=, >=, <, >
Logical Operators not, and, or
Bitwise Operators &, |, ^
Assignment Operators =, +=, -=
Contd..

•Arithmetic Operators: From highest to lowest precedence,


these are ** (exponential), * (multiplication), / (division), +
(addition), - (subtraction).

•Comparison Operators: These include == (equal), != (not


equal), <= (less than or equal to), >= (greater than or equal to),
< (less than), > (greater than).

•Logical Operators: not has the highest precedence, followed


by and, and then or.
Contd..

•Bitwise Operators: Bitwise AND &, OR |, and XOR ^.

•Assignment Operators: The assignment operator = is used to


set values, while += and -= are compound assignment operators
that perform an operation and an assignment in a single step.
Contd..

PEMDAS stands for Parentheses, Exponents,


Multiplication and Division, and Addition and Subtraction.
This acronym serves as a useful mnemonic to remember
the order of operations in Python.
Understanding PEMDAS is a must for any Python
programmer who wants to write error-free code.
Contd..

•Parentheses (): Anything in parentheses is evaluated first,


offering you a way to override other precedence rules.
•Exponents **: Exponential calculations are performed next.
•Multiplication and Division *, /: These are processed from left
to right. They have the same level of precedence, which is where
the left-to-right rule comes in.
•Addition and Subtraction +, -: These are the last to be
performed, also from left to right.
Contd..

Order Rule Component Operators


1st Parentheses ()
2nd Exponents **
3rd Multiplication and *, /
Division
4th Addition and +, -
Subtraction
Operations on Strings

Strings are sequences of characters enclosed in quotes (either


single quotes ' or double quotes ").
Python provides several built-in operations and methods to
manipulate and work with strings effectively.

Concatenation

Create strings using single quotes, double quotes, or triple


quotes
Contd..

Example:
s1 = 'Hello'
s2 = "World" Output:
s3 = '''This is a Hello
multi-line string''' World
This is a
print(s1) # Output: Hello multi-line string
print(s2) # Output: World
print(s3) # Output: This is a
# multi-line string
Contd..

Concatenation:

Joining two or more strings using the + operator:python

s1 = 'Hello'
s2 = 'World'
s3 = s1 + ' ' + s2 # Result: 'Hello
World'
Contd..

Repeating Strings:

Using the * operator to repeat a string:

s = 'Hello' * 3 # Result: 'HelloHelloHello'

Indexing and Slicing


Accessing characters or substrings
using indices:

s = 'Hello'
first_char = s[0] # 'H'
last_char = s[-1] # 'o'
substring = s[1:4] # 'ell'
Contd..
Leng
th

s = 'Hello'
length = len(s) # 5

String Methods
Python provides numerous built-in string methods:
1. Case Conversion
s = 'Hello World'
lowercase = s.lower() # 'hello
world'
uppercase = s.upper() # 'HELLO
WORLD'
titlecase = s.title() # 'Hello World'
Contd..
2. Trimming
Removing whitespace from the beginning and end:
s = ' Hello World '
trimmed = s.strip() # 'Hello World'

3. Searching
Finding substrings and checking conditions:

s = 'Hello World'
position = s.find('World') # 6
contains = 'World' in s # True
starts_with = s.startswith('He') # True
ends_with = s.endswith('ld') # True
Contd..
4. Replacing

s = 'Hello World'
new_s = s.replace('World', 'Python') # 'Hello Python'

5. Splitting and Joining


Splitting a string into a list and joining a list
into a string:
s = 'Hello World'
words = s.split() # ['Hello', 'World']
joined = ' '.join(words) # 'Hello World'
Contd..

Formatting
Strings
Using f-strings (formatted string literals) for interpolation:

name = 'Alice'
age = 30
greeting = f'Hello, {name}. You are {age} years
old.' # 'Hello, Alice. You are 30 years old.'
Escaping
Characters

s = 'He said, "Hello, World!"' #


Include double quotes within the string
newline = 'First line\nSecond line' #
Newline character
Contd..
Raw
Strings Using r to create raw strings where backslashes are
treated as literal characters:
path = r'C:\new_folder\test.txt' #
'C:\\new_folder\\test.txt'
Multi-line Strings
Using triple quotes for
multi-line strings:
multi_line = """This is a
multi-line
string"""
Composition

Composition refers to a design principle where a class is


composed of one or more objects from other classes.
Instead of inheriting from another class, a class contains
instances of other classes as attributes, enabling it to
utilize their functionality.
This allows for more flexible and modular code, as
objects can be composed and reused in different contexts.
Contd..

class Engine:
def __init__(self, horsepower, type):
self.horsepower = horsepower
self.type = type
def start(self):
print(f"The {self.type} engine with
{self.horsepower} horsepower starts.")
def stop(self):
print("The engine stops.")
class Car:
def __init__(self, make, model, engine):
self.make = make
self.model = model
self.engine = engine
Contd..

def start(self):
print(f"The {self.make}
{self.model} car starts.")
self.engine.start()

def stop(self):
print(f"The {self.make}
{self.model} car stops.")
self.engine.stop()

# Create an Engine object


engine = Engine(300, "V8")

# Create a Car object with the Engine


object
car = Car("Ford", "Mustang", engine)
Contd..

# Start the car


car.start()

# Stop the car


car.stop()

OUTPUT:

The Ford Mustang car starts.


The V8 engine with 300 horsepower starts.
The Ford Mustang car stops.
The engine stops.
Control Statements

It is used to control the flow of execution in a


program.
They include conditional statements, loops, and loop
control statements.

1. Conditional Statements
Conditional statements allow you to execute different
blocks of code based on certain conditions.

if statement: Executes a block of code if a condition is true.


if condition:
# code block
Contd..
if-else statement: Executes one block of code if a condition
is true, otherwise executes another block.
if condition:
# code block if condition is true
else:
# code block if condition is false
if-elif-else statement: Checks multiple conditions, executing
the corresponding block of code for the first true condition.
if condition1:
# code block if condition1 is true
elif condition2:
# code block if condition2 is true
else:
# code block if none of the
conditions are true
Contd..
2. Loops
Loops are used to repeatedly execute a block of code.
for loop: Iterates over a sequence (like a list, tuple, or
string).
for item in sequence:
# code block
Example:

for i in range(5):
print(i) OUTPUT:
0
1
2
3
4
Contd..

While loop: Repeats a block of code as long as a condition is


true.
while condition:
# code block

Example: OUTPUT:
i=0 0
while i < 5: 1
print(i) 2
i += 1 3
4
Contd..
3. Loop Control Statements
Loop control statements change the execution flow of loops.

break statement: Exits the loop prematurely.

Example:
for i in range(10): Output:
if i == 5: 0
break 1
print(i)
2
3
4
Contd..

continue statement: Skips the current iteration and continues


with the next one.

Output:
Example:
1
for i in range(10):
if i % 2 == 0: 3
continue 5
print(i) 7
9
Contd..

pass statement: Does nothing and is used as a placeholder.

Output:
Example:
for i in range(10): 0
if i % 2 == 0: 1
pass # This will be replaced with real 2
code later
3
print(i)
4
5
6
7
8
9
Contd..

Assert: Assert is a keyword used to test assumptions about your


code during development.
It's primarily used as a debugging aid to ensure that certain
conditions are met.

Syntax:
assert condition, message
Output:
Example:
x=5 Assertion passed
assert x == 5, "Value of x should be 5"
print("Assertion passed")
Contd..
Return: It is used to exit a function and optionally return a value to
the caller.

Syntax:
return [expression]
def say_hello(name):
def add_numbers(a, if name:
b): print(f"Hello, {name}!")
return a + b return
print("Hello, World!")
result =
add_numbers(3, 5) say_hello("Alice") # Output: Hello,
print(result) # Output: Alice!
8 say_hello("") # Output: Hello,
World!
Contd..
Example of Control Statements

# if-elif-else statement
x = 10
if x < 0:
print("Negative number")
elif x == 0:
print("Zero")
else:
print("Positive number")

# for loop with break and continue


for i in range(10):
if i == 3:
continue
if i == 7:
break
print(i)
Contd..

# while loop Output:


count = 0
while count < 5: Positive number
print(count) 0
count += 1 1
2
4
5
6
0
1
2
3
4
K
N
A U
H
T YO

You might also like