PYTHON PROGRAMMING Unit 2
PYTHON PROGRAMMING Unit 2
UNIT II
Evaluating Expressions
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:
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..
# 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
Category Operators
Arithmetic Operators **, *, /, +, -
Comparison Operators ==, !=, <=, >=, <, >
Logical Operators not, and, or
Bitwise Operators &, |, ^
Assignment Operators =, +=, -=
Contd..
Concatenation
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:
s1 = 'Hello'
s2 = 'World'
s3 = s1 + ' ' + s2 # Result: 'Hello
World'
Contd..
Repeating Strings:
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'
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
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()
OUTPUT:
1. Conditional Statements
Conditional statements allow you to execute different
blocks of code based on certain conditions.
for i in range(5):
print(i) OUTPUT:
0
1
2
3
4
Contd..
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.
Example:
for i in range(10): Output:
if i == 5: 0
break 1
print(i)
2
3
4
Contd..
Output:
Example:
1
for i in range(10):
if i % 2 == 0: 3
continue 5
print(i) 7
9
Contd..
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..
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")