■
Python Basics
Complete Beginner's Reference Guide
Variables · Data Types · Operators · Strings · Control Flow · Functions · I/O
■ Beginner Friendly ■ 50+ Examples ■ Quick Reference Tables ■ Best Practices
Python Basics — Complete Reference Guide Page 1
Table of Contents
1
Introduction to Python What is Python? Why use it?
.
2
Variables & Data Types int, float, str, bool, None
.
3
Operators Arithmetic, Comparison, Logical, Assignment
.
4
Strings in Depth Methods, formatting, slicing, f-strings
.
5 User Input & Type
input(), int(), float(), str()
. Conversion
6
Conditional Statements if, elif, else
.
7
Loops for, while, break, continue, range()
.
8
Functions def, return, parameters, *args, **kwargs
.
9
Scope & Built-in Functions local/global scope, len, type, print...
.
1
0 Error Handling try, except, finally, common errors
.
1
Quick Reference Cheat
1 All key syntax at a glance
Sheet
.
Python Basics — Complete Reference Guide Page 2
SECTION
1 Introduction to Python
What is Python?
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum
in 1991. It is known for its clean, readable syntax that resembles plain English, making it the ideal first
language for beginners and a powerful tool for professionals in data science, web development, automation,
and AI.
• Easy to learn — Simple, readable syntax with minimal boilerplate.
• Versatile — Used in web, data science, AI, scripting, IoT, and more.
• Large ecosystem — 400,000+ packages on PyPI.
• Cross-platform — Runs on Windows, macOS, Linux without changes.
• Community — One of the largest programming communities worldwide.
Your First Python Program
●●● [Link]
1 # This is a comment — Python ignores lines starting with #
3 print("Hello, World!") # prints to the screen
4 print("Welcome to Python!") # each print() adds a new line
■ Output
Hello, World!
Welcome to Python!
■ Tip: In Python, indentation (spaces at the start of a line) is mandatory. Use 4 spaces per indent level —
never mix tabs and spaces.
Python Basics — Complete Reference Guide Page 3
SECTION
2 Variables & Data Types
A variable is a named container for storing data. Python is dynamically typed — you don't declare a type;
Python figures it out automatically.
Creating Variables
●●● python
1 # Variable = value (no type declaration needed!)
2 name = 'Alice' # str — text
3 age = 25 # int — whole number
4 height = 5.7 # float — decimal
5 is_student = True # bool — True or False
6 nothing = None # NoneType — absence of value
8 # Check the type
9 print(type(name)) # <class 'str'>
10 print(type(age)) # <class 'int'>
11 print(type(height)) # <class 'float'>
12 print(type(is_student)) # <class 'bool'>
Data Types At a Glance
Type Example Values
int 0, 42, -7, 1_000_000
float 3.14, -0.5, 2.0, 1.5e3
str 'hello', "world", 'Python 3'
bool True, False
NoneType None
complex 3+4j (advanced)
Multiple Assignment
●●● python
Python Basics — Complete Reference Guide Page 4
1 # Assign multiple variables at once
2 x, y, z = 10, 20, 30
3 print(x, y, z) # 10 20 30
5 # Same value to multiple variables
6 a = b = c = 0
8 # Swap without a temp variable
9 x, y = y, x
10 print(x, y) # 20 10
Naming Rules
• Names can contain letters, digits, and underscores — but cannot start with a digit.
• Case-sensitive: name, Name, and NAME are three different variables.
• Use snake_case for variables and functions: first_name, total_score.
• Avoid Python keywords: if, for, while, class, return, True, False, None…
■■ Warning: Variable names like list, str, input, print are valid but overwrite Python built-ins — avoid them.
Python Basics — Complete Reference Guide Page 5
SECTION
3 Operators
Arithmetic Operators
Operator Meaning — Example
+ Addition: 5 + 3 = 8
- Subtraction: 9 - 4 = 5
* Multiplication: 3 * 4 = 12
/ Division: 7 / 2 = 3.5 (always float)
// Floor Division: 7 // 2 = 3 (drops decimal)
% Modulo: 7 % 2 = 1 (remainder)
** Exponent: 2 ** 10 = 1024
Comparison & Logical Operators
●●● python
1 # Comparison — return True or False
2 print(5 == 5) # True — equal
3 print(5 != 3) # True — not equal
4 print(5 > 3) # True — greater than
5 print(5 < 3) # False — less than
6 print(5 >= 5) # True — greater or equal
7 print(5 <= 4) # False — less or equal
9 # Logical — combine conditions
10 print(True and False) # False — both must be True
11 print(True or False) # True — at least one True
12 print(not True) # False — inverts
Assignment Operators
●●● python
Python Basics — Complete Reference Guide Page 6
1 n = 10
2 n += 5 # n = n + 5 → 15
3 n -= 3 # n = n - 3 → 12
4 n *= 2 # n = n * 2 → 24
5 n //= 5 # n = n // 5 → 4
6 n **= 3 # n = n ** 3 → 64
7 n %= 10 # n = n % 10 → 4
Python Basics — Complete Reference Guide Page 7
SECTION
4 Strings in Depth
Creating Strings
●●● python
1 s1 = 'Single quotes'
2 s2 = "Double quotes"
3 s3 = '''Triple quotes
4 span multiple lines'''
6 # Escape characters
7 print('It\'s Python') # It's Python
8 print("Line1\nLine2") # newline
9 print("Col1\tCol2") # tab
String Indexing & Slicing
●●● python
1 s = 'Python'
2 # 0 1 2 3 4 5 (positive index)
3 # -6-5-4-3-2-1 (negative index)
5 print(s[0]) # P — first character
6 print(s[-1]) # n — last character
7 print(s[0:4]) # Pyth — index 0 to 3
8 print(s[2:]) # thon — from index 2 to end
9 print(s[:3]) # Pyt — from start to index 2
10 print(s[::-1]) # nohtyP — reversed
Essential String Methods
Method What it does
[Link]() Convert to UPPERCASE
[Link]() Convert to lowercase
[Link]() Remove whitespace from both ends
Python Basics — Complete Reference Guide Page 8
[Link](old, new) Replace substring
[Link](sep) Split into list by separator
[Link](iterable) Join list into string
[Link](sub) Find index of substring (-1 if not found)
[Link](sub) Count occurrences of substring
[Link](prefix) Returns True/False
[Link](suffix) Returns True/False
[Link]() True if all characters are digits
[Link]() True if all characters are letters
len(s) Length of the string
String Formatting (f-strings)
●●● python
1 name = 'Alice'
2 score = 94.567
4 # f-string (Python 3.6+) — recommended
5 print(f'Student: {name}')
6 print(f'Score: {score:.2f}') # 94.57 — 2 decimal places
7 print(f'Pass: {score > 90}') # Pass: True
9 # Older .format() method
10 print('Hello, {}!'.format(name))
12 # String concatenation (+ operator)
13 greeting = 'Hello, ' + name + '!'
■ Output
Student: Alice
Score: 94.57
Pass: True
Python Basics — Complete Reference Guide Page 9
SECTION
5 User Input & Type Conversion
Reading Input
The input() function reads a line of text from the user and always returns a string. You must convert it to int
or float if you need numbers.
●●● python
1 name = input('Enter your name: ') # returns str
2 age = int(input('Enter your age: ')) # convert to int
3 gpa = float(input('Enter GPA: ')) # convert to float
5 print(f'Hello {name}, age {age}, GPA {gpa:.1f}')
Type Conversion Functions
Function Converts to — Example
int(x) Integer: int('42') → 42, int(3.9) → 3
float(x) Float: float('3.14') → 3.14, float(5) → 5.0
str(x) String: str(100) → '100', str(True) → 'True'
bool(x) Boolean: bool(0) → False, bool('hi') → True
round(x,n) Round: round(3.14159, 2) → 3.14
abs(x) Absolute: abs(-7) → 7
■ Note: Truthy / Falsy values — in Python, 0, 0.0, '', [], {}, None are all considered False. Everything else is True.
Python Basics — Complete Reference Guide Page 10
SECTION
6 Conditional Statements
if / elif / else
●●● python
1 temperature = 32
3 if temperature > 35:
4 print('Very hot!')
5 elif temperature > 25:
6 print('Warm')
7 elif temperature > 15:
8 print('Mild')
9 else:
10 print('Cold')
12 # Output: Cold
Nested Conditions
●●● python
1 age = 20
2 has_id = True
4 if age >= 18:
5 if has_id:
6 print('Entry allowed')
7 else:
8 print('Need ID')
9 else:
10 print('Too young')
Ternary / One-line if
●●● python
Python Basics — Complete Reference Guide Page 11
1 # value_if_true if condition else value_if_false
2 x = 10
3 label = 'Even' if x % 2 == 0 else 'Odd'
4 print(label) # Even
6 # Practical example
7 score = 85
8 result = 'Pass' if score >= 60 else 'Fail'
Membership & Identity Operators
●●● python
1 fruits = ['apple', 'banana', 'cherry']
3 print('apple' in fruits) # True
4 print('mango' not in fruits) # True
6 a = None
7 print(a is None) # True
8 print(a is not None) # False
Python Basics — Complete Reference Guide Page 12
SECTION
7 Loops
for Loop
●●● python
1 # Iterate over a range
2 for i in range(5): # 0, 1, 2, 3, 4
3 print(i, end=' ')
5 # range(start, stop, step)
6 for i in range(1, 10, 2): # 1, 3, 5, 7, 9
7 print(i, end=' ')
9 # Iterate over a list
10 colors = ['red', 'green', 'blue']
11 for color in colors:
12 print(f'Color: {color}')
14 # enumerate — get index AND value
15 for idx, color in enumerate(colors, start=1):
16 print(f'{idx}. {color}')
while Loop
●●● python
1 count = 1
2 while count <= 5:
3 print(count)
4 count += 1 # IMPORTANT: update the variable!
6 # User-input loop
7 while True:
8 answer = input('Type quit to stop: ')
9 if answer == 'quit':
10 break
11 print(f'You typed: {answer}')
Python Basics — Complete Reference Guide Page 13
Loop Control: break / continue / pass
●●● python
1 # break — exit the loop immediately
2 for n in range(10):
3 if n == 5:
4 break
5 print(n) # prints 0 1 2 3 4
7 # continue — skip current iteration
8 for n in range(6):
9 if n % 2 == 0:
10 continue
11 print(n) # prints 1 3 5 (odd only)
13 # pass — placeholder (does nothing)
14 for n in range(3):
15 pass # no error; useful as stub
Python Basics — Complete Reference Guide Page 14
SECTION
8 Functions
Defining & Calling Functions
●●● python
1 # Define
2 def greet(name):
3 '''Docstring: describes the function.'''
4 message = f'Hello, {name}!'
5 return message
7 # Call
8 result = greet('Alice')
9 print(result) # Hello, Alice!
Parameters & Default Arguments
●●● python
1 def power(base, exp=2): # exp defaults to 2
2 return base ** exp
4 print(power(3)) # 9 (3 squared)
5 print(power(3, 3)) # 27 (3 cubed)
7 # Keyword arguments
8 def profile(name, age, city='Unknown'):
9 print(f'{name}, {age}, {city}')
11 profile('Bob', 30)
12 profile('Carol', age=25, city='NYC')
*args and **kwargs
●●● python
Python Basics — Complete Reference Guide Page 15
1 # *args — accept any number of positional arguments
2 def total(*nums):
3 return sum(nums)
5 print(total(1, 2, 3)) # 6
6 print(total(10, 20, 30, 40)) # 100
8 # **kwargs — accept any number of keyword arguments
9 def show_info(**details):
10 for key, value in [Link]():
11 print(f'{key}: {value}')
13 show_info(name='Alice', age=28, city='Boston')
Lambda Functions
●●● python
1 # lambda arguments: expression
2 square = lambda x: x ** 2
3 add = lambda a, b: a + b
4 is_even = lambda n: n % 2 == 0
6 print(square(7)) # 49
7 print(add(3, 4)) # 7
8 print(is_even(10)) # True
10 # Common use: sorting with a key
11 names = ['Charlie', 'Alice', 'Bob']
12 [Link](key=lambda x: len(x))
13 print(names) # ['Bob', 'Alice', 'Charlie']
Python Basics — Complete Reference Guide Page 16
SECTION
9 Scope & Built-in Functions
Variable Scope
●●● python
1 x = 'global' # global variable
3 def my_func():
4 x = 'local' # local — only exists inside function
5 print(x) # local
7 my_func()
8 print(x) # global — unchanged
10 # Use 'global' keyword to modify global inside function
11 count = 0
12 def increment():
13 global count
14 count += 1
16 increment(); increment()
17 print(count) # 2
Essential Built-in Functions
Function Description
print(*args) Display output to console
input(prompt) Read string from keyboard
len(x) Length of string, list, etc.
range(start,stop,step) Generate a sequence of numbers
type(x) Return the type of an object
int/float/str/bool(x) Type conversion
Python Basics — Complete Reference Guide Page 17
round(x, n) Round to n decimal places
abs(x) Absolute value
min(x) / max(x) Minimum / maximum value
sum(iterable) Sum of all elements
sorted(iterable) Return sorted list (does not modify original)
reversed(iterable) Return reversed iterator
zip(a, b) Pair up elements from two iterables
enumerate(iterable) Return (index, value) pairs
id(x) Memory address / identity of object
help(x) Show documentation for x
dir(x) List attributes and methods of x
Python Basics — Complete Reference Guide Page 18
SECTION
10 Error Handling
Common Error Types
Error Cause
SyntaxError Invalid Python syntax — missing colon, bracket, etc.
NameError Using a variable that hasn't been defined
TypeError Wrong data type — e.g. adding str + int
ValueError Right type, wrong value — e.g. int('abc')
ZeroDivisionError Dividing by zero
IndexError List index out of range
KeyError Dictionary key not found
FileNotFoundError Trying to open a file that doesn't exist
AttributeError Method/attribute doesn't exist on the object
try / except / finally
●●● python
Python Basics — Complete Reference Guide Page 19
1 try:
2 num = int(input('Enter a number: '))
3 result = 100 / num
4 print(f'Result: {result}')
6 except ValueError:
7 print('Please enter a valid integer!')
9 except ZeroDivisionError:
10 print('Cannot divide by zero!')
12 except Exception as e:
13 print(f'Unexpected error: {e}')
15 finally:
16 print('This always runs — cleanup here.')
Raising Exceptions
●●● python
1 def check_age(age):
2 if age < 0:
3 raise ValueError('Age cannot be negative!')
4 if age > 150:
5 raise ValueError('Age seems unrealistic!')
6 return f'Valid age: {age}'
8 try:
9 print(check_age(-5))
10 except ValueError as e:
11 print(f'Error: {e}') # Error: Age cannot be negative!
Python Basics — Complete Reference Guide Page 20
SECTION
11 Quick Reference Cheat Sheet
Complete Python Basics Syntax Reference
Category Syntax / Example
Variable x = 42 | name = 'Alice' | pi = 3.14
Print print('text', x, sep=', ', end='\n')
Input x = input('prompt') → always returns str
Type check type(x) isinstance(x, int)
Arithmetic + - * / // % **
Comparison == != < > <= >=
Logical and or not
Assignment += -= *= /= //= %= **=
if/elif/else if cond:\n ...\nelif cond2:\n ...\nelse:\n ...
for loop for i in range(n): | for x in iterable:
while loop while condition: (update var inside!)
break/continue break — exit loop | continue — skip iteration
function def name(params, default=val): return x
lambda f = lambda x, y: x + y
try/except try:\n risky()\nexcept ErrorType as e:\n handle()
String slice s[start:stop:step] | s[::-1] (reverse)
f-string f'Hello {name}, score={score:.2f}'
String methods .upper() .lower() .strip() .split() .replace()
Type convert int() float() str() bool() round()
Membership 'x' in s | 'x' not in s
Python Basics — Complete Reference Guide Page 21
Identity x is None | x is not None
■ Next Steps: Learn about Lists, Tuples, Dictionaries, Sets, File I/O, OOP, and then dive into Python for Data
Science with NumPy and Pandas!
Python Basics — Complete Reference Guide Page 22