0% found this document useful (0 votes)
4 views15 pages

Python Crash Course

The document is a comprehensive Python crash course designed for complete beginners, covering essential topics such as variables, data types, loops, functions, and error handling. It includes practical examples, mini projects, and tips for further learning. The course emphasizes Python's simplicity and versatility, making it accessible for new programmers.

Uploaded by

Namra Rehman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views15 pages

Python Crash Course

The document is a comprehensive Python crash course designed for complete beginners, covering essential topics such as variables, data types, loops, functions, and error handling. It includes practical examples, mini projects, and tips for further learning. The course emphasizes Python's simplicity and versatility, making it accessible for new programmers.

Uploaded by

Namra Rehman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

🐍 Python Crash Course

For Complete Beginners


Learn Python from scratch — simple, clear, and practical

Topics Covered
1. What is Python & Setup
2. Variables & Data Types
3. User Input & Output
4. Operators
5. Conditionals (if/else)
6. Loops (for & while)
7. Functions
8. Lists, Tuples & Dictionaries
9. String Methods
10. File Handling
11. Error Handling
12. Mini Projects
Chapter 1: What is Python?
Python is a beginner-friendly, versatile programming language used in web development, data
science, artificial intelligence, automation, and much more. It reads almost like plain English, which
makes it perfect for beginners.

Why Python?
• Simple and readable syntax
• Huge community and tons of free resources
• Used by Google, Netflix, NASA, and thousands of companies
• Works on Windows, Mac, and Linux

How to Install Python


• Go to [Link] and download the latest version
• During installation on Windows, check "Add Python to PATH"
• Open your terminal (or Command Prompt) and type: python --version
• Use VS Code or IDLE as your code editor

Your First Program


Let's write the classic "Hello, World!" program:

# This is a comment — Python ignores it


print("Hello, World!")

# Output:
# Hello, World!

💡 Tip: Always save your Python files with a .py extension, for example: [Link]
Chapter 2: Variables & Data Types
A variable is like a container that stores data. You can name it anything (no spaces), and Python
figures out the data type automatically.

Creating Variables
name = "Alice" # String (text)
age = 25 # Integer (whole number)
height = 5.7 # Float (decimal number)
is_student = True # Boolean (True or False)

print(name) # Alice
print(age) # 25
print(type(age)) # <class 'int'>

The Four Main Data Types


Type Example Description
str "Hello" Text / words
int 42 Whole numbers
float 3.14 Decimal numbers
bool True / False Yes/No values
Chapter 3: Input & Output
Python lets you print messages to the screen and ask the user to type something in.

Printing Output
print("Hello!") # Basic print
print("My name is", "Alice") # Multiple items
name = "Bob"
print(f"Hello, {name}!") # f-string (recommended)
print("Score:", 95)

Getting User Input


name = input("What is your name? ") # Waits for user to type
print("Nice to meet you,", name)

# input() always returns a string!


# To use it as a number, convert it:
age = int(input("How old are you? "))
print("Next year you will be", age + 1)

💡 Tip: f-strings are the easiest way to include variables in your text. Just wrap them in
curly braces: f"Hello, {name}!"
Chapter 4: Operators
Operators let you do math and compare values.

Math Operators
x = 10
y = 3

print(x + y) # 13 → Addition
print(x - y) # 7 → Subtraction
print(x * y) # 30 → Multiplication
print(x / y) # 3.33 → Division
print(x // y) # 3 → Floor division (no decimal)
print(x % y) # 1 → Modulus (remainder)
print(x ** y) # 1000 → Power (10 to the 3rd)

Comparison Operators (return True or False)


print(5 == 5) # True → Equal to
print(5 != 3) # True → Not equal to
print(5 > 3) # True → Greater than
print(5 < 3) # False → Less than
print(5 >= 5) # True → Greater than or equal
print(5 <= 4) # False → Less than or equal

Logical Operators
print(True and False) # False → both must be True
print(True or False) # True → at least one True
print(not True) # False → flips the value
Chapter 5: Conditionals (if / elif / else)
Conditionals let your program make decisions. If something is true, do this. Otherwise, do that.

Basic if/else
age = 18

if age >= 18:


print("You are an adult.")
else:
print("You are a minor.")

Multiple Conditions with elif


score = 75

if score >= 90:


print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")

💡 Tip: Python uses INDENTATION (4 spaces) to define code blocks. This is mandatory
— always indent code inside if/else.
Chapter 6: Loops
Loops let you repeat a block of code multiple times without writing it over and over.

for Loop — Loop Through a Sequence


# Loop through a range of numbers
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4

# Loop through a list


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

while Loop — Loop While a Condition is True


count = 0

while count < 5:


print("Count:", count)
count += 1 # Same as count = count + 1

# Output: Count: 0, Count: 1 ... Count: 4

break and continue


for i in range(10):
if i == 5:
break # Stop the loop entirely
if i % 2 == 0:
continue # Skip even numbers
print(i) # Prints 1, 3
Chapter 7: Functions
A function is a reusable block of code. You define it once and call it whenever you need it — this
keeps your code clean and avoids repetition.

Defining and Calling a Function


def greet():
print("Hello! Welcome to Python.")

greet() # Call the function


greet() # Call it again — easy!

Functions with Parameters


def greet(name):
print(f"Hello, {name}!")

greet("Alice") # Hello, Alice!


greet("Bob") # Hello, Bob!

Functions that Return a Value


def add(a, b):
return a + b

result = add(3, 7)
print(result) # 10

def square(n):
return n * n

print(square(5)) # 25

Default Parameters
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")

greet("Alice") # Hello, Alice!


greet("Bob", "Hi there") # Hi there, Bob!
Chapter 8: Lists, Tuples & Dictionaries

Lists — Ordered & Changeable


fruits = ["apple", "banana", "cherry"]

print(fruits[0]) # apple (index starts at 0)


print(fruits[-1]) # cherry (last item)

[Link]("mango") # Add to end


[Link]("banana") # Remove item
print(len(fruits)) # 3 → number of items

fruits[0] = "grape" # Change an item


print(fruits) # ["grape", "cherry", "mango"]

Tuples — Ordered & Unchangeable


# Tuples use parentheses and cannot be changed
coordinates = (10.5, 20.3)
print(coordinates[0]) # 10.5

# Great for fixed data like RGB colors, coordinates


color = (255, 128, 0)

Dictionaries — Key-Value Pairs


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

print(person["name"]) # Alice
person["email"] = "a@[Link]" # Add new key
person["age"] = 26 # Update value
del person["city"] # Delete a key

# Loop through a dictionary


for key, value in [Link]():
print(key, ":", value)
Chapter 9: String Methods
Strings have many built-in methods to help you work with text.

text = " Hello, Python World! "

print([Link]()) # Remove spaces: "Hello, Python World!"


print([Link]()) # " hello, python world! "
print([Link]()) # " HELLO, PYTHON WORLD! "
print([Link]("Python", "Amazing")) # Replace word
print([Link](",")) # [" Hello", " Python World! "]

sentence = "hello world"


print([Link]()) # Hello World
print([Link]("hello")) # True
print([Link]("world")) # True
print(len(sentence)) # 11
print("world" in sentence) # True

String Slicing
word = "Python"

print(word[0]) # P (first character)


print(word[0:3]) # Pyt (index 0,1,2)
print(word[2:]) # thon (from index 2 to end)
print(word[:4]) # Pyth (from start to index 3)
print(word[::-1]) # nohtyP (reversed!)
Chapter 10: File Handling
Python can read from and write to files on your computer — very useful for saving data.

Writing to a File
# "w" = write mode (creates file or overwrites)
with open("[Link]", "w") as file:
[Link]("Hello from Python!\n")
[Link]("This is a second line.\n")

# The file is automatically closed after the "with" block

Reading from a File


# "r" = read mode
with open("[Link]", "r") as file:
content = [Link]() # Read everything at once
print(content)

# Read line by line


with open("[Link]", "r") as file:
for line in file:
print([Link]()) # Remove newline character

Appending to a File
# "a" = append mode (adds to existing content)
with open("[Link]", "a") as file:
[Link]("Added a new line!\n")

💡 Tip: Always use the "with" statement when working with files. It automatically closes
the file even if an error occurs.
Chapter 11: Error Handling
Errors will happen. Python lets you "catch" errors so your program doesn't crash, and you can
handle them gracefully.

try / except
try:
number = int(input("Enter a number: "))
result = 10 / number
print("Result:", result)

except ValueError:
print("That's not a valid number!")

except ZeroDivisionError:
print("You can't divide by zero!")

except Exception as e:
print("Something went wrong:", e)

finally:
print("This always runs, error or not.")

Common Error Types


• ValueError — Wrong type of value (e.g., int("hello"))
• TypeError — Wrong type used in operation (e.g., 5 + "hello")
• ZeroDivisionError — Dividing by zero
• FileNotFoundError — File doesn't exist
• IndexError — List index out of range
• KeyError — Dictionary key doesn't exist
Chapter 12: Mini Projects 🚀
The best way to learn is by doing. Here are 3 beginner projects to practice everything you've
learned.

Project 1: Simple Calculator


def calculator():
print("=== Simple Calculator ===")
a = float(input("First number: "))
op = input("Operator (+, -, *, /): ")
b = float(input("Second number: "))

if op == "+": print("Result:", a + b)
elif op == "-": print("Result:", a - b)
elif op == "*": print("Result:", a * b)
elif op == "/":
if b != 0: print("Result:", a / b)
else: print("Error: Cannot divide by zero!")
else:
print("Unknown operator!")

calculator()

Project 2: Guess the Number


import random

def guess_game():
secret = [Link](1, 100)
attempts = 0

print("Guess the number between 1 and 100!")

while True:
guess = int(input("Your guess: "))
attempts += 1

if guess < secret:


print("Too low! Try higher.")
elif guess > secret:
print("Too high! Try lower.")
else:
print(f"You got it in {attempts} tries!")
break

guess_game()
Project 3: To-Do List
def todo_app():
tasks = []
print("=== To-Do List App ===")

while True:
print("\n1. Add task 2. View tasks 3. Quit")
choice = input("Choose: ")

if choice == "1":
task = input("Enter task: ")
[Link](task)
print("Task added!")
elif choice == "2":
if tasks:
for i, t in enumerate(tasks, 1):
print(f"{i}. {t}")
else:
print("No tasks yet!")
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice.")

todo_app()
What's Next? 🎯
Congratulations on finishing the Python Crash Course! Here are great next steps to keep improving:

Beginner Next Steps


• Practice daily on [Link] or HackerRank
• Learn about List Comprehensions: [x*2 for x in range(10)]
• Explore Python modules: math, random, datetime, os
• Work through 10 more small projects

Intermediate Topics to Explore


• Object-Oriented Programming (OOP) — Classes & Objects
• Regular Expressions (regex) for text patterns
• Working with APIs using the requests library
• Data analysis with pandas and numpy
• Web development with Flask or Django

Great Free Resources


• [Link]/doc — Official Python documentation
• [Link]/3/tutorial — Official beginner tutorial
• [Link] — Excellent tutorials for all levels
• [Link] — Harvard's free Python course
• [Link]/learn — Free data science with Python

💡 Tip: The best programmers write a little code every single day. Even 20 minutes of
practice builds real skills over time. Keep going!

Happy Coding! 🐍

You might also like