Unit 3 Python
Unit 3 Python
Example:
text = "Hello, World!"
print(text[0]) # Output: H
print(text[0:5]) # Output: Hello
print(text.lower()) # Output: hello, world!
Example:
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # Output: [2, 3, 4]
numbers.append(6)
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
List Slicing
# Reverse a list
reversed_list = numbers[::-1]
step_slice = numbers[::3]
mid_slice = numbers[2:-1]
Example:
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
# A simple tuple
coordinates = (10, 20)
data = 1, 2, 3
# An empty tuple
empty = ()
single_element = (42,)
Tuple Slicing
t = (1, 2, 3, 4, 5)
print(color)
4. Dictionary Manipulation
Dictionaries are unordered collections of key-value pairs. They are defined using curly
braces {}.
Example:
student = {"name": "Alice", "age": 23}
print(student["name"]) # Output: Alice
student["age"] = 24
print(student) # Output: {'name': 'Alice', 'age': 24}
5. Manipulation Methods
String Methods: upper(), lower(), find(), replace(), split()
List Methods: append(), remove(), pop(), sort(), reverse()
Dictionary Methods: keys(), values(), items(), get(), update()
6. Programming Examples
Example 1: String Functions
text = "Python Programming"
print(text.replace("Python", "Java")) # Output: Java Programming
Example:
def greet(name):
return "Hello " + name
for i in range(6):
print(fibonacci(i), end=" ") # Output: 0 1 1 2 3 5