Docs
python basics
01 - Python Basics
📌 What You'll Learn
- •Python syntax and structure
- •Keywords and identifiers
- •Variables and data types
- •Input and output
- •Operators
- •Comments and indentation
- •Type casting
- •Math functions
🔤 Python Syntax
Python is known for its clean and readable syntax. Unlike other languages, Python uses indentation (whitespace) to define code blocks instead of curly braces {}.
Key Points:
- •Python files have
.pyextension - •Python is case-sensitive (
Name≠name) - •Statements end with a newline (no semicolon needed)
- •Use 4 spaces for indentation (standard)
# This is a valid Python program
print("Hello, World!")
# Indentation matters!
if True:
print("This is indented") # 4 spaces
🔑 Keywords and Identifiers
Keywords
Reserved words that have special meaning in Python. You cannot use them as variable names.
# Python 3.10+ has 35 keywords:
False, None, True, and, as, assert, async, await,
break, class, continue, def, del, elif, else, except,
finally, for, from, global, if, import, in, is,
lambda, nonlocal, not, or, pass, raise, return,
try, while, with, yield
Identifiers
Names given to variables, functions, classes, etc.
Rules:
- •Can contain letters (a-z, A-Z), digits (0-9), and underscore (_)
- •Cannot start with a digit
- •Cannot be a keyword
- •Case-sensitive
# Valid identifiers
my_variable = 10
_private = 20
userName123 = "John"
MyClass = "class"
# Invalid identifiers
# 123abc = 10 ❌ Starts with digit
# my-var = 10 ❌ Contains hyphen
# class = 10 ❌ Is a keyword
📦 Variables and Data Types
Variables
Variables are containers for storing data values. Python has no command for declaring variables - they are created when you assign a value.
# Variable assignment
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 100 # Same value to multiple variables
Data Types
| Type | Description | Example |
|---|---|---|
int | Integer numbers | 42, -10, 0 |
float | Decimal numbers | 3.14, -0.5 |
str | Text/String | "Hello", 'World' |
bool | Boolean | True, False |
None | Null/No value | None |
list | Ordered, mutable collection | [1, 2, 3] |
tuple | Ordered, immutable collection | (1, 2, 3) |
dict | Key-value pairs | {"name": "John"} |
set | Unordered, unique items | {1, 2, 3} |
# Check type with type()
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
🖥️ Input and Output
Output with print()
# Basic print
print("Hello, World!")
# Print multiple values
print("Name:", "Alice", "Age:", 25)
# Print with separator
print("a", "b", "c", sep="-") # a-b-c
# Print without newline
print("Hello", end=" ")
print("World") # Hello World
# Print with formatting
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}") # f-string (recommended)
Input with input()
# Get user input (always returns string)
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Convert input to number
age = int(input("Enter your age: "))
height = float(input("Enter your height: "))
➕ Operators
Arithmetic Operators
a, b = 10, 3
print(a + b) # 13 Addition
print(a - b) # 7 Subtraction
print(a * b) # 30 Multiplication
print(a / b) # 3.333... Division (float)
print(a // b) # 3 Floor division (integer)
print(a % b) # 1 Modulus (remainder)
print(a ** b) # 1000 Exponentiation (power)
Comparison Operators
a, b = 10, 5
print(a == b) # False Equal
print(a != b) # True Not equal
print(a > b) # True Greater than
print(a < b) # False Less than
print(a >= b) # True Greater or equal
print(a <= b) # False Less or equal
Logical Operators
x, y = True, False
print(x and y) # False Both must be True
print(x or y) # True At least one True
print(not x) # False Inverts the value
Assignment Operators
x = 10 # Assign
x += 5 # x = x + 5 → 15
x -= 3 # x = x - 3 → 12
x *= 2 # x = x * 2 → 24
x /= 4 # x = x / 4 → 6.0
x //= 2 # x = x // 2 → 3.0
x %= 2 # x = x % 2 → 1.0
x **= 3 # x = x ** 3 → 1.0
Bitwise Operators
a, b = 5, 3 # Binary: a=0101, b=0011
print(a & b) # 1 AND (0001)
print(a | b) # 7 OR (0111)
print(a ^ b) # 6 XOR (0110)
print(~a) # -6 NOT (inverts all bits)
print(a << 1) # 10 Left shift (1010)
print(a >> 1) # 2 Right shift (0010)
Identity Operators
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is c) # True Same object in memory
print(a is b) # False Different objects
print(a is not b) # True
print(a == b) # True Same values (equality)
Membership Operators
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("mango" in fruits) # False
print("mango" not in fruits) # True
💬 Comments and Indentation
Comments
# This is a single-line comment
# Multi-line comments using multiple #
# Line 1
# Line 2
"""
This is a multi-line string (docstring)
Often used as multi-line comments
But technically it's a string literal
"""
'''
Single quotes work too
for multi-line strings
'''
Indentation
# Python uses indentation to define code blocks
# Standard: 4 spaces (not tabs)
if True:
print("Indented block") # 4 spaces
if True:
print("Nested block") # 8 spaces
# IndentationError if incorrect:
# if True:
# print("Error!") # Not indented - ERROR!
🔄 Type Casting
Converting one data type to another.
# String to Integer
age_str = "25"
age_int = int(age_str) # 25
# String to Float
price_str = "19.99"
price_float = float(price_str) # 19.99
# Number to String
num = 42
num_str = str(num) # "42"
# Float to Integer (truncates decimal)
pi = 3.14159
pi_int = int(pi) # 3
# Integer to Float
x = 10
x_float = float(x) # 10.0
# To Boolean
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False (empty string)
print(bool("Hi")) # True (non-empty string)
print(bool([])) # False (empty list)
print(bool([1])) # True (non-empty list)
🔢 Math Functions
Built-in Math Functions
# Basic functions
print(abs(-10)) # 10 Absolute value
print(round(3.7)) # 4 Round to nearest integer
print(round(3.14159, 2)) # 3.14 Round to 2 decimals
print(pow(2, 3)) # 8 Power (2^3)
print(min(1, 5, 3)) # 1 Minimum
print(max(1, 5, 3)) # 5 Maximum
print(sum([1, 2, 3]))# 6 Sum of iterable
print(divmod(10, 3)) # (3, 1) Quotient and remainder
Math Module
import math
# Constants
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
# Functions
print(math.sqrt(16)) # 4.0 Square root
print(math.ceil(3.2)) # 4 Ceiling (round up)
print(math.floor(3.8)) # 3 Floor (round down)
print(math.factorial(5)) # 120 5!
print(math.gcd(12, 8)) # 4 Greatest common divisor
print(math.log(10)) # 2.302... Natural log
print(math.log10(100)) # 2.0 Log base 10
print(math.sin(math.pi/2)) # 1.0 Sine
print(math.cos(0)) # 1.0 Cosine
print(math.degrees(math.pi)) # 180.0 Radians to degrees
print(math.radians(180)) # 3.14159... Degrees to radians
📝 Summary
- •Python uses clean syntax with indentation
- •Variables don't need type declarations
- •Python has various data types: int, float, str, bool, list, tuple, dict, set
- •Use
input()for user input,print()for output - •Multiple types of operators: arithmetic, comparison, logical, bitwise
- •Type casting converts between data types
- •Math module provides advanced mathematical functions
🎯 Next Steps
After mastering these basics, proceed to 02_strings to learn about string manipulation!