Introduction
Learning to code can seem intimidating when you are starting from scratch. Programming languages, syntax, variables, and errors may initially feel confusing. However, Python makes the learning process easier because of its simple and readable syntax.
Python is a high-level, general-purpose programming language used in web development, data science, artificial intelligence, automation, and software development. Its readability makes it a suitable language for beginners while remaining powerful enough for professional developers.
This guide introduces the fundamentals of Python, from installing the necessary tools to writing and running practical programs. By the end, you should understand the basic concepts and have an idea of how to start building your own projects.
1. Why Learn Python?
Python is one of the most popular programming languages because it is versatile and relatively easy to learn.
Some reasons to learn Python include:
- Beginner-friendly syntax: Python code is generally easy to read and understand.
- Versatility: It can be used in data analysis, web development, automation, and artificial intelligence.
- Large community: Beginners can find tutorials, documentation, and support online.
- Libraries and frameworks: Python provides tools that simplify complex tasks.
- Career opportunities: Python is useful in fields such as software engineering, data science, and machine learning.
Python is therefore a valuable starting point for anyone interested in technology.
2. Installing Python on Windows
Before writing Python programs, you need to install Python on your computer.
Follow these steps:
- Visit the official Python website: https://www.python.org/
- Navigate to the Downloads section.
- Download the Windows installer.
- Run the installer and select the option to add Python to PATH if available.
- Complete the installation.
To confirm that Python is installed, open Command Prompt or Git Bash and type:
python --version
If Python is installed correctly, the terminal should display the installed version.
3. Setting Up Visual Studio Code
Visual Studio Code (VS Code) is a code editor that provides a convenient environment for writing and running Python programs.
To set it up:
- Download VS Code from https://code.visualstudio.com/.
- Install and open the application.
- Open the Extensions panel.
- Search for the Python extension by Microsoft and install it.
- Create a folder for your Python projects.
- Open that folder in VS Code.
You can now create Python files with the .py extension.
For example, create a file named hello.py.
4. Writing and Running Your First Python Program
Your first program can be as simple as displaying a message.
print("Hello, World!")
The print() function displays information in the terminal.
To run the program in VS Code:
- Open the Python file.
- Open the integrated terminal.
- Navigate to the folder containing your file if necessary.
- Type:
python hello.py
The terminal should display:
Hello, World!
Congratulations! You have written and executed your first Python program.
5. Understanding Variables and Data Types
Variables are names used to store information that a program can access and manipulate.
For example:
student_name = "Amina"
age = 20
fee_balance = 15000.50
has_paid = False
print(student_name)
print(age)
print(fee_balance)
print(has_paid)
Python supports several basic data types:
-
String (
str): Text, such as"Amina". -
Integer (
int): Whole numbers, such as20. -
Float (
float): Decimal numbers, such as15000.50. -
Boolean (
bool): EitherTrueorFalse.
Variables make it possible to store and reuse information without repeatedly typing the same values.
6. Working with Input and Output
Programs become more interactive when users can provide information.
Python uses the input() function to receive information from a user.
Example:
name = input("What is your name? ")
print(f"Welcome, {name}!")
The program asks for the user's name and then displays a personalized greeting.
An important detail is that input() returns a string. If you want to perform calculations using a number entered by the user, you may need to convert it.
For example:
age = int(input("Enter your age: "))
print(f"Next year, you will be {age + 1}.")
Here, int() converts the input into a whole number.
7. Understanding Python Operators
Operators are symbols used to perform calculations and comparisons.
Common arithmetic operators include:
| Operator | Meaning | Example |
|---|---|---|
+ |
Addition | 10 + 5 |
- |
Subtraction | 10 - 5 |
* |
Multiplication | 10 * 5 |
/ |
Division | 10 / 5 |
// |
Floor division | 11 // 5 |
% |
Modulus (remainder) | 11 % 5 |
** |
Exponentiation | 2 ** 3 |
For example:
price = 150
quantity = 3
total = price * quantity
print(f"Total cost: KES {total}")
Output:
Total cost: KES 450
Operators are useful when building calculators, billing systems and other applications that involve numerical operations.
8. Working with Strings
A string is a sequence of characters enclosed in quotation marks.
Python provides several built-in string methods that help manipulate text.
name = " amina otieno "
print(name.strip())
print(name.title())
print(name.upper())
print(name.lower())
Some useful string methods include:
-
strip(): Removes whitespace from the beginning and end. -
title(): Capitalises the first letter of each word. -
upper(): Converts text to uppercase. -
lower(): Converts text to lowercase. -
replace(): Replaces part of a string with another value. -
split(): Divides a string into a list. -
join(): Combines strings using a specified separator.
For example:
sentence = "Python is fun and Python is powerful"
print(sentence.count("Python"))
Output:
2
String methods are particularly useful when cleaning names, processing messages and working with text data.
9. Making Decisions with Conditional Statements
Conditional statements allow a program to make decisions based on whether a condition is true or false.
Python uses if, elif ', andelse`.
Example:
`python
balance = 500
if balance >= 1000:
print("You can make the purchase.")
elif balance >= 500:
print("You have just enough.")
else:
print("Insufficient balance.")
`
The program checks the conditions in order and executes the matching block.
Indentation is important in Python because it determines which statements belong to a particular condition.
10. Building Practical Python Projects
The best way to understand programming is to apply what you have learned.
Project 1: A Simple Vegetable Shop Billing System
This program calculates a customer's bill based on the vegetable selected and the quantity purchased.
`python
sukuma = 20
tomatoes = 10
onions = 15
item = input("Which vegetable would you like? ").lower()
quantity = int(input("How many do you want? "))
if item == "sukuma":
total = sukuma * quantity
elif item == "tomatoes":
total = tomatoes * quantity
elif item == "onions":
total = onions * quantity
else:
total = 0
print("Sorry, that vegetable is unavailable.")
if total > 0:
print(f"Your total bill is KES {total}")
`
This project combines variables, user input, arithmetic operators and conditional statements.
Project 2: A Simple M-Pesa Message Parser
Python can also be used to extract information from text messages.
Consider a simplified M-Pesa confirmation message:
text
QK7H2X9 Confirmed. Ksh1,250.00 sent to JOHN KAMAU 0712345678 on 2/12/26 at 7:15 PM.
The split() method can divide the message into individual parts.
`python
message = "QK7H2X9 Confirmed. Ksh1,250.00 sent to JOHN KAMAU 0712345678 on 2/12/26 at 7:15 PM."
parts = message.split()
transaction_code = parts[0]
amount = parts[2]
print("Transaction code:", transaction_code)
print("Amount:", amount)
`
This is a simplified demonstration of text parsing. A real M-Pesa parser would need more robust handling of different message formats, missing information and validation.
11. Common Beginner Mistakes
Every beginner encounters errors. Understanding common mistakes makes troubleshooting easier.
1. Indentation errors
Python uses indentation to organise code blocks. Inconsistent indentation can cause errors.
2. Incorrect variable names
Python is case-sensitive. For example, name and Name are treated as different variables.
3. Forgetting quotation marks
Text values must be enclosed in quotation marks.
4. Incorrect data types
Trying to add a number to a string without converting the data can cause a TypeError.
5. Running the wrong file
Always check that you are running the correct Python file from the correct project folder.
When an error occurs, read the error message carefully. It often identifies the type of problem and the line where Python encountered it.
Conclusion
Learning Python is a gradual process that requires practice, patience, and curiosity. Understanding variables, data types, input and output, operators, strings and conditional statements provides a strong foundation for more advanced programming.
Start with small programs, experiment with different examples, and gradually build projects that solve practical problems.
You can explore the code examples from this guide in my public GitHub repository:
GitHub: https://github.com/4688-tori/python-technical-assignment
Remember, you do not need to understand everything at once. The most important step is to keep writing, testing, and improving your code.
Happy coding!
Top comments (0)