0% found this document useful (0 votes)
14 views3 pages

Python Programming Cheat Sheet

This document is a cheat sheet for Python programming, covering basic syntax, variables, data types, data structures, control flow, functions, classes, file handling, modules, and exception handling. It provides examples for each topic, such as printing, using lists, dictionaries, loops, defining functions, and handling exceptions. The notes serve as a quick reference guide for essential Python concepts and operations.

Uploaded by

shreenimk23
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)
14 views3 pages

Python Programming Cheat Sheet

This document is a cheat sheet for Python programming, covering basic syntax, variables, data types, data structures, control flow, functions, classes, file handling, modules, and exception handling. It provides examples for each topic, such as printing, using lists, dictionaries, loops, defining functions, and handling exceptions. The notes serve as a quick reference guide for essential Python concepts and operations.

Uploaded by

shreenimk23
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 Notes Cheat Sheet

1. Basic Syntax
# This is a comment
print("Hello, world!")

2. Variables and Data Types


x = 10 # Integer
y = 3.14 # Float
name = "John" # String
is_valid = True # Boolean

3. Data Structures - Lists


fruits = ["apple", "banana", "cherry"]
[Link]("mango")
print(fruits[1]) # banana

Tuples
coords = (4, 5)

Dictionaries
person = {"name": "Alice", "age": 25}
print(person["name"])

Sets
unique = {1, 2, 3}

4. Control Flow - If-Else


x = 5
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")

Loops
# For loop
Python Notes Cheat Sheet

for i in range(5):
print(i)

# While loop
i = 0
while i < 5:
print(i)
i += 1

5. Functions
def greet(name):
return f"Hello, {name}"

print(greet("John"))

6. Classes and Objects


class Dog:
def __init__(self, name):
[Link] = name

def bark(self):
print(f"{[Link]} says woof!")

d = Dog("Buddy")
[Link]()

7. File Handling
# Write to file
with open("[Link]", "w") as f:
[Link]("Hello!")

# Read from file


with open("[Link]", "r") as f:
print([Link]())

8. Modules and Libraries


import math
print([Link](16)) # 4.0
Python Notes Cheat Sheet

9. Exception Handling
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Done.")

Common questions

Powered by AI

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' .

You might also like