0% found this document useful (0 votes)
8 views2 pages

Python Basics Examples

The document provides an overview of Python basics, including types of operators, control flow statements, string immutability, leap year calculation, and function definition. It includes code examples demonstrating arithmetic, assignment, comparison, logical, bitwise, membership, and identity operators, as well as loops and functions. Each section illustrates key concepts with practical code snippets.
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)
8 views2 pages

Python Basics Examples

The document provides an overview of Python basics, including types of operators, control flow statements, string immutability, leap year calculation, and function definition. It includes code examples demonstrating arithmetic, assignment, comparison, logical, bitwise, membership, and identity operators, as well as loops and functions. Each section illustrates key concepts with practical code snippets.
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

Python Basics - Examples with Code

1. Types of Operators in Python

# Arithmetic Operators
a = 10
b = 3
print("Addition:", a + b) # 13
print("Power:", a ** b) # 1000

# Assignment Operators
a += 5
print("After += :", a) # 15

# Comparison Operators
print("a > b:", a > b) # True

# Logical Operators
print("True and False:", True and False) # False

# Bitwise Operators
print("Bitwise AND:", 5 & 3) # 1

# Membership Operators
print("a in [5, 15]:", a in [5, 15]) # True

# Identity Operators
x = [1, 2]
y = x
print("x is y:", x is y) # True

2. Control Flow Statements

# if-elif-else and loops


num = 7
if num > 0:
print("Positive")
elif num == 0:
print("Zero")
else:
print("Negative")

# For loop
for i in range(3):
print("Loop:", i)

# While loop
count = 0
while count < 3:
print("While count:", count)
count += 1
Python Basics - Examples with Code

3. Strings in Python are Immutable

s = "python"
# s[0] = 'P' # This will cause an error

# Correct way:
s = "P" + s[1:]
print("Modified string:", s) # Python

4. Program to Find Leap Year or Not

year = int(input("Enter a year: "))


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")

# Example input/output:
# Enter a year: 2024
# 2024 is a leap year

5. Functions in Python

# Define a function
def add_numbers(a, b):
return a + b

# Call the function


result = add_numbers(5, 10)
print("Sum:", result) # 15

You might also like