0% found this document useful (0 votes)
2 views8 pages

Python Programming

The document provides examples of various Python programming concepts including arithmetic operations, comparison operators, string manipulation, list operations, tuples, dictionaries, sets, and binary types. It illustrates how to create, modify, and access different data types with practical code snippets. Additionally, it explains the use of methods and functions associated with these data types.

Uploaded by

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

Python Programming

The document provides examples of various Python programming concepts including arithmetic operations, comparison operators, string manipulation, list operations, tuples, dictionaries, sets, and binary types. It illustrates how to create, modify, and access different data types with practical code snippets. Additionally, it explains the use of methods and functions associated with these data types.

Uploaded by

Anita Choudhary
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Example (Arithmetic operations)

x = 25
y=7
print(x + y) # 32 addition
print(x - y) # 18 subtraction
print(x * y) # 175 multiplication
print(x / y) # 3.5714285714285716 ← float division (important!)
print(x // y) # 3 floor division (integer result)
print(x % y) # 4 remainder (modulo)
print(x ** y) # 6103515625 exponentiation (25⁷)

# Also works with very large numbers


print(2 ** 64) # 18446744073709551616
print(2 ** 1000 % 100) # 76 ← modular exponentiation still fast

Example (Comparison Operators (return bool))


Python
a = 100
b = 200
c = 100
print(a == b) # False
print(a != b) # True
print(a < b) # True
print(a <= c) # True
print(b > a) # True
print(a >= c) # True

Cycling through indices (modulo trick)


items = ["pen", "book", "laptop"]
for i in range(10):
print(items[i % len(items)]) # cycles: pen → book → laptop → pen → ...

String Example 1:
# 1. Create the pieces
greeting = "Hello"
name = "Anita"
# 2. Concatenate them
full = greeting + ", " + name + "!"
# 3. See the result
print(full) # Hello, Anita!
# Bonus: show types
print(type(greeting)) # <class 'str'>
print(type(full)) # <class 'str'>

String Example 2:
# Assigning strings
greeting = "Hello"
name = 'World' # Single or double quotes are fine
# Concatenation and slicing
full = greeting + ", " + name + "!"
slice_ex = full[0:5] # Slices the string from index 0 to 4 (end is exclusive), extracting "Hello".
# Printing
print(full) # Output: Hello, World!
print(slice_ex) # Output: Hello
print(type(greeting)) # Output: <class 'str'>
String Methods (upper() and split() ) Example 1:
sentence = "apple banana cherry date"
# Split on whitespace (default behavior)
words = [Link]() # ['apple', 'banana', 'cherry', 'date']
print(words)
print(len(words)) #4
Example 2: Case conversion methods
text = "Hello World! Python is FUN"
# Convert to uppercase print([Link]()) # HELLO WORLD! PYTHON IS FUN
# Convert to lowercase print([Link]()) # hello world! python is fun
# Title Case → First letter of each word capital print([Link]()) # Hello World! Python Is Fun
# Capitalize → Only first letter of the whole string print("python is great".capitalize()) # Python is great
# Swap case → uppercase ↔ lowercase print("PyThOn".swapcase()) # pYtHoN
List Example 1:
# Creating a list
fruits = ["apple", "banana", "cherry"] # Creates a list with three string elements. Lists use square brackets.
# Modifying
[Link]("date") # Adds "date" to the end of the list (mutable operation).
fruits[1] = "blueberry" # Change index 1(Replaces the element at index 1 ("banana") with "blueberry")
# Printing
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'date']
print(type(fruits)) # Output: <class 'list'>
List Example 2( pop -> removing and returning an element):
tasks = ["study", "eat", "code", "sleep"]
# Remove last item
last = [Link]() #pop() remove and get one item
print(last) # sleep
print(tasks) # ['study', 'eat', 'code']
# Remove item from position 1
second = [Link](1)
print(second) # eat
print(tasks) # ['study', 'code']
# Remove first item
first = [Link](0)
print(first) # study
print(tasks) # ['code']
List Example 3 (Slicing : getting sub-lists / parts of the list)
# 0 1 2 3 4 5
fruits = ["apple", "banana", "mango", "kiwi", "orange", "grapes"]
print(fruits[0:3]) # ['apple', 'banana', 'mango']
print(fruits[2:5]) # ['mango', 'kiwi', 'orange']
print(fruits[:3]) # ['apple', 'banana', 'mango'] ← from start
print(fruits[3:]) # ['kiwi', 'orange', 'grapes'] ← till end
print(fruits[:]) # whole list copy
# Every second item
print(fruits[::2]) # ['apple', 'mango', 'orange']
# Reverse the list
print(fruits[::-1]) # ['grapes', 'orange', 'kiwi', 'mango', 'banana', 'apple']
Explanation:
# Positions: 0 1 2 3 4 5
fruits = ["apple", "banana", "mango", "kiwi", "orange", "grapes"]
Most important rule of slicing
fruits[start : end : step]
start → included
end → not included
step → how we jump (optional)

print(fruits[0:3])
# start = 0 end = 3
# → positions 0, 1, 2
# → apple, banana, mango

print(fruits[2:5])
# start = 2 end = 5
# → positions 2, 3, 4
# → mango, kiwi, orange

print(fruits[:3])
# start = missing → means 0
# end = 3
# → same as [0:3]
# → apple, banana, mango

print(fruits[3:])
# start = 3
# end = missing → means go to the very end
# → kiwi, orange, grapes

print(fruits[:])
# start = missing → 0
# end = missing → end of list
# → whole list (but this is a **copy**)

print(fruits[::2])
# step = 2 → take every second item
# start from 0 → 0, 2, 4
# → apple, mango, orange

print(fruits[::-1])
# step = -1 → go backwards
# start from end → end, end-1, end-2, ...
# → grapes, orange, kiwi, mango, banana, apple
List Example 4(Indexing (accessing single elements)
Indexing – Accessing single elements
Python
# 0 1 2 3 4 5 6
fruits = ["apple", "banana", "mango", "kiwi", "orange", "grapes", "cherry"]
# Basic positive indexing
print(fruits[0]) # apple → first item
print(fruits[3]) # kiwi
print(fruits[-1]) # cherry → last item
print(fruits[-2]) # grapes → second last
# Common mistake beginners make
# print(fruits[7]) # IndexError: list index out of range
# print(fruits[-8]) # IndexError: list index out of range
# Safe way (recommended in real code)
if len(fruits) > 5:
print(fruits[5]) # grapes
else:
print("Not enough fruits")
Example 1(Tuple: Immutable, ordered collection (like list but can't be changed)
# Creating a tuple
coords = (10, 20, 30)
# Accessing
x = coords[0]
# Printing
print(coords) # Output: (10, 20, 30)
print(x) # Output: 10
print(type(coords)) # Output: <class 'tuple'>
Line-by-Line Explanation:
 coords = (10, 20, 30): Creates a tuple with integers. Tuples use parentheses.
 x = coords[0]: Accesses the first element by index (tuples support indexing but not modification).
 print(coords): Outputs the tuple.
 print(x): Outputs the extracted value.
 print(type(coords)): Confirms tuple type.
Example (Mapping Type: Dictionary (dict))
# Creating a dict
person = {"name": "Alice", "age": 30, "city": "New York"}
# Modifying and accessing
person["age"] = 31
age = [Link]("age")
# Printing
print(person) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York'}
print(age) # Output: 31
print(type(person)) # Output: <class 'dict'>
Line-by-Line Explanation:
 person = {"name": "Alice", "age": 30, "city": "New York"}: Creates a dictionary with string keys and mixed
values.
 person["age"] = 31: Updates the value for key "age" (mutable).
 age = [Link]("age"): Safely retrieves the value for "age" using .get() method (returns None if key
missing).
 print(person): Outputs the updated dict (order may vary as dicts are unordered before Python 3.7, but insertion
order preserved since).
 print(age): Outputs the retrieved value.
 print(type(person)): Confirms dict type.
Example (Set data type)
# Creating a set
colors = {"red", "green", "blue"}
# Modifying
[Link]("yellow")
[Link]("green")
# Printing
print(colors) # Output: {'blue', 'red', 'yellow'} (order may vary)
print(type(colors)) # Output: <class 'set'>
# Example 1 – using | operator (most common way) (Union (all elements from both sets)
fruits = {"apple", "banana", "mango", "kiwi"} vegetables = {"carrot", "tomato", "potato", "kiwi"} # kiwi is in both
# Union using | all_items = fruits | vegetables
print(all_items) # Possible output: {'apple', 'banana', 'mango', 'kiwi', 'carrot', 'tomato', 'potato'} # (order can be different
every time)
# Example 2 – using .union() method
a = {1, 2, 3, 4} b = {3, 4, 5, 6} c = {5, 6, 7, 8}
result = [Link](b, c) # can combine multiple sets at once
print(result) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
# Example 1 – using & operator (most common) (Intersection (common elements only)
(Intersection = elements that are in BOTH sets (A AND B)
students_python = {"Anita", "Rahul", "Priya", "Vikram", "Sohan"} students_java = {"Rahul", "Priya", "Mohan",
"Neha"}
common = students_python & students_java
print(common) # Output: {'Rahul', 'Priya'} (only students in both classes)
Example (Frozenset)
# Creating a frozenset
frozen_colors = frozenset(["red", "green"])
# Printing
print(frozen_colors) # Output: frozenset({'red', 'green'})
print(type(frozen_colors)) # Output: <class 'frozenset'>
Line-by-Line Explanation:
 frozen_colors = frozenset(["red", "green"]): Creates an immutable set from a list.
 print(frozen_colors): Outputs the frozenset.
 print(type(frozen_colors)): Confirms type (can't add/remove after creation).
Example(Boolean type)
age = 17
# Comparison operators → give True or False
is_adult = age >= 18
is_teen = age >= 13 and age <= 19
is_child = age < 13
print(is_adult) # False
print(is_teen) # True
print(is_child) # False

Explanation:
age = 17 # Line 1: normal number
is_adult = age >= 18 # Line 2: asks "is age 18 or more?" → False
is_teen = age >= 13 and age <= 19 # Line 3: two conditions with AND → True
is_child = age < 13 # Line 4: asks "is age less than 13?" → False
print(is_adult) # Line 5: shows False

What are binary types?


They are used when you want to work with raw bytes (not normal text).
Examples where you meet bytes:
Reading image files, PDF files, video files
Downloading data from the internet
Sending/receiving data over network (sockets)
Working with old files, hardware, protocols
Normal strings ("hello") are text → bytes are raw numbers 0–255
Example:
1. bytes (cannot be changed = immutable)
Python# Very simple example
data = b'hello' # ← notice the b before the quotes
print(data) # b'hello'
print(len(data)) #5
print(data[0]) # 104 ← number for letter 'h'
print(data[1]) # 101 ← number for 'e'

Line-by-line Explanation:
Pythondata = b'hello' # creates bytes object (5 bytes long)
# each letter became its ASCII number
print(data) # shows b'hello' ← b means bytes
print(len(data)) # 5 characters = 5 bytes
print(data[0]) # 104 ← ASCII code of 'h'
print(data[1]) # 101 ← ASCII code of 'e'
print(data[2]) # 108 ← 'l'
print(data[3]) # 108 ← 'l'
print(data[4]) # 111 ← 'o'
# You CANNOT change it:
# data[0] = 72 # ← ERROR! bytes are read-only
bytearray (can be changed = mutable)
Example:

ba = bytearray(b'hello')
print(ba) # bytearray(b'hello')
ba[0] = 72 # change first byte → 'H' (72 = ASCII of H)
print(ba) # bytearray(b'Hello')
[Link](33) # add '!' (33 = ASCII of !)
print(ba) # bytearray(b'Hello!')
ba[1:3] = b'ey' # replace positions 1 and 2
print(ba) # bytearray(b'Heylo!')

Line-by-line Explanation:

ba = bytearray(b'hello') # create changeable version of b'hello'


ba[0] = 72 # change byte at position 0 from 104→72
# 104 was 'h' → 72 is 'H'
print(ba) # now starts with 'H'
[Link](33) # add one more byte at the end (33 = '!')
# like [Link]() but for bytes
ba[1:3] = b'ey' # replace two bytes with new two bytes
# position 1 and 2: 'e'+'l' → 'e'+'y'

List examples:

1) fruits = ["apple", "banana", "mango", "orange", "grapes"]


# First 3 items (index 0, 1, 2)
print(fruits[:3])

# List of 10 different fruits


2) base_fruits = [
"apple", "banana", "mango", "orange", "grapes",
"pineapple", "kiwi", "strawberry", "blueberry", "cherry"
]
# Repeat 5 times → 50 fruits total
fruits = base_fruits * 5
# Show result
print("Total fruits:", len(fruits)) # should print 50
print("First 15 fruits:")
print(fruits[:15])

You might also like