Python Fundamentals
1. Computer Programming
Definition: Process of writing a set of instructions to solve real-life problems.
Programming languages have rules called syntax (like grammar in human languages) while giving the instruction to the computer.
Examples of programming languages: Python, Java, JavaScript, C, C++.
2. Introduction to Python
Python is recommended as the first programming language for beginners as it is simple and easy to learn.
File extension: .py
History:
Developed by Guido van Rossum in 1989 at the National Research Institute, Netherlands.
Released publicly in 1991.
Name inspired by the BBC TV show “Monty Python’s Flying Circus”.
3. Features of Python
Free and Open-Source – no cost, even for commercial use.
Cross-platform – works on Windows, macOS, Linux.
Interpreted Language – executes code line by line.
Dynamically Typed – variables can change types during runtime.
Code Optimization – fewer lines of code compared to other languages.
Example: Printing “Hello World” in Python requires just one line.
4. Career Opportunities with Python
Data Analyst – data collection, processing, and visualization.
Web Developer – dynamic websites & apps.
Machine Learning Engineer – building predictive models.
AI Developer – creating intelligent systems.
5. Python Text Editor (IDLE)
IDLE = Integrated Development Learning Environment.
Installed automatically with Python.
Used for writing and running Python programs.
Two modes:
Interactive Mode (Shell) – quick testing and exploration.
Script Mode (Editor) – creating, saving, and reusing full programs.
6. Using Python IDLE
Installation: Download from python.org → Check “Add Python to PATH” during installation.
Creating a file: File → New File → Write code → Save with .py.
Running a program: Run → Run Module (or press F5).
Opening an existing file: Right-click file → Edit with IDLE.
7. Key Points
Programming - giving instructions to a computer.
Syntax - rules of a programming language.
Python - simple, powerful, beginner-friendly.
.py - file extension for Python programs.
IDLE - built-in editor (Interactive Mode + Script Mode).
Careers - Data, Web, AI, ML.
Try it >>>
1. Output in Python
Output: Information or result produced by a computer after input, processing, and storage.
In Python, print() function is used to display messages, text, numbers, or results on the console/terminal.
2. Syntax of print()
print(object, sep="", end="")
object → Mandatory (what you want to print).
sep → Optional (separator between multiple objects, default is space).
end → Optional (what to print at the end, default is newline \n).
👉 If the object is a string, enclose it in quotes (' ' or " ").
👉 If the object is a variable, no quotes are needed.
3. Output Formatting
Output formatting makes the displayed result more readable and meaningful.
Some of the ways to format output:
Comma Operator ( , ) – separates values with a space.
print("Name:", "Karma") # Output: Name: Karma
Plus Operator ( + ) – concatenates (joins) strings.
print("Hello" + " Bhutan") # Output: Hello Bhutan
F-Strings – allows inserting variables/expressions directly inside strings.
name = "Dorji"
print(f"My name is {name}") # Output: My name is Dorji
1. What is a Variable?
A variable is a container for storing data values.
Variables store different data types like:
Numbers (integers, floats)
Strings (text)
Lists, Sets, Tuples, Dictionaries
Example:
age = 15 --------- storing numbers
name = "Sonam" --------- storing strings
cars = ["Alto", "Prado", "Hilux", "Creta"] ------- a list
2. Importance of Variables
Data Storage – store values for later use.
Data Manipulation – use variables in calculations/operations.
Value Sharing – share data across different parts of a program.
Data Representation – descriptive variable names make programs clearer.
3. Rules for Naming Variables
✅ Rules:
Must begin with a letter or an underscore (_).
Cannot start with a number.
Can only contain letters, numbers, and underscores.
Are case-sensitive (Name and name are different).
Should be descriptive (use meaningful names).
❌ Invalid examples:
2value, my-name, class
✅ Valid examples:
age, student_name, _count
4. Types of Variable Assignment
Direct Assignment
x = 10
name = "Karma"
Multiple Assignment
x = y = 4 # same value to multiple variables
Chained Assignment
x, y, z = 3, 4, 5 # different values to multiple variables
Comments in Python
Comments are lines in code that explain what the code does.
Not executed by the computer.
Written for human readers (programmers).
Help improve readability, understanding, and collaboration.
Benefits of Comments:
Make code easier to understand.
Act as reminders or explanations.
Help other programmers when maintaining or updating code.
Useful in debugging and teamwork.
Types of Comments:
Single-line Comments
Start with # (hash symbol).
Everything after # on the same line is treated as a comment.
Used for short explanations.
Example:
# This code adds two numbers
x = 5 + 10
Multi-line Comments
Written inside triple quotes (""" ... """).
Can span across multiple lines.
Used for long explanations, documentation, or describing algorithms.
Example:
"""
This program demonstrates
the use of multi-line comments.
"""
print("Hello World")
Input Function in Python
input() is used to get information from the user during program execution.
The entered data is always stored as a string (text), even if it looks like a number.
Program pauses and waits for the user to type and press Enter.
Syntax:
variable = input("Message to user: ")
Examples:
name = input("Enter your name: ")
print("Hello", name)
Importance of input():
Makes the program interactive.
Collects data from the user.
Stores user responses in variables.
Useful for personalized outputs.
Good programming refers to writing code that is efficient, easy maintainable, and follows best practices to enhance readability.
Common practices:
Code testing and debugging
Code optimization
Code documentation
Advantages
Easy to understand
Less hassle to update/maintain
Code reuse (modular programming)
Faster performance
Clear documentation and reliable testing
Debugging
Definition: Finding and fixing mistakes (bugs) in a program.
Like being a “detective” for your code.
Importance of Debugging:
Identifies errors in the code
Improves quality and reliability
Saves time/resources by catching problems early
Optimizes performance
Types of Errors
Syntax Error – Mistake in code rules (e.g., missing punctuation, wrong keywords).
Example: x==”PEMA” instead of x=="PEMA"
Semantic Error – Mistake in logic/meaning (code runs but gives wrong results).
Example: dividing a number by 0.
Code Optimization
Definition: Improving program performance by reducing execution time and memory usage.
Techniques:
Use efficient algorithms
Remove repetitive code
Use Python features (multiple assignments, loops, etc.)
Example:
# Multiple assignment
x, y, z = "karma", 24, "Khaling"
print("My name:", x, "Age:", y, "I am from:", z)
Code Documentation
Definition: Writing explanations inside code for clarity.
Methods:
Comments (inline notes in code)
Function documentation (purpose, parameters, return values, exceptions)
Usage of examples
Data types represent the types of data present inside a variable. In other words, a data type is like a label that tells the computer what kind of information is stored in a variable. A data type could be a number, a piece of text, or a true/false value.
Data types in programming helps in:
Efficient memory usage
Preventing errors
Improving readability
Classification of Python Data Types
Numeric Types
int → represents whole numbers (5, -10)
float → represents decimals numbers (3.14, -2.5)
complex → numbers with real & imaginary parts (4+8j)
Text Type
str → represents sequence of characters in quotes (‘ ’, “ ”, or ''' ''')
Sequence Types
list → ordered, changeable, in [ ]
tuple → ordered, unchangeable, in ( )
range → sequence of numbers, often in loops
Mapping Type
dict → consists of key-value pairs {“name”: “Pema”}
Set Types
set → unordered, { }
frozenset → immutable version of a set
Boolean Type
bool → True or False (used in conditions)
Strings in Detail
Quotes: single('abc'), double("abc"), triple('''abc''')
Indexing:
Positiveve index (left → right, starts from 0)
Negative index (right → left, starts from -1)
Slice Operator [start:stop:step]
String Operations:
Concatenation (+)
Repetition (*)
Type Casting
Converting one data type to another.
Functions:
int(), float(), complex(), str(), bool()
Escape Characters
Special characters inside strings:
\n → newline
\t → tab space
\" → double quote
\' → single quote
\\ → backslash
What are Operators?
Operators are symbols or characters that perform operations on operands (variables, values, or expressions).
Example:
x = 5
y = 2
print(x + y) # + is an operator
Importance of Operators
Perform calculations and logical operations.
Help compare values and make decisions.
Used to manipulate data in programs.
Improve computational efficiency.
3. Types of Operators in Python
1. Arithmetic Operators
Used for mathematical calculations.
Addition +
Subtraction -
Multiplication *
Division /
Floor Division // → whole number division
Modulus % → remainder
Exponentiation ** → power
Example:
a = 7; b = 3
print(a+b) # 10
print(a-b) # 4
print(a*b) # 21
print(a/b) # 2.33
print(a//b) # 2
print(a%b) # 1
print(a**b) # 343
2. Assignment Operators
Used to assign values to variables.
= (simple assignment)
+=, -=, *=, /=, %=, **=, //=
Example:
x = 10
x += 5 # x = x + 5 → 15
3. Comparison Operators
Used to compare two values. Returns True/False.
== (equal to)
!= (not equal to)
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
Example:
5 > 3 # True
7 == 8 # False
4. Logical Operators
Used to combine conditional statements.
and → True if both are True
or → True if one is True
not → reverses the result
Example:
x = 10; y = 5
print(x > 5 and y < 10) # True
print(x < 5 or y < 10) # True
print(not(x > 5)) # False
5. Membership Operators
Check if a value exists in a sequence (string, list, tuple).
in → True if present
not in → True if not present
Example:
print('g' in 'songs') # True
print('z' not in 'training') # True
6. Identity Operators
Check if two objects refer to the same memory location.
is → True if same object
is not → True if not same
Example:
a = [1,2,3]
b = a
c = [1,2,3]
print(a is b) # True
print(a is c) # False (different memory)
print(a is not c) # True
1. What are Conditional Statements?
Definition: Conditional statements control the flow of a program based on a condition.
They allow different actions depending on whether a condition is True or False.
Conditions are usually checked using comparison and logical operators.
2. Importance of Conditional Statements
Help in decision-making within programs.
Allow programs to react differently depending on inputs.
Make code dynamic and flexible.
3. Types of Conditional Statements
(a) IF Statement
Executes a block of code if a condition is True.
Syntax:
if condition:
# code to execute
Example:
if raining:
print("Take umbrella")
(b) IF-ELSE Statement
Executes one block if condition is True, another if condition is False.
Syntax:
if condition:
# code if true
else:
# code if false
Example:
num = int(input("Enter a number: "))
if num > 0:
print("Positive number")
else:
print("Negative number")
(c) IF-ELIF-ELSE Statement
Used when there are multiple conditions.
Syntax:
if condition1:
# code
elif condition2:
# code
else:
# code
Example:
marks = 75
if marks >= 90:
print("Excellent")
elif marks >= 40:
print("Pass")
else:
print("Fail")
(d) Nested IF Statements
An if statement inside another if/else block.
Syntax:
if condition1:
if condition2:
# nested code
else:
# nested else
else:
# outer else
Example:
num = 12
if num % 2 == 0:
if num > 10:
print("Even and greater than 10")
5. Key Points (Summary)
Conditional statements = decision-making tools in Python.
Types: IF, IF-ELSE, IF-ELIF-ELSE, Nested IF.
Conditions use comparison & logical operators.
Proper indentation is crucial in Python conditionals.
Used widely in program logic, validations, and user input handling.
1. What are Loops?
A loop is a sequence of instructions executed repeatedly as long as a condition is true.
Loops automate repetitive tasks, avoiding writing the same code again and again.
2. Importance of Loops
Simplify programs by reducing code length.
Useful for tasks like generating number series, processing data, or drawing shapes.
Make programs more efficient and productive.
3. The range() Function
Used with loops to generate a sequence of numbers.
Syntax:
range(start, stop, step)
start → starting number (default = 0)
stop → end (excluded)
step → increment (default = 1)
Examples:
range(5) # 0,1,2,3,4
range(2, 9) # 2,3,4,5,6,7,8
range(1, 10, 3) # 1,4,7
4. Types of Loops
(a) For Loop
Used when the number of repetitions is known.
Syntax:
for variable in sequence:
# code
Examples:
# Looping through string
for ch in "PYTHON":
print(ch)
# Multiplication table
n = 5
for i in range(1, 11):
print(n, "x", i, "=", n*i)
✅ Activities: Print even numbers, access characters in a string, display multiples, find sum of numbers, draw shapes using Turtle.
(b) While Loop
Used when the number of repetitions is not fixed (runs until condition is False).
Syntax:
while condition:
# code
Examples:
# Print numbers 0–4
i = 0
while i < 5:
print(i)
i += 1
# Factorial
n = 5
fact = 1
while n > 0:
fact *= n
n -= 1
print("Factorial:", fact)
✅ Activities: Print message multiple times, sum of first 100 numbers, multiplication tables, calculate averages, draw shapes with Turtle.
5. Control Flow Statements in Loops
1. break
Ends the loop immediately when condition is met.
for i in range(6):
if i == 3:
break
print(i) # prints 0,1,2
2. continue
Skips current iteration and moves to the next.
for i in range(6):
if i == 3:
continue
print(i) # skips 3
3. pass
Does nothing – acts as a placeholder.
for i in range(3):
pass # no error, empty block
6. Difference Between For and While Loops
For Loop While Loop
Used when number of iterations is known Used when condition is uncertain
Iterates over sequences (range, list, string, etc.) Repeats until condition becomes False
Example: traversing a list Example: reading input until correct
7. Key Points (Summary)
Loops execute code repeatedly while a condition holds.
range() helps generate number sequences.
For Loop → fixed repetitions.
While Loop → runs until condition is false.
Control Statements:
break → stop loop
continue → skip iteration
pass → placeholder