Live Execution Engine

In-Browser Python Simulator

Test any Python code right inside your browser! Type or edit the code below and press Run Code.

Python 3 Sandbox
# Python 3 Practical Demo
name = "Student"
age = 16
print("Welcome to Cyber-Learn Python Studio!")
print("Hello,", name, "- Age:", age)

a = 10
b = 3
print("10 // 3 =", a // b)
print("10 ** 3 =", a ** b)
Click "Run Code" to view program output here.
Unit 3 • Section 3.1

3.1 Introduction to Python Programming

Python is a high-level, widely-used programming language famous for its simplicity and readability. It is versatile and is used worldwide in fields like web development, data analysis, and artificial intelligence (AI).

3.1.1 Basic Programming Concepts

Computer programming is the process of creating a set of instructions that tell a computer how to perform a task. The programming lifecycle consists of four steps:

  1. Write Code: Type the instructions in a code editor.
  2. Compile / Interpret: The computer translates code into machine language (0s and 1s).
  3. Execute: Run the program to produce the desired result.
  4. Fix Errors (Debugging): Correct logic or syntax mistakes if results differ from expectation.

Setting Up the Python Development Environment

  1. Download Python: Visit https://www.python.org, navigate to Downloads, and get the latest version (e.g., Python 3.13.x).
  2. Install Python: Run the downloaded installer.
  3. CRITICAL STEP: Check the box "Add Python to PATH" during setup so system command line can access Python.
  4. Set up an IDE: Use PyCharm (Community Edition), VS Code, or IDLE (built into Python).
  5. Configure IDE: Set interpreter path (e.g., C:\Python312\python.exe).
  6. Test Setup: Create test.py and execute the test program below.
First Test Program (test.py)
print("Hello, Python!")
Hello, Python!
Google Colab Cloud Alternative: You can also use colab.research.google.com — a free cloud platform where Python comes pre-installed with scientific libraries (NumPy, Pandas, Matplotlib) without local installation!
Unit 3 • Section 3.2

3.2 Basic Python Syntax & Structure

The print() function is used to display output text on the screen. Notice how clean Python syntax is compared to older languages:

print() Function Example
print("K2 is the second-highest mountain in the world")
print("Edhi Foundation operates the world's largest volunteer ambulance network.")
K2 is the second-highest mountain in the world Edhi Foundation operates the world's largest volunteer ambulance network.

Python Comments

Comments are lines ignored by the interpreter. They explain code logic to programmers:

  • Single-line comment: Starts with # symbol.
  • Multi-line block: Enclosed in triple quotes ''' ... '''.
Comments Example
# This is a single line comment
print("K2 is the second-highest mountain in the world")

''' Multi-line comment block
    explaining information for students '''
print("Edhi Foundation operates the world's largest volunteer ambulance network.")
K2 is the second-highest mountain in the world Edhi Foundation operates the world's largest volunteer ambulance network.

3.2.1 Variables in Python

A variable is a named storage container in memory holding values that can change during program execution.

Variable Modification Example
print("Hello dear students!")

age = 71
print("Azam lived for", age, "years")

age = 60
print("Iqbal lived for", age, "years")
Hello dear students! Azam lived for 71 years Iqbal lived for 60 years

Variable Naming Rules

  • Must begin with a letter (a-z, A-Z) or an underscore ( _ ).
  • Remaining characters can be letters, digits (0-9), or underscores.
  • Names are case-sensitive (e.g., age and Age are distinct).
  • Python reserved keywords cannot be used as variable names.
Reserved Keywords in Python:
if, else, elif, for, while, break, continue, and, or, not, in, is, True, False, None

Basic Data Types

Data TypeMeaningExample
intWhole numbers without decimalage = 17
floatDecimal floating-point numbersprice = 19.99
strText strings enclosed in quotesname = "Ali"
boolBoolean truth values (True or False)is_student = True

Input and Output Operations

input(): Function displays prompt text and waits for user entry. Returns input as a string (str).

print(): Displays output value on console screen.

Greeting Input Example
name = input("Enter your name: ")
print("Hello, " + name + "!")
Enter your name: Maryam Ashraf Hello, Maryam Ashraf!

Type Conversion with int() & float()

Convert string input into numbers using int() for whole numbers or float() for decimals.

Numeric Input Casting
user_age = int(input("Enter your age: "))
print("Your age is:", user_age)

user_height = float(input("Enter height in meters: "))
print("Your height is", user_height, "meters")
Enter your age: 16 Your age is: 16 Enter height in meters: 1.5 Your height is 1.5 meters
Unit 3 • Section 3.3

3.3 Operators & Expressions

Operators are symbols performing calculations on values (operands). Expressions combine variables, constants, and operators.

3.3.1 Arithmetic Operators

All Arithmetic Operators (Book Practical)
# Define variables
a = 10
b = 3

# Perform all arithmetic operations on these numeric variables and print results
print(a, "+", b, "=", a + b)     # Output: 10+3=13
print(a, "-", b, "=", a - b)     # Output: 10-3=7
print(a, "*", b, "=", a * b)     # Output: 10*3=30
print(a, "/", b, "=", a / b)     # Output: 10/3=3.3333333333333335
print(a, "//", b, "=", a // b)   # Output: 10//3=3   #floor division
print(a, "%", b, "=", a % b)     # Output: 10%3=1
print(a, "**", b, "=", a ** b)   # Output: 10**3=1000   # represent power operator:
10 + 3 = 13 10 - 3 = 7 10 * 3 = 30 10 / 3 = 3.3333333333333335 10 // 3 = 3 10 % 3 = 1 10 ** 3 = 1000

3.3.2 Comparison Operators

All Comparison Operators
# Define variables
x = 10
y = 5

# Greater than
print(x, ">", y, "=", x > y)      # Output: 10 > 5 = True
# Less than
print(x, "<", y, "=", x < y)      # Output: 10 < 5 = False
# Equal to
print(x, "==", y, "=", x == y)    # Output: 10 == 5 = False
# Not equal to
print(x, "!=", y, "=", x != y)    # Output: 10 != 5 = True
# Greater than or equal to
print(x, ">=", y, "=", x >= y)    # Output: 10 >= 5 = True
# Less than or equal to
print(x, "<=", y, "=", x <= y)    # Output: 10 <= 5 = False
10 > 5 = True 10 < 5 = False 10 == 5 = False 10 != 5 = True 10 >= 5 = True 10 <= 5 = False

3.3.3 Compound Assignment Operators

Compound Assignment Operators
# Define initial values
a = 10
b = 5

# Assignment
a = a
print("a =", a)                          # Output: a = 10

# Addition assignment
a += b
print("a after addition =", a)           # Output: a = 15

# Subtraction assignment
a -= b
print("a after subtraction =", a)        # Output: a = 10

# Multiplication assignment
a *= b
print("a after multiplication =", a)     # Output: a = 50

# Division assignment
a /= b
print("a after division =", a)           # Output: a = 10.0

# Floor division assignment
a //= b
print("a after floor division =", a)     # Output: a = 2.0

# Modulus assignment
a %= b
print("a after modulus =", a)            # Output: a = 2.0

# Exponentiation assignment
a **= b
print("a after exponentiation =", a)     # Output: a = 32.0
a = 10 a after addition = 15 a after subtraction = 10 a after multiplication = 50 a after division = 10.0 a after floor division = 2.0 a after modulus = 2.0 a after exponentiation = 32.0

3.3.4 Logical Operators

Logical operators are used to combine multiple conditions or expressions. The most common logical operators are and, or, and not — they perform logical operations and return Boolean values (True or False) based on the evaluation of the expressions involved.

All Logical Operators (Book Practical)
# Define variables
x = True
y = False

# Logical AND
logical_and = x and y
print(x, "and", y, "=", logical_and)      # Output: True and False = False

# Logical OR
logical_or = x or y
print(x, "or", y, "=", logical_or)        # Output: True or False = True

# Logical NOT
logical_not_x = not x
print("not", x, "=", logical_not_x)       # Output: not True = False

logical_not_y = not y
print("not", y, "=", logical_not_y)       # Output: not False = True
True and False = False True or False = True not True = False not False = True

3.3.5 Operator Precedence

Precedence rules determine evaluation order:

  1. Parentheses ( ) — highest priority.
  2. Exponentiation ** — right-associative power operator.
  3. Multiplication / Division / Modulo (*, /, //, %).
  4. Addition / Subtraction (+, -).
Precedence Worked Textbook Example
print(4 * 3 + 10 / 2 - 11 % 3)
15.0

Book full demonstration program: (note the f before each string — in Python, f-strings are used for string interpolation, embedding variables or expressions inside a string):

PYTHON OPERATOR PRECEDENCE DEMONSTRATION
print("= PYTHON OPERATOR PRECEDENCE DEMONSTRATION =")

# 1. Arithmetic Operators
print("1. ARITHMETIC OPERATORS:")
print(f"3 + 2 * 5 = {3 + 2 * 5}")        # Multiplication before addition
print(f"(3 + 2) * 5 = {(3 + 2) * 5}")    # Parentheses change the order
print(f"3 ** 2 = {3 ** 2}")              # Exponentiation
print(f"2 ** 3 * 4 = {2 ** 3 * 4}")      # Exponentiation before multiplication
print(f"15 / 3 * 2 = {15 / 3 * 2}")      # Division and multiplication (left to right)
print(f"15 // 4 + 2 = {15 // 4 + 2}")    # Floor division before addition
print(f"11 // 4 + 2 = {11 // 4 + 2}")    # Floor division before addition
print(f"17 % 5 * 2 = {17 % 5 * 2}")      # Modulo before multiplication
= PYTHON OPERATOR PRECEDENCE DEMONSTRATION = 1. ARITHMETIC OPERATORS: 3 + 2 * 5 = 13 (3 + 2) * 5 = 25 3 ** 2 = 9 2 ** 3 * 4 = 32 15 / 3 * 2 = 10.0 15 // 4 + 2 = 5 11 // 4 + 2 = 4 17 % 5 * 2 = 4
Do You Know? In Python, the f before a string is used for string interpolation (embedding variables or expressions inside a string). Exponentiation ** is right associative — when there are multiple exponents, Python evaluates them from right to left (e.g., 2 ** 3 ** 2 = 2 ** 9 = 512).
Cyber Interactive Visualizer Suite

Visual Concepts Studio

Interact directly with RAM memory allocation, operator precedence step evaluator, and First-Come First-Served process scheduler!

Real-time RAM Memory Inspector

Enter a Python variable assignment below to visualize memory address allocation:

0x7FFF01
age
71
int
0x7FFF02
name
"Ali"
str
0x7FFF03
height
1.5
float
Exercise Practicals Lab

Textbook Exam Practicals Solver

All four textbook exercise practicals are pre-loaded with interactive validation!

Practical 1: Greeting Message

Write a program taking user name and outputting a greeting message.

greeting.py
name = input("Enter your name: ")
print("Hello,", name, "! Welcome to Python programming.")
Enter your name: Ali Hello, Ali ! Welcome to Python programming.

Practical 2: Sum of Two Numbers

Write a program asking user for two integers and printing their sum.

sum_two.py
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

sum_val = num1 + num2
print("The sum is:", sum_val)
Enter first number: 12 Enter second number: 30 The sum is: 42

Practical 3: Average of Five Numbers

Write a program accepting 5 integers and calculating average.

average_five.py
n1 = int(input("Enter number 1: "))
n2 = int(input("Enter number 2: "))
n3 = int(input("Enter number 3: "))
n4 = int(input("Enter number 4: "))
n5 = int(input("Enter number 5: "))

avg = (n1 + n2 + n3 + n4 + n5) / 5
print("The average is:", avg)
The average is: 30.0

Practical 4: Solve Expressions

Evaluate 10 // 3, 10 / 3, 10 % 3, 2 ** 4.

expressions.py
print("10 // 3 =", 10 // 3)
print("10 / 3 =", 10 / 3)
print("10 % 3 =", 10 % 3)
print("2 ** 4 =", 2 ** 4)
10 // 3 = 3 10 / 3 = 3.3333333333333335 10 % 3 = 1 2 ** 4 = 16
Knowledge Verification

Gamified Practice Quiz

Test your knowledge to gain XP and level up your programmer badge!

Question 1: What is the output of Python expression 10 // 3?

Recap

Chapter Summary

  • Python is high-level, readable, and used in AI, web development, and data science.
  • Always select "Add Python to PATH" when installing from python.org.
  • input() reads string inputs — use int() / float() to convert.
  • Variable names are case-sensitive and cannot use reserved keywords (like if, else, for).
  • Operators include arithmetic (+ - * / // % **), comparison (> < == != >= <=), and logical (and or not).
  • Operator precedence order: Parentheses () > Power ** > Mult/Div * / // % > Add/Sub + -.