Python Assignment CH 1 & CH 2
Python Assignment CH 1 & CH 2
1. Define variables of different data types, initialize them, and display their values.
# Arithmetic operators
a = 10
b = 3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
# Comparison operators
print("Greater than:", a > b)
print("Less than:", a < b)
print("Equal to:", a == b)
print("Not equal to:", a != b)
# Logical operators
x = True
y = False
print("Logical AND:", x and y)
print("Logical OR:", x or y)
print("Logical NOT:", not x)
# Assignment operators
c = 5
c += 2 # Equivalent to c = c + 2
print("Value of c after addition:", c)
# String demonstration
message = "Hello, Python!"
print("Original Message:", message)
# String methods
print("Uppercase:", message.upper())
print("Lowercase:", message.lower())
print("Length of the string:", len(message))
print("Index of 'Python':", message.find("Python"))
Brief explanation of constants, variables, expressions, keywords, and statements
available in Python:
• Constants: Fixed values like numbers, strings, etc., whose values do not change.
• Variables: Containers to store data values. Their values can change during program
execution.
• Expressions: Combinations of values, variables, operators, and calls to functions that
are evaluated to produce a value.
• Keywords: Reserved words in Python that have special meanings and cannot be used
as identifiers.
• Statements: Instructions that the Python interpreter can execute, such as assignments,
loops, conditional statements, etc.
Chapter 2
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
# Example usage:
year = 2024
if is_leap_year(year):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
python
Copy code
def sum_first_20_odd_numbers():
sum_odd = 0
count = 0
num = 1
return sum_odd
# Example usage:
length = 5
width = 3
print("Area of rectangle with length", length, "and width", width, "is:",
area_rectangle(length, width))
• break statement: Terminates the current loop (for loop, while loop) and transfers
control to the next statement outside the loop.
• continue statement: Skips the rest of the current iteration of a loop and jumps to the
next iteration of the loop.
These statements are used to control the flow of loops in Python programs.