Who this guide is for
- Beginners who already installed Python and created a virtual environment
- Learners who want a strong foundation before touching advanced topics
- Developers from other languages who need Python syntax and idioms quickly
What you’ll learn
- Core Python syntax rules, especially indentation and readable structure
- Variables, data types, operators, and type conversion in daily use
- Input/output, conditionals, loops, functions, and built-in functions
- Essential collections: lists, tuples, sets, and dictionaries
- Basic exception handling patterns for safer programs
Why this topic matters
Most Python frustrations come from weak fundamentals, not complex algorithms. If your basics are solid, advanced topics become much easier because you already understand how data flows, how control structures work, and how to debug simple issues.
This guide is your practical foundation. You will build the mental model needed for every next step in this series: object-oriented programming, testing, packaging, and production-ready code.
Core concepts
Syntax, indentation, and data basics
Python uses indentation to define code blocks. There are no curly braces, so consistent spacing is required.
Use 4 spaces per indentation level. Keep names descriptive.
user_name = "Ava"
age = 21
is_active = True
height = 1.68
middle_name = None
if is_active:
print(f"{user_name} is active.")
print(f"Height: {height} m")
print(f"Middle name set? {middle_name is not None}")
Common basic data types:
intfor whole numbersfloatfor decimal numbersstrfor textboolforTrue/FalseNonefor “no value”
String formatting and methods examples:
language = "python"
version = 3.12
print(f"Learning {language.title()} {version:.1f}") # f-string formatting
print(language.upper())
print(language.replace("py", "my"))
Control flow: conditionals and loops
Control flow decides what your code does and when it does it.
score = 78
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
print(grade)
Logical operators example:
has_ticket = True
has_id = False
print(has_ticket and has_id) # logical AND
print(has_ticket or has_id) # logical OR
print(not has_id) # logical NOT
Operator coverage snapshot:
a = 10
b = 3
print(a + b) # arithmetic
print(a > b) # comparison
a += 2 # assignment
print(a)
print(a is b) # identity
print(2 in [1, 2, 3]) # membership
print("py" in "python") # membership
Loops let you repeat operations:
for number in range(1, 4):
print(number)
while + continue example:
counter = 0
while counter < 5:
counter += 1
if counter == 3:
continue
print(counter)
You will also use loop controls like break and continue as your logic grows.
Ternary operator example:
status = "adult" if age >= 18 else "minor"
print(status)
Loop else example:
for value in [1, 2, 3]:
if value == 10:
break
else:
print("Value 10 was not found")
Functions, collections, and error handling
Functions organize reusable logic. Collections store related values.
def average(numbers):
return sum(numbers) / len(numbers)
values = [10, 20, 30]
print(average(values))
Essential collections in practice:
list: ordered and mutabletuple: ordered and immutableset: unique values onlydict: key-value pairs
Tuple example:
point = (10, 20)
print(point[0], point[1])
Dictionary comprehension example:
squared = {n: n * n for n in range(1, 4)}
print(squared)
Basic exception handling prevents crashes from expected bad input:
try:
value = int("not-a-number")
except ValueError:
print("Please provide a valid integer.")
try/except/else/finally + custom exception example:
class NegativeNumberError(Exception):
pass
def parse_positive(text):
try:
number = int(text)
if number < 0:
raise NegativeNumberError("Number must be >= 0")
except ValueError:
print("Input must be an integer")
return None
except NegativeNumberError as error:
print(error)
return None
else:
print("Valid positive number")
return number
finally:
print("Validation finished")
Step-by-step walkthrough
Step 1 — Build a tiny script with variables, input, and output
Create basics_demo.py:
name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"Hello, {name}!")
print(f"Next year, you will be {age + 1}.")
print(type(age))
print(isinstance(age, int))
This gives you hands-on practice with input(), type conversion, and formatted output.
Step 2 — Add conditions and loops
Extend your script with a condition and a loop:
if age >= 18:
print("You are an adult.")
else:
print("You are under 18.")
for i in range(3):
print(f"Loop run #{i + 1}")
Now you control program decisions and repeated actions.
Step 3 — Wrap logic in functions and handle errors
Refactor parts of your script into functions and protect risky conversions:
def to_int(text):
try:
return int(text)
except ValueError:
return None
raw = input("Enter a number: ")
number = to_int(raw)
if number is None:
print("Invalid number.")
else:
print(f"Double value: {number * 2}")
This is the first step toward maintainable and robust code.
Function parameter flexibility with args and *kwargs:
def summarize(*args, **kwargs):
print("args:", args)
print("kwargs:", kwargs)
summarize(1, 2, 3, user="ava", active=True)
Default argument example:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ava"))
print(greet("Ava", "Welcome"))
Practical examples
Example 1 — Expense tracker with list and dictionary
You can combine loops, dictionaries, and arithmetic to solve a real task.
expenses = {
"food": 120,
"transport": 45,
"internet": 30,
}
total = sum(expenses.values())
for category, amount in expenses.items():
print(f"{category}: ${amount}")
print(f"Total: ${total}")
Expected output:
food: $120
transport: $45
internet: $30
Total: $195
Example 2 — Count unique words with sets
Sets are useful when you need unique values only.
sentence = "python is simple and python is powerful"
words = sentence.split()
unique_words = set(words)
print(f"Total words: {len(words)}")
print(f"Unique words: {len(unique_words)}")
print(sorted(unique_words))
Expected output:
Total words: 7
Unique words: 5
['and', 'is', 'powerful', 'python', 'simple']
Common mistakes and how to avoid them
- Inconsistent indentation -> Use 4 spaces and configure your editor to insert spaces, not mixed tabs/spaces.
- Forgetting type conversion for user input -> Convert with
int()orfloat()and guard withtry/except. - Overusing global variables -> Pass data into functions and return results explicitly.
- Choosing wrong data structure -> Use
dictfor labeled data,setfor uniqueness,listfor ordered mutable data. - Ignoring exceptions -> Handle expected errors close to the source of input or external data.
- Skipping debugging tools -> Start with
print()debugging, then usepdbfor step-by-step inspection.
Quick pdb intro:
import pdb
value = 10
pdb.set_trace()
print(value * 2)
Quick practice
- Write a program that asks for 5 numbers, stores them in a list, then prints min, max, and average.
- Create a dictionary for a student’s profile (
name,age,major) and print it in a formatted sentence. - Build a safe division function that returns a friendly message when dividing by zero.
Key takeaways
- Python basics are the foundation for every advanced topic in this series.
- Readable syntax plus correct control flow makes programs easier to debug and maintain.
- Functions and collections are your daily tools for structuring logic and data.
- Basic exception handling turns fragile scripts into reliable programs.
Next step
Continue to Advanced Python Features. In the next guide, you will explore scope rules, modules, comprehensions, decorators, generators, context managers, and other powerful language features.
No Comments