When learning to code in Python, understanding its syntax is the first step.
In programming, syntax refers to the rules that define the correct structure of code. Like grammar in human languages, programming syntax tells the computer how to interpret our writing.
Python is known for having a clear, readable syntax, which makes it a top choice for beginners. Unlike many other programming languages, Python doesn’t use curly braces { } or semicolons ; to define blocks of code. Instead, it uses indentation, making the code look clean and easy to follow. So, let us start by understanding what indentation is.
Unlike many other programming languages, Python has no explicit command for declaring a variable. A variable is created the moment you first assign a value to it.
Variables can have short names (like x and y) or more descriptive names that make your code easier to read (age, car_name, total_volume).
To keep your code valid, you must follow these essential rules:
Starting character: A variable name must start with a letter or the underscore (_) character.
No leading numbers: A variable name cannot start with a number.
Allowed characters: It can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
Case Sensitivity: Variable names are case-sensitive. For example, age, Age, and AGE are three completely different variables.
Take a look at the code block below. Can you guess what it will print to the console?
a = 'Hi There'
b = 2.22
c = 0xFF
print(a)
print(b)
print(c)
The Result:
a prints out: Hi There (a standard string)
b prints out: 2.22 (a floating-point decimal)
c prints out: 255 (Python automatically converts the hexadecimal value 0xFF to its base-10 decimal equivalent!)
Because Python dynamically handles data types, you might sometimes wonder, "What kind of data is this variable actually holding?"
We can easily find out using the built-in type() function.
a = 'Hi There'
b = 2.22
c = 0xFF
print(type(a)) # Output: <class 'str'>
print(type(b)) # Output: <class 'float'>
print(type(c)) # Output: <class 'int'>
A block is a group of statements in a program or script. Usually it consists of at least one statement and of declarations for the block, depending on the programming or scripting language. A language which allows grouping with blocks, is called a block structured language.
Python programs get structured through indentation, i.e. code blocks are defined by their indentation.
This principle makes it easier to read and understand other people's Python code.
All statements with the same distance to the right belong to the same block of code, i.e. the statements within a block line up vertically. The block ends at a line less indented or the end of the file. If a block has to be more deeply nested, it is simply indented further to the right.
Numeric literals are immutable (unchangeable) and come in three primary types:
Integers (int): Whole numbers without a fractional part. They can be positive, negative, or zero. Python also supports binary, octal, and hexadecimal integers.
Floating-Point (float): Numbers that contain a decimal point or use exponential notation (e or E).
Octal: An octal literal represents a number in the base-8 number system (which uses digits from 0 to 7).
Complex (complex): Numbers represented in the form x + yj, where x is the real part and y is the imaginary part.
# Integer literals
a = 42 # Decimal
b = 0b101010 # Binary (starts with 0b)
c = 0x2A # Hexadecimal (starts with 0x)
d = 0o10 # Octal (starts with 0o)
e = 0o755 # Common Unix file permission (equal to decimal 493)
# Float literals
pi = 3.14159
distance = 1.5e4 # 1.5 * 10^4 or 15000.0
# Complex literal
num = 3 + 5j
Note:
Starting in Python 3.6, you can use underscores (_) in numeric literals to make them easier to read. For example, writing 1_000_000 is exactly the same to Python as writing 1000000.
A string literal is a sequence of characters surrounded by quotes. Python treats single quotes (') and double quotes (") exactly the same.
Single/Double quotes: Used for single-line strings.
Triple quotes (''' or """): Used for multi-line strings or docstrings.
Character literal: Python does not have a distinct "character" type; a single character is just a string of length 1.
single_line = "Hello, World!"
multi_line = """This is a string
that spans across
multiple lines."""
# Escape sequences are also part of string literals
escaped_str = "Hello\nWorld" # \n inserts a newline
Boolean literals represent truth values. There are only two boolean literals in Python, and they are case-sensitive:
True (internally represents the value 1)
False (internally represents the value 0)
is_python_fun = True
is_earth_flat = False
Python has one special literal used to signify the absence of a value or a null value: None. It is often used to initialize variables that will be assigned values later, or to represent the return value of a function that doesn't explicitly return anything.
current_user = None # No user is logged in yet
Python also allows you to define literal structures for its built-in collection data types:
Comments in Python are code lines that the Python interpreter ignores during execution. They are crucial for explaining what your code does, making it easier for you and others to read and maintain.
The most common way to write a comment is by using the hash symbol (#). Anything written after the # on that line is treated as a comment.
# This is a standalone single-line comment
print("Hello, World!") # This is an inline comment
Python doesn't have a specific, built-in syntax for multi-line comments (like /* ... */ in C++ or Java). However, you have two standard ways to achieve this:
The PEP(Python Enhancement Proposals) 8 style guide recommends using consecutive # tags for multi-line explanations.
# This is a multi-line comment.
# Each line starts with a hash mark.
# It is the most Pythonic way to write long comments.
You can also use triple quotes (""" or '''). If a string literal is not assigned to a variable, Python evaluates it but essentially ignores it.
"""
This is a multi-line comment
using triple-quoted strings.
It's often used for quick, temporary testing.
"""
print("Python ignores the string above.")
Warning: While this works as a comment, Python technically reads these as string constants. If placed immediately under a function or class definition, it turns into a Docstring (see below).
Docstrings are a special type of comment used to document modules, functions, classes, or methods. Unlike regular comments, docstrings are retained by the runtime and can be accessed using the __doc__ attribute or the help() function.
They must be written using triple quotes (""").
def greet(name):
"""
This function takes a name as an argument
and prints a personalized greeting.
"""
print(f"Hello, {name}!")
# Accessing the docstring
print(greet.__doc__)
In Python, displaying output to the screen and formatting strings neatly are core skills. Python has evolved significantly in how it handles string formatting, moving from older, clunky methods to modern, highly readable ones.
Here is everything you need to know about print() and string formatting.
The print() function sends data to the standard output device (your screen). It can take multiple arguments, separated by commas, and will automatically separate them with a space.
print("Hello", "World", 2026)
# Output: Hello World 2026
sep (Separator): Changes the character that separates the arguments (default is a space).
end (End line): Changes what gets printed at the very end of the line (default is a newline \n).
# Using sep to create a date string
print("16", "06", "2026", sep="-")
# Output: 16-06-2026
# Using end to print on the same line
print("Hello", end=" ")
print("World!")
# Output: Hello World!
Introduced in Python 3.6, f-strings (formatted string literals) are the most readable, concise, and fastest way to format strings.
To create an f-string, prefix the string with an f or F and write Python expressions inside curly braces {}.
name = "Alice"
age = 30
# Simple f-string
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 30 years old.
You can do math, call methods, and format numbers right inside the braces.
# 1. Math and operations
print(f"Next year, I will be {age + 1}.")
# 2. String methods
print(f"Shouting: {name.upper()}")
# 3. Float precision (Round to 2 decimal places)
pi = 3.14159
print(f"Pi to two decimals: {pi:.2f}") # Output: 3.14
# 4. Number formatting (Commas for thousands)
money = 1000000
print(f"Balance: ${money:,}") # Output: Balance: $1,000,000
While f-strings are the standard now, you will likely encounter two older methods in legacy codebases.
This method uses curly braces {} as placeholders and passes variables into the .format() function at the end.
name = "Bob"
# Position-based
print("Hello, {}. You are {}.".format(name, age))
# Index-based
print("Hello, {0}. Yes, {0}!".format(name))
This acts like printf in C. It uses specifiers like %s for strings and %d for integers. It is generally discouraged in modern Python because it gets messy quickly.
print("Hello, %s. You are %d." % (name, age))
Keywords in Python are reserved words that have a specific, predefined meaning to the Python interpreter. Because they are the building blocks of the language's syntax, you cannot use them as names for variables, functions, classes, or any other identifiers.
Python keywords are case-sensitive. Most of them are written in lowercase (like if, for, def), but three start with a capital letter (True, False, None).
As of Python 3.10 and newer, there are 35 built-in keywords. You can group them by their function to make them easier to remember:
These represent literal values in Python. Note that they are capitalized.
True: The boolean true value.
False: The boolean false value.
None: Represents the absence of a value or a null value.
Used to combine conditional statements.
and: Returns True if both statements are true.
or: Returns True if one of the statements is true.
not: Reverses the boolean result (not True becomes False).
is: Tests for object identity (checks if two variables point to the exact same object in memory).
in: Checks if a value is present in a sequence (list, tuple, string, etc.).
Used to make decisions and direct the flow of the program.
if: Starts a conditional statement.
elif: Short for "else if", used to check multiple conditions if the previous ones were false.
else: Executes a block of code if none of the preceding conditions are met.
Used to repeat blocks of code.
for: Creates a loop that iterates over a sequence.
while: Creates a loop that continues as long as a condition remains true.
break: Terminates the loop prematurely and skips to the next code block.
continue: Skips the current iteration of a loop and moves to the next one.
pass: A null statement that does nothing; used as a placeholder where code is syntactically required.
Used to create functions, classes, and scopes.
def: Defines a function.
class: Defines a user-defined class (object-oriented programming).
return: Exits a function and optionally hands back a value.
lambda: Creates an anonymous, short, single-expression function.
global: Declares that a variable inside a function is global (accessible outside the function).
nonlocal: Declares that a variable inside a nested function belongs to the outer enclosing function.
Used to catch and handle errors safely so your program doesn't crash.
try: Defines a block of code to test for errors.
except: Defines a block of code to run if an error occurs in the try block.
finally: Defines a block of code that will run regardless of whether an exception was raised or caught.
raise: Manually triggers an exception or error.
assert: Used for debugging; tests if a condition is true, throwing an error if it isn't.
Used to clean up resources and import external code.
import: Imports a module or library into your script.
from: Used alongside import to bring in specific parts of a module.
as: Creates an alias (shortcut name) for an imported module.
with: Wraps the execution of a block of code with methods defined by a context manager (great for safely opening/closing files).
Used for handling code that runs concurrently.
async: Declares that a function is an asynchronous coroutine.
await: Pauses the execution of an async function until a promise/future is resolved.
match: Used for structural pattern matching (similar to switch-case statements in other languages).
case: Defines specific patterns to look for inside a match block.
You can always get the live, up-to-date list of keywords directly from Python using the keyword module.
import keyword
# Print all keywords
print(keyword.kwlist)
# Check if a specific word is a keyword
print(keyword.iskeyword("apple")) # Output: False
print(keyword.iskeyword("if")) # Output: True
In Python, data types are used to classify the category of a value. Since Python is a dynamically typed language, you don’t need to explicitly declare the data type when you create a variable—Python figures it out automatically.
Python has the following data types built-in by default, in these categories:
Python uses escape sequences to insert characters that are otherwise difficult to type or would break the syntax of your string. By prefixing a character with a backslash (\), you tell Python to treat it as a special command rather than literal text.
Here is the breakdown of the escape sequences you mentioned, along with clear examples of how they behave in code.
Used to include a literal single quote inside a string that is already enclosed in single quotes. (Without the backslash, Python would think the string ended early).
# Without the backslash, this would throw a SyntaxError
print('It\'s a beautiful day!')
# Output: It's a beautiful day!
Because the backslash is the escape character itself, you need to type it twice to display a single literal backslash.
print("C:\\Users\\Desktop\\Project")
# Output: C:\Users\Desktop\Project
Note:
Linux: Uses /. No escaping needed. Safe and clean.
Windows: Uses \. Often requires \\ (double backslash) or a "raw string" prefix in code to prevent escape sequence errors.
Breaks the string and moves the remaining text to the next line.
print("Hello\nWorld!")
# Output:
# Hello
# World!
Moves the cursor (carriage) back to the beginning of the current line. Any text coming after the \r will overwrite the text that came before it.
print("Hello World!\rReset")
# Output: Reset World!
# (The word "Reset" overwrote "Hello")
Inserts a standard horizontal tab space (usually equal to 4 or 8 spaces, depending on your environment).
print("Name:\tAlice\tAge:\t25")
# Output: Name: Alice Age: 25
Moves the cursor back one space, effectively erasing the character that immediately precedes it.
print("Hello \bWorld!")
# Output: HelloWorld!
# (The space before \b was deleted)
Historically used to tell page printers to advance to the next page. In modern terminal outputs, it often shows up as a strange blank symbol or a page break, though its use is quite rare today.
print("Page 1\fPage 2")
# Output (in some terminals):
# Page 1
# Page 2
Allows you to insert a character based on its 3-digit octal (base-8) number value.
# 110 in octal represents the letter 'H'
# 151 in octal represents the letter 'i'
print("\110\151")
# Output: Hi
Allows you to insert a character based on its 2-digit hexadecimal (base-16) number value.
# 48 in hex is 'H'
# 69 in hex is 'i'
print("\x48\x69")
# Output: Hi
Note: If you want to ignore all escape sequences in a string (like when dealing with complex file paths or regular expressions), you can prefix the string with an r or R. This creates a raw string.
print(r"C:\Users\name\new_folder")
# Output: C:\Users\name\new_folder (The \n wasn't treated as a new line!)
In Python, the input() function is your go-to tool when you want to make your programs interactive. It pauses the execution of your code and waits for the user to type something in.
When you call input(), you can pass an optional string as a prompt. This prompt is displayed on the screen so the user knows what they are supposed to type.
name = input("Enter your name: ")
print("Hello, " + name + "!")
How it works:
The program prints Enter your name: and blinks, waiting for input.
The user types Aaron and hits Enter.
The string "Aaron" is saved into the variable name.
The program prints Hello, Aaron!.
This is the most common trip-up for beginners. No matter what the user types—whether it's a name, a whole sentence, or a number like 42—input() always treats it as a string (text).
If you try to do math with a raw input, Python will throw an error:
# This will cause a TypeError later if you try to do math!
age = input("Enter your age: ")
# If the user types 25, age is actually stored as the string "25"
If you need the user to input a number (an integer or a decimal/float), you must wrap the input() function inside a conversion function like int() or float().
1. Getting an Integer (Whole Number)
age = int(input("Enter your age: "))
print(f"In 5 years, you will be {age + 5}.")
2. Getting a Float (Decimal Number)
price = float(input("Enter the item price: $"))
discounted_price = price * 0.9
print(f"The discounted price is ${discounted_price:.2f}")
When it comes to passwords, using the standard input() function has one massive flaw: it displays the password on the screen in plain text as the user types it. This is a major security risk known as "shoulder surfing" (where someone looking over your shoulder can see the password).
To fix this, Python has a built-in module called getpass designed specifically for handling passwords and sensitive data securely.
The getpass module hides the characters as they are being typed. Depending on your operating system or terminal, it will either show nothing at all as you type, or show asterisks (****).
Here is how you use it:
import getpass
username = input("Username: ")
# Instead of input(), use getpass.getpass()
password = getpass.getpass("Password: ")
print(f"Logged in successfully as {username}!")
Username: jsmith
Password: <- (The cursor moves, but typing is invisible!)
Logged in successfully as jsmith!
It works just like input(): It stops the program, prints a prompt, and always returns the result as a string.
IDLE/GUI Limitations: If you are using Python's default IDLE editor or certain built-in terminals in code editors (like older versions of PyCharm or VS Code), getpass might sometimes fallback to a normal, visible input text box because those environments don't support masking. It works perfectly in standard terminal/command prompt environments.
Custom Prompts: If you don't provide a prompt inside the parentheses (e.g., getpass.getpass()), it will automatically default to printing "Password: ".
Security Best Practice: Just like regular input(), getpass stores the password in computer memory as plain text. While this keeps it safe from people looking at your screen, you should never hardcode or print passwords out in your final application!
In this example: - x=20 (0001 0100) and y=12 (0000 1100)
Assignment Operators in Python
Identity Operator
Logical Operator
In Python, conditional statements allow your code to make decisions and execute different blocks of code based on whether a condition is true or false.
Python uses three main keywords for conditional logic:
if: The starting point. It checks a condition.
elif (short for else if): Checks another condition only if the previous conditions were false. You can have multiple elif blocks.
else: The safety net. It runs if none of the above conditions are met.
if condition1:
# Runs if condition1 is True
print("Condition 1 is met")
elif condition2:
# Runs if condition1 is False AND condition2 is True
print("Condition 2 is met")
else:
# Runs if all previous conditions are False
print("No conditions were met")
Crucial Python Rule: Python relies on indentation (usually 4 spaces) to define what code belongs inside the conditional block. Missing indentation will trigger an IndentationError.
Let's look at a simple grading system:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B") # This will print
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
You can chain multiple conditions together using logical operators:
and: Returns True if both statements are true.
or: Returns True if at least one statement is true.
not: Reverses the result (turns True to False and vice versa).
age = 22
has_id = True
if age >= 21 and has_id:
print("Entry allowed.")
If you have a very simple if-else statement, you can compress it into a single line. This is great for assigning variables based on a condition.
Syntax: expression_if_true if condition else expression_if_false
age = 16
status = "Adult" if age >= 18 else "Minor"
print(status) # Outputs: Minor
You can place an if statement inside another if statement. Just keep an eye on your indentation!
num = 15
if num > 0:
print("Positive number")
if num % 2 == 0:
print("And it's even")
else:
print("And it's odd") # This will print