String Data Type
In Python, a string is a sequence of characters enclosed in quotes. Strings are immutable (cannot be changed after creation).
Creating Strings:
- Single quotes: 'Hello World'
- Double quotes: "Python Programming"
- Triple quotes: '''Multi-line strings''' or """Another multi-line string"""
String Operations
1. Concatenation (+)
Joining two strings together:
"Hello" + "World" → "HelloWorld"
2. Repetition (*)
Repeating a string multiple times:
"Hi" * 3 → "HiHiHi"
3. Indexing
Accessing individual characters using their position (starts from 0):
s = "Python" s[0] → 'P' s[3] → 'h' s[-1] → 'n' (negative index counts from end)
4. Slicing
Extracting a portion of the string:
s = "Programming" s[2:5] → 'ogr' (from index 2 to 4) s[:4] → 'Prog' (from start to index 3) s[6:] → 'mming' (from index 6 to end) s[::2] → 'Pormig' (every second character)
5. String Length (len())
Finding how many characters are in a string:
len("Hello") → 5
6. String Methods
Built-in functions that operate on strings:
- upper(): "hello".upper() → "HELLO"
- lower(): "HELLO".lower() → "hello"
- strip(): " hello ".strip() → "hello" (removes whitespace)
- split(): "a,b,c".split(",") → ['a', 'b', 'c']
- replace(): "hello".replace("l", "L") → "heLLo"
- find(): "hello".find("e") → 1 (returns index or -1 if not found)
7. String Formatting
Inserting values into strings:
name = "Alice" age = 25 f"Hello {name}, you are {age} years old" → "Hello Alice, you are 25 years old"
8. Escape Characters
Special characters in strings:
- \n: New line
- \t: Tab
- \\: Backslash
- \": Double quote
9. String Membership (in, not in)
Checking if a substring exists:
"ell" in "Hello" → True "xyz" not in "Hello" → True
10. String Comparison
Comparing strings alphabetically:
"apple" < "banana" → True "Hello" == "hello" → False (case-sensitive)
Defining Lists
A list is a collection of items in a particular order. Lists are:
- Mutable - can be changed after creation
- Ordered - items stay in the order you put them
- Can contain mixed data types - can store numbers, strings, other lists etc.
Creating Lists:
# Empty list empty_list = [] # List with items numbers = [1, 2, 3, 4, 5] fruits = ["apple", "banana", "cherry"] mixed = [1, "hello", 3.14, True]
List Slicing
Getting parts of a list using index positions:
Basic Syntax:
list[start:stop:step]
- start: Index where slice begins (included)
- stop: Index where slice ends (not included)
- step: Number of indices to move forward each time
Examples:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] numbers[2:5] → [2, 3, 4] # items from index 2 to 4 numbers[:4] → [0, 1, 2, 3] # items from start to index 3 numbers[5:] → [5, 6, 7, 8, 9] # items from index 5 to end numbers[::2] → [0, 2, 4, 6, 8] # every second item numbers[::-1] → [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] # reversed list
Tuple Data Type
A tuple is similar to a list but with key differences:
- Immutable - cannot be changed after creation
- Faster than lists for fixed data
- Used for data that shouldn't change
Creating Tuples:
# Empty tuple empty_tuple = () # Tuple with items colors = ("red", "green", "blue") coordinates = (10.5, 20.3) # Single item tuple (note the comma) single_item = (5,)
Tuple Operations:
- Accessing items: colors[1] → "green"
- Slicing: colors[1:] → ("green", "blue")
- Length: len(colors) → 3
- Concatenation: (1, 2) + (3, 4) → (1, 2, 3, 4)
- Repetition: ("Hi",) * 3 → ("Hi", "Hi", "Hi")
When to Use Tuples:
- When you need to protect data from accidental changes
- For fixed collections (like days of week, months)
- As dictionary keys (lists can't be dictionary keys)
- When performance matters (tuples are faster than lists)
Important Notes:
- You can't add, remove or change items in a tuple
- But you can create new tuples from existing ones
- Tuples can contain mutable objects like lists
Strings
Strings are sequences of characters used to represent text.
Key Features:
- Immutable: Cannot be changed after creation
- Indexed: Each character has a position number (starts at 0)
- Versatile: Many built-in methods for manipulation
Common Operations:
# Creation name = "Python Programming" # Access print(name[0]) # 'P' (first character) print(name[-1]) # 'g' (last character) # Slicing print(name[0:6]) # 'Python' # Methods print(name.upper()) # 'PYTHON PROGRAMMING' print(name.split()) # ['Python', 'Programming'] print(name.replace('P', 'J')) # 'Jython Jrogramming'
Lists
Lists are ordered collections of items that can be changed.
Key Features:
- Mutable: Can be modified after creation
- Ordered: Items maintain their position
- Flexible: Can hold different data types
Common Operations:
# Creation numbers = [1, 2, 3, 4] mixed = [1, "two", 3.0, True] # Access print(numbers[1]) # 2 # Modification numbers[0] = 10 # [10, 2, 3, 4] numbers.append(5) # [10, 2, 3, 4, 5] # Slicing print(numbers[1:3]) # [2, 3] # Methods numbers.sort() # Sorts the list numbers.reverse() # Reverses the list
Dictionaries
Dictionaries store data as key-value pairs for quick lookups.
Key Features:
- Unordered: No fixed order of items
- Mutable: Can be changed after creation
- Fast access: Values accessed by unique keys
Common Operations:
# Creation student = { "name": "John", "age": 20, "courses": ["Math", "Physics"] } # Access print(student["name"]) # 'John' print(student.get("age")) # 20 # Modification student["age"] = 21 # Update value student["grade"] = "A" # Add new key-value pair # Methods print(student.keys()) # ['name', 'age', 'courses', 'grade'] print(student.values()) # ['John', 21, ['Math', 'Physics'], 'A']
Building Blocks
These three data types form the foundation of Python programs because:
- Strings handle all text processing and input/output
- Lists manage collections of items and sequences
- Dictionaries organize data for efficient access and storage
Working Together Example:
# A simple student record system students = [ {"name": "Alice", "grades": [85, 90, 78]}, {"name": "Bob", "grades": [92, 88, 95]} ] for student in students: name = student["name"] average = sum(student["grades"])/len(student["grades"]) print(f"{name}'s average: {average:.2f}")
Key Differences
Feature | String | List | Dictionary |
---|---|---|---|
Mutable | No | Yes | Yes |
Ordered | Yes | Yes | No (Python 3.7+: insertion order preserved) |
Access Method | Index | Index | Key |
Use Case | Text data | Ordered collections | Key-value mappings |
String Manipulation Methods
Strings in Python have many built-in methods for manipulation:
Case Conversion:
- upper(): Converts to uppercase - "hello".upper() → "HELLO"
- lower(): Converts to lowercase - "HELLO".lower() → "hello"
- title(): Converts to title case - "hello world".title() → "Hello World"
Searching and Checking:
- find(): Returns index of substring - "hello".find("e") → 1
- startswith(): Checks if string starts with substring - "hello".startswith("he") → True
- endswith(): Checks if string ends with substring - "hello".endswith("lo") → True
Modification:
- replace(): Replaces substring - "hello".replace("l", "L") → "heLLo"
- strip(): Removes whitespace - " hello ".strip() → "hello"
- split(): Splits into list - "a,b,c".split(",") → ['a', 'b', 'c']
- join(): Joins list into string - ",".join(['a', 'b', 'c']) → "a,b,c"
List Manipulation Methods
Lists are mutable and have many manipulation methods:
Adding Elements:
- append(): Adds item to end - [1,2].append(3) → [1,2,3]
- insert(): Inserts at position - [1,3].insert(1,2) → [1,2,3]
- extend(): Adds multiple items - [1,2].extend([3,4]) → [1,2,3,4]
Removing Elements:
- remove(): Removes first matching value - [1,2,2].remove(2) → [1,2]
- pop(): Removes item at index - [1,2,3].pop(1) → [1,3]
- clear(): Removes all items - [1,2,3].clear() → []
Other Operations:
- sort(): Sorts list - [3,1,2].sort() → [1,2,3]
- reverse(): Reverses list - [1,2,3].reverse() → [3,2,1]
- count(): Counts occurrences - [1,2,2,3].count(2) → 2
- index(): Returns first index - [1,2,3].index(2) → 1
- copy(): Creates shallow copy - [1,2,3].copy() → [1,2,3]
Dictionary Manipulation Methods
Dictionaries store key-value pairs with these manipulation methods:
Accessing Elements:
- get(): Returns value for key - {"a":1}.get("a") → 1
- keys(): Returns all keys - {"a":1,"b":2}.keys() → ['a', 'b']
- values(): Returns all values - {"a":1,"b":2}.values() → [1, 2]
- items(): Returns key-value pairs - {"a":1}.items() → [('a', 1)]
Adding/Updating Elements:
- update(): Adds/updates items - {"a":1}.update({"b":2}) → {"a":1,"b":2}
- setdefault(): Gets value or sets default - {"a":1}.setdefault("b",2) → 2
Removing Elements:
- pop(): Removes key and returns value - {"a":1}.pop("a") → 1
- popitem(): Removes last inserted item - {"a":1,"b":2}.popitem() → ('b', 2)
- clear(): Removes all items - {"a":1}.clear() → {}
Other Operations:
- copy(): Creates shallow copy - {"a":1}.copy() → {"a":1}
- fromkeys(): Creates dict from keys - dict.fromkeys(['a','b'],0) → {'a':0,'b':0}
Examples
String Example:
text = " Hello, World! " clean_text = text.strip().lower() words = clean_text.split() # Result: ['hello,', 'world!']
List Example:
numbers = [3, 1, 4, 1, 5] numbers.sort() numbers.append(9) # Result: [1, 1, 3, 4, 5, 9]
Dictionary Example:
student = {"name": "John", "age": 21} student["courses"] = ["Math", "Physics"] age = student.pop("age") # Result: student = {'name': 'John', 'courses': ['Math', 'Physics']} # age = 21
String Built-in Functions
Strings in Python come with many useful functions for text processing:
Essential String Functions:
- len(): Returns length of string - len("hello") → 5
- str(): Converts other types to string - str(123) → "123"
- ord(): Gets ASCII value - ord('A') → 65
- chr(): Gets character from ASCII - chr(65) → 'A'
String Methods:
text = "Python Programming" print(text.upper()) # PYTHON PROGRAMMING print(text.lower()) # python programming print(text.find('Pro')) # 7 (index where 'Pro' starts) print(text.replace('Python', 'C')) # C Programming print(text.split()) # ['Python', 'Programming'] print('-'.join(['2023', '08', '15'])) # 2023-08-15
List Built-in Functions
Lists have powerful functions for collection manipulation:
Essential List Functions:
- len(): Returns length - len([1,2,3]) → 3
- list(): Converts to list - list("hello") → ['h','e','l','l','o']
- sorted(): Returns sorted list - sorted([3,1,2]) → [1,2,3]
- min()/max(): Finds smallest/largest - min([3,1,2]) → 1
- sum(): Sums numbers - sum([1,2,3]) → 6
List Methods:
numbers = [1, 2, 3] numbers.append(4) # [1,2,3,4] numbers.insert(1, 1.5) # [1,1.5,2,3,4] numbers.remove(2) # [1,1.5,3,4] numbers.pop() # [1,1.5,3] numbers.sort() # [1,1.5,3] numbers.reverse() # [3,1.5,1]
Dictionary Built-in Functions
Dictionaries provide efficient key-value pair operations:
Essential Dictionary Functions:
- len(): Counts pairs - len({'a':1,'b':2}) → 2
- dict(): Creates dictionary - dict([('a',1),('b',2)]) → {'a':1,'b':2}
- zip(): Combines lists into dict - dict(zip(['a','b'],[1,2])) → {'a':1,'b':2}
Dictionary Methods:
student = {'name':'John', 'age':21} print(student.get('name')) # John print(student.keys()) # dict_keys(['name', 'age']) print(student.values()) # dict_values(['John', 21]) student.update({'grade':'A'}) # {'name':'John','age':21,'grade':'A'} age = student.pop('age') # age=21, student={'name':'John','grade':'A'}
Examples
1. String Processing Program
sentence = "The quick brown fox jumps over the lazy dog" words = sentence.split() long_words = [word for word in words if len(word) > 3] word_count = {word:len(word) for word in words} # Result: long_words = ['quick', 'brown', 'jumps', 'over', 'lazy'] # word_count = {'The':3, 'quick':5, ..., 'dog':3}
2. List Processing Program
numbers = [5, 2, 8, 1, 9, 3] sorted_nums = sorted(numbers) even_nums = [num for num in numbers if num%2 == 0] stats = { 'min': min(numbers), 'max': max(numbers), 'avg': sum(numbers)/len(numbers) } # Result: sorted_nums = [1,2,3,5,8,9] # even_nums = [2, 8] # stats = {'min':1, 'max':9, 'avg':4.666...}
3. Dictionary Processing Program
inventory = { 'apples': 50, 'bananas': 25, 'oranges': 30 } # Add new item inventory['pears'] = 40 # Update quantity inventory['apples'] += 10 # Find items with low stock low_stock = {item:qty for item,qty in inventory.items() if qty < 30} # Result: low_stock = {'bananas':25}
Important Notes
- Strings are immutable - methods return new strings
- Lists are mutable - methods modify the original list
- Dictionary keys must be immutable (strings, numbers, tuples)
- Built-in functions work across all Python versions
- List comprehensions and dictionary comprehensions are powerful tools
Python Functions
A function is a block of reusable code that performs a specific task.
Key Features of Functions:
- Reusability: Write once, use multiple times
- Modularity: Break complex problems into smaller parts
- Abstraction: Hide implementation details
- Organization: Makes code more readable and maintainable
Function Components:
def function_name(parameters): """docstring - describes what the function does""" # Function body statements return [expression] # Optional return statement
Example Function:
def calculate_area(length, width): """Calculates area of a rectangle""" area = length * width return area # Calling the function result = calculate_area(5, 3) print(result) # Output: 15
Types of Functions
Built-in Functions:
Predefined in Python (print(), len(), input(), etc.)
User-defined Functions:
Created by programmers to perform specific tasks
Lambda Functions:
Small anonymous functions defined with lambda keyword
square = lambda x: x * x print(square(5)) # Output: 25
Function Parameters and Arguments
Positional Arguments:
def greet(name, message): print(f"{message}, {name}!") greet("Alice", "Hello") # Output: Hello, Alice!
Keyword Arguments:
greet(message="Hi", name="Bob") # Output: Hi, Bob!
Default Parameters:
def greet(name, message="Hello"): print(f"{message}, {name}!") greet("Charlie") # Output: Hello, Charlie!
Variable-length Arguments:
def sum_numbers(*args): return sum(args) print(sum_numbers(1, 2, 3)) # Output: 6
Organizing Code Using Functions
Benefits of Organized Code:
- - Readability: Easier to understand
- - Maintainability: Easier to modify and debug
- - Reusability: Avoid code duplication
- - Collaboration: Easier for teams to work together
Best Practices:
- - Single Responsibility: Each function should do one thing
- - Descriptive Names: Use clear function names
- - Proper Documentation: Include docstrings
- - Reasonable Size: Keep functions short (10-20 lines)
- - Limit Parameters: 3-4 parameters maximum
Example of Well-organized Code:
def calculate_bmi(weight, height): """Calculate Body Mass Index""" return weight / (height ** 2) def classify_bmi(bmi): """Classify BMI into categories""" if bmi < 18.5: return "Underweight" elif 18.5 <= bmi < 25: return "Normal" elif 25 <= bmi < 30: return "Overweight" else: return "Obese" def main(): """Main program function""" weight = float(input("Enter weight in kg: ")) height = float(input("Enter height in meters: ")) bmi = calculate_bmi(weight, height) category = classify_bmi(bmi) print(f"Your BMI is {bmi:.1f} ({category})") if __name__ == "__main__": main()
Function Scope and Lifetime
Local Variables:
Variables defined inside a function, only accessible within that function
Global Variables:
Variables defined outside functions, accessible throughout program
Example:
global_var = "I'm global" def test_scope(): local_var = "I'm local" print(global_var) # Can access global print(local_var) # Can access local test_scope() print(global_var) # Works print(local_var) # Error - local_var not defined here
Return Values
- Functions can return any Python object
- Can return multiple values as a tuple
- If no return statement, function returns None
Multiple Return Values:
def min_max(numbers): return min(numbers), max(numbers) smallest, largest = min_max([5, 2, 8, 1, 9]) print(smallest, largest) # Output: 1 9
Practical Applications
- - Mathematical calculations
- - Data processing and transformation
- - File operations
- - Creating reusable utility functions
- - Breaking down complex algorithms
No comments:
Post a Comment