Python Programming Cheat Sheet
Python Programming Cheat Sheet
Tuples should be used over lists when you need a collection of items that should not change throughout the program, as tuples are immutable, meaning their elements cannot be altered. Key differences include: tuples use parentheses (coords = (4, 5)) and are immutable, while lists use brackets and are mutable (e.g., fruits = ['apple', 'banana', 'cherry']).
Reading from and writing to a file in Python involves using the open() function with specified modes ('r' for reading, 'w' for writing). To write to a file: with open('file.txt', 'w') as f: f.write('Hello!'). To read from a file: with open('file.txt', 'r') as f: print(f.read()). File operations are essential for data persistence, allowing you to store data permanently beyond the life of the program execution .
Object instantiation in Python involves creating an instance of a class using the class constructor. This is done with the class name followed by parentheses. For example, defining a class Dog and creating an object involves: class Dog: def __init__(self, name): self.name = name; def bark(self): print(f'{self.name} says woof!'); d = Dog('Buddy'); d.bark() outputs 'Buddy says woof!' .
To determine if a number is positive, zero, or negative in Python, you can use an if-else control flow structure. For example: if x > 0, the number is positive; elif x == 0, it is zero; else, it is negative. Example code: x = 5; if x > 0: print('Positive'); elif x == 0: print('Zero'); else: print('Negative').
Exception handling improves program robustness by allowing a program to continue running or gracefully exit with informative feedback when errors occur, rather than crashing. A specific error type can be caught using try-except blocks. For example, handling a ZeroDivisionError with try: x = 1 / 0; except ZeroDivisionError: print('Cannot divide by zero.'); displays an error message without terminating the program abruptly .
To add a new fruit to a list in Python, you use the append() method. This method adds the specified element to the end of the list. For example: fruits = ['apple', 'banana', 'cherry']; fruits.append('mango') results in ['apple', 'banana', 'cherry', 'mango'].
Comments in Python, denoted by the '#' symbol, play a crucial role in documenting code. They improve code readability and maintainability by explaining the purpose and function of code segments, making it easier for others (or the original developer at a later time) to understand the code's intent and logic, thus enhancing code quality .
A simple function to greet users can be defined in Python using the def keyword. For example: def greet(name): return f'Hello, {name}'; print(greet('John')) outputs 'Hello, John'. Functions are useful because they allow code reusability, modularity, and better organization by encapsulating logic into named blocks of code that can be easily called and reused .
Modules and libraries in Python provide reusable code, allowing programmers to leverage existing functionalities for efficient and organized coding without reinventing the wheel. For instance, using the math library to apply a mathematical function involves: import math; print(math.sqrt(16)) outputs 4.0, demonstrating how easily complex operations can be performed .
Dictionaries in Python are useful when you need to store key-value pairs and retrieve data based on unique keys. You would use them in situations requiring fast lookups, such as storing user information where keys are usernames. To retrieve an element by its key, use the syntax: person = {'name': 'Alice', 'age': 25}; print(person['name']) outputs 'Alice' .