Welcome to the world of Python! Whether you’re a student, a professional switching careers, or just curious about coding, Python is one of the best languages to start with. It’s simple, readable, and incredibly powerful.
What is Python?
Python is a high-level, interpreted programming language. That means:
- High-level: You write code in a way that’s close to human language.
- Interpreted: Python runs your code line-by-line, making it easier to debug.
- Versatile: Used in web development, data science, AI, automation, and more.
Python is known for its clean syntax, which makes it ideal for beginners.
Setting Up Python
To start coding:
Install Python from python.org. Once installed, open terminal and check if python has been installed successfully.
python --version
Let’s write our first Python file, say hello.py, which can be done in any text editor like notepad or vim/nano (in linux). Now type the following code in the file and save it:
# hello.py
print("Hello, world!")
Now, open your command line or terminal, navigate to the directory where you saved your file, and run following command to execute the code.
python hello.py
The output should be:
Hello, World!
And just like that, you’ve run your first Python script!
Python Basics
1. Variables and Data Types
Variables are like containers that store data. You can name them anything (following naming rules), and Python automatically figures out the type.
name = "Alice" # String (text)
age = 25 # Integer (whole number)
height = 5.6 # Float (decimal number)
is_student = True # Boolean (True/False)
- Strings are text.
- Integers are whole numbers.
- Floats are decimal numbers.
- Booleans are either
TrueorFalse.
2. Operators
Operators let you perform actions on variables.
# Arithmetic Operators:
x = 10 + 5 # Addition
y = 10 - 3 # Subtraction
z = 4 * 2 # Multiplication
a = 10 / 2 # Division
# Comparison Operators:
# Used to compare values. They return True or False.
print(x > y) # Greater than
print(x == y) # Equal to
# Logical Operators:
# Used to combine conditions.
print(True and False) # False
print(True or False) # True
3. Control Flow
Control flow lets your program make decisions and repeat actions.
if Statement:
if age > 18:
print("You are an adult.")
else:
print("You are a minor.")
elif Statement:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
for Loop:
Used to repeat actions a fixed number of times.
for i in range(5):
print(i)
This prints numbers from 0 to 4.
while Loop:
Repeats as long as a condition is true.
# Keep asking for input until the user enters "stop"
user_input = ""
while user_input != "stop":
user_input = input("Enter a command (type 'stop' to exit): ")
print(f"You entered: {user_input}")
Important Note: In Python a for loop is used for definite iteration over a sequence of items (like a list, string, or range), where the number of iterations is known in advance. A while loop is used for indefinite iteration, repeating a block of code as long as a specified condition remains True, making it ideal when the number of iterations is unknown beforehand.
Data Structures
Python has built-in structures to store collections of data.
1. List – Ordered, mutable
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
2. Tuple – Ordered, immutable
point = (10, 20)
3. Dictionary – Key-value pairs, just like JSON object.
person = {"name": "Alice", "age": 25}
print(person["name"]) # Alice
4. Set – Unordered, unique items
unique_numbers = {1, 2, 3, 2}
print(unique_numbers) # {1, 2, 3}
Here’s a comparative table that clearly explains the differences between Python’s core data structures — List, Tuple, Set, and Dictionary — with detailed descriptions and examples:
Python Data Structures Comparison
| Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Definition | Ordered, mutable collection | Ordered, immutable collection | Unordered, mutable, unique items | Unordered collection of key-value pairs |
| Syntax | fruits = ["apple", "banana"] | point = (10, 20) | nums = {1, 2, 3} | person = {"name": "Alice", "age": 25} |
| Ordering | Maintains order | Maintains order | No guaranteed order | No guaranteed order (Python 3.7+ maintains insertion order) |
| Mutability | ✅ Can be changed | ❌ Cannot be changed | ✅ Can be changed | ✅ Can be changed |
| Duplicates Allowed | ✅ Yes | ✅ Yes | ❌ No | ✅ Keys must be unique; values can repeat |
| Indexing | ✅ Yes (fruits[0]) | ✅ Yes (point[1]) | ❌ No indexing | ✅ Keys used for access (person["name"]) |
| Use Case | Store ordered items like a list | Fixed data like coordinates | Unique items like tags or IDs | Map relationships like name-age pairs |
| Common Methods | .append(), .remove(), .sort() | .count(), .index() | .add(), .remove(), .union() | .keys(), .values(), .items() |
| Performance | Slower than tuple for iteration | Faster for iteration | Fast membership tests | Fast lookups via keys |
Summary
- Use lists when you need an ordered, changeable collection.
- Use tuples when you want to protect data from being modified.
- Use sets when you need to store unique items and perform fast membership checks.
- Use dictionaries when you want to associate keys with values for fast lookups.
Would you like a visual diagram of this comparison or a downloadable Markdown/PDF version for your blog or documentation?
Functions
Functions are reusable blocks of code.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
defdefines a function.returnsends back a result.
Mini Project: Age Calculator
Let’s build a simple python project step by step and run it.
1. Setup a project directory let’s say age-calculator.
mkdir age-calculator
2. Create a main.py file in age-calculator directory and add following code:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
years_to_100 = 100 - age
print(f"Hi {name}, you'll turn 100 in {years_to_100} years!")
3. Execute the code:
D:\Python\age-calculator> python main.py
# Output
Enter your name: Tom
Enter your age: 25
Hi Tom, you'll turn 100 in 75 years!
In the program-
input()gets user input.int()converts input to a number.f""is an f-string for formatting.
That’s it! We have created our first python project.