Python: From Basics to Building Blocks
This document provides a detailed exploration of the foundational concepts in the
Python programming language. We will cover the essential syntax, data structures,
and conventions that every Python programmer must understand.
1. Syntax and Basic Concepts
The syntax of a programming language is the set of rules that defines the
combinations of symbols that are considered to be correctly structured programs.
Python was designed to be a highly readable language, with a clean and simple
syntax.
a. Keywords and Identifiers
Keywords
Keywords are the reserved words in Python. They are used to define the syntax and
structure of the Python language. You cannot use a keyword as a variable name,
function name, or any other identifier. They are case-sensitive.
Here is a list of all keywords in Python 3.9:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Identifiers
An identifier is the name given to entities like variables, functions, classes, etc. It helps
to differentiate one entity from another.
Rules for writing identifiers:
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z), digits (0 to 9), or an underscore _.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly
fine.
3. Keywords cannot be used as identifiers.
4. Special symbols like !, @, #, $, % etc., cannot be used in an identifier.
5. An identifier can be of any length.
Valid Identifiers Invalid Identifiers Reason for Invalidity
my_variable my-variable Contains a hyphen
variable123 123variable Starts with a digit
_private_var class Is a reserved keyword
userName user Name Contains a space
b. Statements and Expressions
Statements
A statement is an instruction that the Python interpreter can execute. It is a complete
line of code that performs some action. For example, assignment statements, if
statements, for statements, while statements, etc., are all statements.
# Assignment statement
x = 10
# A for loop is a compound statement
for i in range(5):
print(i) # This print function call is also a statement
# An if-elif-else statement
if x > 5:
print("x is greater than 5") # statement
elif x == 5:
print("x is 5") # statement
else:
print("x is less than 5") # statement
Expressions
An expression is a combination of values, variables, operators, and calls to functions
that needs to be evaluated to produce a new value. Essentially, if you can print it or
assign it to a variable, it's an expression.
# Expressions
5+3 # Evaluates to 8
x-2 # Evaluates to 8 (using x from above)
2 * (3 + 4) # Evaluates to 14
'Hello' + ', ' + 'World!' # Evaluates to 'Hello, World!'
x>5 # Evaluates to the boolean value True
Key Difference: The primary distinction is that statements do something (they
perform an action), while expressions are evaluated to a value.
c. Indentation and Code Blocks
Unlike many other languages that use curly braces {} to define blocks of code, Python
uses indentation. A code block (the body of a function, loop, etc.) starts with
indentation and ends with the first unindented line.
The standard is to use four spaces for each level of indentation.
A colon : signifies the start of an indented block.
Correct Indentation Example:
def my_function():
name = "Alice"
if name == "Alice":
print("Hello, Alice!") # This is inside the 'if' block
for i in range(3):
print(i) # This is inside the 'for' block
print("Welcome!") # This is inside the function block but outside the 'if' block
my_function()
Incorrect Indentation (will cause an IndentationError):
def my_function():
name = "Alice" # Error: expected an indented block
if name == "Alice":
print("Hello, Alice!") # Error: unexpected indent
print("Welcome!") # Error: unindent does not match any outer indentation level
d. Comments and Docstrings
Comments
Comments are used to explain the code. They are ignored by the Python interpreter.
They are for making the code more readable to humans.
● Single-line comments: Start with a hash symbol #. Everything after the # on that
line is a comment.
● Multi-line comments: Python doesn't have a specific syntax for multi-line
comments. The convention is to use consecutive single-line comments.
# This is a single-line comment.
x = 10 # This is an inline comment explaining the purpose of the variable.
# This is a multi-line comment.
# It explains the purpose of the function below.
def add(a, b):
return a + b
Docstrings
A docstring (documentation string) is a special kind of string literal that occurs as the
first statement in a module, function, class, or method definition. It is used to
document what the code does. Docstrings are enclosed in triple quotes (""" or ''').
Unlike comments, docstrings are not ignored by the interpreter. They are stored as an
attribute (__doc__) of the object and can be accessed at runtime.
def power(base, exp):
"""
Calculates the power of a number.
Args:
base (int or float): The base number.
exp (int or float): The exponent.
Returns:
int or float: The result of base raised to the power of exp.
"""
return base ** exp
# Accessing the docstring
print(power.__doc__)
2. Variables and Data Types
A variable is a container for storing a value. In Python, you don't need to declare the
type of a variable. The type is inferred at runtime based on the value assigned to it.
Data Type Description Example
Integers (int) Whole numbers, positive or x = 10, y = -300
negative, without decimals.
Floats (float) Numbers with a decimal point. pi = 3.14, e = 2.718e2 (271.8)
Can also represent scientific
notation.
Strings (str) A sequence of characters, name = "John Doe", message
enclosed in single ('), double = 'Hello'
("), or triple (""" or ''') quotes.
Booleans (bool) Represents one of two values: is_active = True, has_error =
True or False. Often the result False
of comparisons.
Example Usage:
# Integer
age = 25
print(f"Age: {age}, Type: {type(age)}")
# Float
price = 19.99
print(f"Price: {price}, Type: {type(price)}")
# String
full_name = "Jane Smith"
print(f"Name: {full_name}, Type: {type(full_name)}")
# Boolean
is_student = True
print(f"Is Student: {is_student}, Type: {type(is_student)}")
3. Type Casting
Type casting (or type conversion) is the process of converting a variable from one
data type to another. Python has several built-in functions for this purpose.
Function Description Example Result
int() Converts a int(3.9) 3
compatible value into int("123") 123
an integer. For floats,
it truncates (cuts off)
the decimal. For
strings, the string
must represent a
whole number.
float() Converts a value into float(10) 10.0
a floating-point float("3.14") 3.14
number.
str() Converts a value into str(123) "123"<br"True"
a string. str(True)
bool() Converts a value into bool(0) False
a boolean. 0, 0.0, "" bool(100) True
(empty string), None, bool("") False
and empty bool("Hi") True
collections become
False. Everything else
is True.
Example Scenario:
Imagine you get user input, which is always a string, but you need to perform a
calculation.
# User input is always a string
age_str = input("Enter your age: ") # e.g., user enters "30"
# We must cast it to an integer to do math
age_int = int(age_str)
# Now we can perform calculations
age_in_a_decade = age_int + 10
print("In a decade, you will be " + str(age_in_a_decade) + " years old.")
4. Literals
A literal is a notation for representing a fixed value in source code. It's the raw data
assigned to variables or used in expressions.
Literal Type Description Examples
String Literals A sequence of characters in 'Hello', "Python", """Multi-line
quotes. string"""
Numeric Literals Represent numbers. 100 (int), 3.14 (float), 3+4j
(complex)
Boolean Literals The two constant values True True, False
and False.
Special Literal The Python None literal, None
representing the absence of a
value.
Collection Literals Notations for creating [1, 2, 3] (list), (1, 2, 3) (tuple),
collections. {"a": 1, "b": 2} (dictionary),
{"x", "y", "z"} (set)
# Assigning literals to variables
name = "Alex" # String literal
age = 42 # Numeric literal (int)
is_tall = False # Boolean literal
wallet = None # Special literal
print(name, age, is_tall, wallet)