Programming is the process of creating instructions that a computer can understand and execute to perform specific tasks. These instructions are written in a programming language, which is a way for humans to communicate with computers.
Low-Level Languages:
Directly interact with hardware.
Example: Assembly language, Machine code.
Harder to read and write, but extremely efficient.
Example of Assembly code:
MOV AX, BX ; Move the value from BX to AX
High-Level Languages:
Interpreted vs. Compiled Languages:
Python code can be executed in two primary ways:
Interactive Mode:
Allows you to test Python code interactively in a terminal or shell.
Use the command python or python3 to enter the Python REPL (Read-Eval-Print Loop).
Example:
>>> print("Hello, World!")
Hello, World!
Script Mode:
Used to write more extensive and reusable Python programs in .py files.
Run a Python script by typing python script_name.py in the terminal.
Example:
#my_script.py
print("Hello from a script!")
Statements:
A statement is a single instruction that the Python interpreter can execute.
Example:
x = 5 # Assignment statement
print(x) # Print statement
Blocks:
A block is a group of statements that are executed together.
Python uses indentation to define blocks (4 spaces is the standard).
Example:
if x > 0:
print("x is positive") # This is part of the block
print("Block ends here")
Indentation:
Indentation is mandatory in Python and defines the structure of the program.
Example:
if x > 0:
print("Positive number") # Indented block
Comments are used to explain the code and are ignored by the Python interpreter. They help make the code more understandable for others (or yourself in the future).
Single-line Comments:
Start with a # symbol.
Example:
#This is a single-line comment
print("Comments are ignored by the interpreter")
Multi-line Comments:
Enclosed in triple quotes (""" or ''').
Example:
"""
This is a multi-line comment.
It spans multiple lines.
"""
print("Multi-line comments are also ignored")
Definition: Keywords are reserved words in Python that have a special meaning and cannot be used as variable names.
Examples of Keywords: if, else, while, for, class, def, return, etc.
To see the full list of keywords:
help("keywords")
Definition: Identifiers are names used to identify variables, functions, or objects in Python.
Rules for Identifiers:
_.Name and name are different identifiers.Examples:
my_variable = 10 # Valid
_hidden_variable = 20 # Valid
1variable = 30 # Invalid
Python uses whitespace (indentation) to define code blocks.
Incorrect indentation raises an IndentationError.
Example:
#Correct indentation
if x > 0:
print("Positive")
#Incorrect indentation
if x > 0:
print("Positive") # This will raise an IndentationError
Definition: Variables are used to store data values.
Declaration and Initialization:
Python does not require explicit variable declarations.
Example:
x = 10 # Integer
name = "Alice" # String
int (Integer):42, -5).float (Floating-point):3.14, -0.5).str (String):"Hello", 'World').bool (Boolean):True or False.Example:
x = 10 # Initially, x is an integer
print(type(x)) # Output: <class 'int'>
x = "Now a string" # x is reassigned to a string
print(type(x)) # Output: <class 'str'>
Type conversion is the process of converting one data type into another.
Implicit Conversion:
Python automatically converts a smaller data type to a larger data type (e.g., int to float) when required.
Example:
x = 3
y = 2.5
result = x + y # x is implicitly converted to float
print(result) # Output: 5.5
print(type(result)) # Output: <class 'float'>
Explicit Conversion:
You can manually convert data types using built-in functions like int(), float(), and str().
Example:
#Convert string to integer
x = int("42")
print(x) # Output: 42
#Convert integer to string
y = str(123)
print(y) # Output: "123"
print(type(y)) # Output: <class 'str'>
Common Conversion Functions:
int(): Converts a value to an integer.float(): Converts a value to a float.str(): Converts a value to a string.bool(): Converts a value to a Boolean.Operators are symbols or keywords used to perform operations on variables or values. Python provides several categories of operators.
Arithmetic operators are used for mathematical calculations.
| Operator | Description | Example | Output |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 5 / 2 |
2.5 |
// |
Floor Division | 5 // 2 |
2 |
% |
Modulus (remainder) | 5 % 2 |
1 |
** |
Exponentiation | 2 ** 3 |
8 |
Examples:
a = 10
b = 3
print(a + b) # Output: 13
print(a % b) # Output: 1
print(a ** b) # Output: 1000
Comparison operators compare two values and return a Boolean result (True or False).
| Operator | Description | Example | Output |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
< |
Less than | 3 < 5 |
True |
> |
Greater than | 5 > 3 |
True |
<= |
Less than or equal to | 3 <= 3 |
True |
>= |
Greater than or equal to | 5 >= 3 |
True |
Example:
x = 10
y = 20
print(x < y) # Output: True
print(x == y) # Output: False
Logical operators are used to combine conditional statements.
| Operator | Description | Example | Output |
|---|---|---|---|
and |
Returns True if both conditions are true |
(5 > 3) and (3 > 1) |
True |
or |
Returns True if at least one condition is true |
(5 > 3) or (3 < 1) |
True |
not |
Reverses the Boolean result | not(5 > 3) |
False |
Example:
x = 5
print(x > 3 and x < 10) # Output: True
print(x > 3 or x < 4) # Output: True
print(not(x > 3)) # Output: False
Assignment operators are used to assign values to variables.
| Operator | Description | Example | Equivalent To |
|---|---|---|---|
= |
Assign | x = 5 |
|
+= |
Add and assign | x += 3 |
x = x + 3 |
-= |
Subtract and assign | x -= 3 |
x = x - 3 |
*= |
Multiply and assign | x *= 3 |
x = x * 3 |
/= |
Divide and assign | x /= 3 |
x = x / 3 |
Example:
x = 10
x += 5
print(x) # Output: 15
x *= 2
print(x) # Output: 30
Bitwise operators perform operations on binary representations of numbers.
| Operator | Description | Example | Output |
|---|---|---|---|
& |
AND | 5 & 3 |
1 |
| ` | ` | OR | `5 |
^ |
XOR | 5 ^ 3 |
6 |
~ |
NOT | ~5 |
-6 |
<< |
Left shift | 5 << 1 |
10 |
>> |
Right shift | 5 >> 1 |
2 |
Example:
x = 5 # Binary: 0101
y = 3 # Binary: 0011
print(x & y) # Output: 1 (Binary: 0001)
print(x | y) # Output: 7 (Binary: 0111)
The input() function is used to get input from the user as a string.
Example:
name = input("Enter your name: ")
print("Hello, " + name)
The print() function displays information to the console.
Example:
age = 25
print(f"I am {age} years old.") # Output: I am 25 years old.
type() and id()type() FunctionThe type() function returns the type (class) of a given object. It is often used to verify the data type of a variable, especially in debugging or when handling dynamically typed values.
Syntax:
type(object)
Example:
x = 42
print(type(x)) # Output: <class 'int'>
This tells you that x is of type int.
id() FunctionThe id() function returns the “identity” of an object. This identity is a unique integer that remains constant for the object during its lifetime. In CPython (the most common Python interpreter), this corresponds to the memory address.
Syntax:
id(object)
Example:
x = 42
print(id(x)) # Output: a unique integer representing the object's memory address
Although this output is not meaningful for logic, it helps in understanding how variables reference memory.
While the PCEP exam does not focus heavily on writing exception handling code, it often includes questions that test your understanding of error types resulting from incorrect syntax or operations.
SyntaxErrorOccurs when the code is not syntactically correct.
Example:
print("Hello" # Missing closing parenthesis → SyntaxError
This error happens before the code is even executed.
TypeErrorOccurs when an operation or function is applied to an object of inappropriate type.
Example:
print("5" + 5) # TypeError: cannot concatenate str and int
You cannot add a string and an integer directly. You must explicitly convert one to match the other's type.
print("5" + str(5)) # Output: 55
NameErrorOccurs when you try to use a variable that hasn’t been defined.
print(x) # If x was never assigned before → NameError
The bool() function is used to convert values into Boolean True or False. Understanding which values evaluate to False is essential for writing conditional logic.
The following values evaluate to False when converted using bool():
The number zero: 0, 0.0
Empty sequences or collections: '', [], {}, ()
The special value None
Example:
print(bool("")) # Output: False
print(bool([])) # Output: False
print(bool(0)) # Output: False
print(bool(None)) # Output: False
Any value not listed above is considered True when converted to a Boolean.
Example:
print(bool("hello")) # Output: True
print(bool(1)) # Output: True
print(bool([1, 2])) # Output: True
print() with sep and end ParametersThe print() function can be customized using the sep and end parameters:
sep (separator): Defines the string inserted between arguments.
end: Defines what is printed at the end of the output (default is newline \n).
sepprint("apple", "banana", "cherry", sep=" | ")
#Output: apple | banana | cherry
endprint("Hello", end="!!!")
print("World")
#Output: Hello!!!World
print("Hello", "World", sep="--", end="!!!")
#Output: Hello--World!!!
This is a frequent PCEP test pattern, often used to assess your understanding of Python's flexibility in output formatting.
| Concept | Function / Use | Example |
|---|---|---|
type() |
Returns type of object | type(5) → <class 'int'> |
id() |
Returns unique object ID | id(x) |
| Error Types | SyntaxError, TypeError |
print("5" + 5) → TypeError |
bool() conversion |
Empty = False, Non-empty = True |
bool("") → False, bool("Hi") → True |
print(sep=, end=) |
Output control | print("A", "B", sep="--", end="!") |
Why does the input() function always return a string even when the user types a number?
The input() function always returns user input as a string because it is designed to capture raw text from standard input.
Python does not automatically infer numeric types from user input. Even if a user enters “10”, it is treated as "10". To use it numerically, explicit type conversion is required using functions like int() or float(). A common mistake is performing arithmetic directly on input values, leading to string concatenation instead of numeric addition. For example, "10" + "5" results in "105", not 15. Proper handling requires converting input before computation.
Demand Score: 82
Exam Relevance Score: 90
What is the difference between int, float, and string types in Python?
int represents whole numbers, float represents decimal numbers, and string represents text.
The int type handles integers like 5 or -3, while float handles numbers with decimals like 3.14. Strings are sequences of characters enclosed in quotes, such as "hello". A common confusion arises when numbers are stored as strings, preventing arithmetic operations. For example, "5" * 2 results in "55", not 10. Understanding these distinctions is critical for selecting the correct data type and avoiding unintended behavior in expressions.
Demand Score: 80
Exam Relevance Score: 88
How does operator precedence affect the result of expressions in Python?
Operator precedence determines the order in which operations are evaluated in an expression.
Python evaluates expressions using a predefined hierarchy, where operations like multiplication and division occur before addition and subtraction. For example, 2 + 3 * 4 evaluates to 14, not 20. Parentheses can override precedence, forcing specific evaluation order. A frequent mistake is assuming left-to-right execution without considering precedence rules, leading to incorrect results. Understanding precedence ensures predictable computation outcomes.
Demand Score: 75
Exam Relevance Score: 85
How do different numeral systems (binary, octal, hexadecimal) work in Python?
Python supports multiple numeral systems using specific prefixes: 0b for binary, 0o for octal, and 0x for hexadecimal.
These numeral systems allow representation of numbers in different bases. For example, 0b1010 equals 10 in decimal, and 0xA also equals 10. Python internally converts them into decimal for computation. A common mistake is treating them as strings rather than numeric values. Understanding these systems is useful when working with low-level data or bitwise operations.
Demand Score: 70
Exam Relevance Score: 82