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