Python Basics
Python is a powerful, high-level, and easy-to-learn programming language that is widely used in web development, data science, automation, artificial intelligence, and more. Designed with readability in mind, Python uses simple syntax similar to English, making it ideal for beginners and professionals alike.
1. Getting Started
To run Python, you need to install it from python.org, or use an online IDE like Replit, Google Colab, or Jupyter Notebooks.
print("Hello, World!")This line uses the built-in print() function to output text to the screen.
2. Variables and Data Types
Variables store data. You don't need to declare the type explicitly in Python:
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
Common data types include:
int– integers (e.g., 1, 100)float– decimals (e.g., 3.14)str– strings (e.g., "Hello")bool– Boolean values (TrueorFalse)
3. Operators
Python supports arithmetic and logical operations:
# Arithmetic
x = 10 + 5 # 15
y = 20 - 8 # 12
z = 4 * 3 # 12
w = 15 / 3 # 5.0
# Comparison
a == b, a != b, a > b, a < b
# Logical
and, or, not
4. Control Flow: if, elif, else
Python uses indentation (usually 4 spaces) to define blocks of code:
if age > 18:
print("Adult")
elif age == 18:
print("Just turned adult")
else:
print("Minor")
5. Loops: for and while
Use loops to repeat actions:
# For loop
for i in range(5):
print(i) # 0 to 4
# While loop
count = 0
while count < 5:
print(count)
count += 1
6. Functions
Functions allow code reuse and organization:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
7. Data Structures
Python has built-in structures for storing collections:
- List – ordered, mutable:
fruits = ["apple", "banana"] - Tuple – ordered, immutable:
coords = (10, 20) - Set – unordered, unique:
colors = {"red", "blue"} - Dict – key-value pairs:
person = {"name": "Alice", "age": 25}
8. Comments and Documentation
Use # for single-line comments and triple quotes """ for documentation:
# This is a comment
"""This function greets the user"""
9. Importing Modules
Modules let you use additional functionality:
import math
print(math.sqrt(16)) # 4.0
Conclusion
Python's simplicity, combined with its powerful libraries and community support, makes it one of the best languages to start programming. Once you master the basics, you can explore areas like web development with Flask/Django, data analysis with Pandas, or automation with scripts.
