Python Cheatsheet for Beginners

Python Cheatsheet for Beginners

Python Cheatsheet for Beginners

1. Variables and Data Types

Python supports various data types such as strings, integers, floats, lists, etc.

# Example of variable assignment
name = "Alice"
age = 25
height = 5.6
is_student = True
my_list = [1, 2, 3, 4]

2. Basic Operators

Operators allow us to perform operations on variables and values.

# Arithmetic Operators
sum = 10 + 5      # Addition
difference = 10 - 5  # Subtraction
product = 10 * 5  # Multiplication
quotient = 10 / 5  # Division

# Comparison Operators
x = 5
y = 10
print(x == y)  # Equal to
print(x != y)  # Not equal to
print(x < y)   # Less than

3. Conditional Statements

Conditional statements allow you to execute code based on certain conditions.

# If-else statement
age = 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.") 

4. Loops

Loops let you execute a block of code multiple times.

# For loop
for i in range(5):  # Will print numbers 0 to 4
    print(i)

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

5. Functions

Functions are reusable blocks of code that you can call with a name.

# Function definition
def greet(name):
    return "Hello, " + name

# Function call
message = greet("Alice")
print(message)  # Output: Hello, Alice

6. Lists

Lists are ordered collections of items in Python.

# List creation
fruits = ["apple", "banana", "cherry"]

# Accessing list elements
print(fruits[0])  # apple

# Adding an element to the list
fruits.append("orange")

# Removing an element from the list
fruits.remove("banana")

7. Dictionaries

Dictionaries store data in key-value pairs.

# Dictionary creation
person = {"name": "Alice", "age": 25, "city": "New York"}

# Accessing dictionary values
print(person["name"])  # Alice

# Adding a new key-value pair
person["job"] = "Engineer"

8. Importing Libraries

Python allows you to use additional libraries by importing them.

Leave a Reply

Your email address will not be published. Required fields are marked *