Complete Beginner's Guide to Python — Pages 1–30
(Detailed, with Examples & Solutions)
This PDF consolidates pages 1–30 into one detailed, beginner-friendly guide. It includes clear
explanations, step-by-step examples, and ready-to-run code solutions for the exercises found on pages
1–30.
Contents
1. 1. Programming Languages & Python overview
2. 2. Built-in functions, print(), input()
3. 3. Data types: immutable vs mutable
4. 4. Variables & naming rules
5. 5. Type checking and typecasting (int, float, str, bool)
6. 6. Operators: arithmetic, comparison, logical — with PEDMAS
7. 7. Conditional statements: if, elif, else
8. 8. Loops: for, while, range(), in operator
9. 9. Jump statements: break, continue, infinite loops
10. 10. Mini-projects & solved exercises (calculator, Fibonacci, factorial, prime, FizzBuzz, etc.)
11. 11. How to run Python code and next steps
1. Programming Languages & Python overview
Computers only understand machine code (0s and 1s). Programming languages allow humans to write
instructions in a readable form which are then translated to machine operations. Languages close to
machine are called low-level (hard to read), while high-level languages like Python are easy for humans.
Why Python?
Python is beginner-friendly because its syntax is simple and readable. It has many built-in features, works
across platforms, and is widely used for scripting, web apps, data analysis, and more.
Example (very first program)
print('Hello, Python!')
# Output: Hello, Python!
2. Built-in functions, print(), input()
A function is a named block of code that performs a task. Python has many built-in functions. Two you'll
use immediately are print() to show output and input() to get text from the user.
print()
Use print() to display values or text. Multiple items separated by commas will be printed with spaces by
default.
print('Hello', 'world')
# Output: Hello world
input()
input(prompt) shows a prompt and returns what the user types as a string.
name = input('Enter your name: ')
print('Hello', name)
# If user types 'Ana' -> Output: Hello Ana
3. Data types: immutable vs mutable
Every value in Python has a type. Two major categories: immutable (cannot change in-place) and mutable
(can change). Common types:
Immutable: int, float, str, tuple Mutable: list, dict, set
Examples
x = 10 # int (immutable)
y = 'hello' # str (immutable)
arr = [1,2,3] # list (mutable)
arr.append(4)
print(arr) # Output: [1, 2, 3, 4]
4. Variables & naming rules
A variable is a name pointing to a value in memory. You create variables by assignment: name = value.
Rules:
• Use letters (a-z), digits (0-9) and underscore (_).
• A variable must start with a letter or underscore (_).
• No spaces are allowed; use snake_case or camelCase.
• Variable names are case-sensitive: num, Num and NUM are different.
Examples
score = 90
first_name = 'Riya'
_num = 5
print(first_name, score)
# Output: Riya 90
5. Type checking and typecasting (int, float, str, bool)
Use type() to inspect the type of any object. Typecasting (type conversion) functions change one type to
another:
Common typecasts: int(), float(), str(), bool()
print(type(5)) # <class 'int'>
print(type('hi')) # <class 'str'>
print(int('8')) # 8 (integer)
print(float('10.2')) # 10.2 (float)
print(str(25)) # '25' (string)
print(bool(0)) # False
print(bool('')) # False
print(bool('text')) # True
Note: int('hello') will raise ValueError because 'hello' is not a number.
6. Operators: arithmetic, comparison, logical — with PEDMAS
Arithmetic operators:
+ Addition 4 + 2 = 6
- Subtraction 7 - 5 = 2
* Multiplication 5 * 2 = 10
/ Division 7 / 2 = 3.5
% Modulus 5 % 2 = 1
** Exponent 3 ** 2 = 9
// Floor division 7 // 2 = 3
PEDMAS (Order of operations):
Parentheses, Exponent, Division, Multiplication, Addition, Subtraction. Always apply in this order.
Example:
result = 9 + 7 * (8 - 4) / 2 - 3 ** 2
# Stepwise -> final: 14
print(result)
Comparison operators (return True/False): ==, !=, >, <, >=, <=
print(5 == 5) # True
print(4 != 5) # True
print(2 > 3) # False
Logical operators: and, or, not (combine conditions)
print(3 < 7 and 8 == 8) # True (both true)
print(4 > 5 or 9 == 9) # True (one true)
print(not (3 > 2)) # False (reverse)
7. Conditional statements: if, elif, else
Use if to run code only when a condition is True. Use elif to check more conditions. Use else for the final
fallback.
age = int(input('Age: '))
if age >= 18:
print('Eligible to vote')
elif age >= 13:
print('Teenager')
else:
print('Child')
Indentation is critical in Python. Indent using 4 spaces (or a consistent tab) to mark blocks.
8. Loops: for, while, range(), in operator
The for loop iterates over a sequence (list, string, range).
for i in range(5):
print(i)
# Output: 0 1 2 3 4
Using 'in' with strings:
word = 'python'
for ch in word:
print(ch)
# prints each character
The while loop repeats as long as a condition is True:
i = 1
while i < 6:
print(i)
i += 1
# prints 1 to 5
9. Jump statements: break, continue, infinite loops
break exits the nearest enclosing loop immediately.
for ch in 'apple':
if ch in 'aeiou':
print('Vowel found!')
break
# stops at first vowel
continue skips the rest of the loop body and moves to next iteration.
for num in range(1,11):
if num == 4 or num == 6:
continue
print(num)
# prints 1 2 3 5 7 8 9 10
Infinite loop happens if condition never becomes False:
while True:
print('This is infinite')
break # remove break and it's infinite
10. Mini-projects & solved exercises (with code and outputs)
Below are several exercises from pages 1–30 with full solutions and explanations. You can copy and run
these in any Python 3 interpreter.
Solution 1 — Simple Calculator (if-elif)
num1 = float(input('Enter first number: '))
op = input('Enter operator (+, -, *, /): ')
num2 = float(input('Enter second number: '))
if op == '+':
result = num1 + num2
elif op == '-':
result = num1 - num2
elif op == '*':
result = num1 * num2
elif op == '/':
if num2 == 0:
result = 'Error: Division by zero'
else:
result = num1 / num2
else:
result = 'Invalid operator'
print('Result:', result)
Explanation: We convert inputs to float for decimal support, then check operator and compute.
Division-by-zero is handled.
Solution 2 — First 10 Fibonacci numbers
a, b = 0, 1
fib = []
for _ in range(10):
fib.append(a)
a, b = b, a + b
print(fib)
# Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Solution 3 — Sum of digits of a number
n = input('Enter a number: ')
total = 0
for ch in n:
if ch.isdigit():
total += int(ch)
print('Sum of digits:', total)
# Example: '4453' -> 16
Solution 4 — Multiplication table (ask for number and terms)
num = int(input('Enter number: '))
terms = int(input('How many terms? '))
for i in range(1, terms+1):
print(num, 'x', i, '=', num * i)
Solution 5 — Check if a number is prime
n = int(input('Enter number: '))
if n <= 1:
print(n, 'is not prime')
else:
is_prime = True
i = 2
while i * i <= n:
if n % i == 0:
is_prime = False
break
i += 1
print(n, 'is prime' if is_prime else 'is not prime')
Solution 6 — Factorial using loop
n = int(input('Enter a positive integer: '))
fact = 1
for i in range(1, n+1):
fact *= i
print('Factorial of', n, 'is', fact)
Solution 7 — Word guessing game (simple version)
secret = 'python'
guessed = ['_'] * len(secret)
attempts = 6
while attempts > 0 and '_' in guessed:
print('Current:', ' '.join(guessed))
ch = input('Guess a letter: ')
if ch in secret:
for i, c in enumerate(secret):
if c == ch:
guessed[i] = ch
else:
attempts -= 1
print('Wrong! Attempts left:', attempts)
if '_' not in guessed:
print('You won! The word is', secret)
else:
print('Game over. The word was', secret)
Solution 8 — FizzBuzz (1 to 100)
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
Solution 9 — Fahrenheit to Celsius
f = float(input('Enter Fahrenheit: '))
c = (f - 32) * 5 / 9
print('Celsius:', c)
Solution 10 — Stationery total
pen = 25
pencil = 8
notebook = 45
colours = 88
total = pen + pencil + notebook + colours
print('Total:', total) # 166
Common beginner errors & tips
IndentationError: Make sure your blocks are indented consistently (4 spaces).
TypeError: Occurs when you try to use an operation with incompatible types (e.g., '2' + 3). Use int()/str()
to convert.
ValueError: Occurs when conversion fails (int('abc') raises ValueError).
ZeroDivisionError: Division by zero; always check divisor before dividing.
Quick tips:
• Use print() to debug values inside loops or conditions.
• Start simple: write small programs and test frequently.
• Use meaningful variable names.
• When stuck, try dividing the problem into smaller steps.
11. How to run Python code and next steps
To run Python: install Python 3 from python.org or use an online REPL (e.g., repl.it, Trinket, or Google
Colab). Save code in a file, e.g., program.py, and run: python program.py
Next suggested practice:
• Practice the examples above by modifying inputs and observing outputs.
• Try adding input validation (what if user types letters instead of numbers?).
• Learn functions (def) and start organizing repeated code into functions.
• Explore lists, dictionaries, and simple file I/O.