Welcome to the Python Basics Tutorial! This guide will help you get started with Python programming, covering fundamental concepts and practical examples.
Table of Contents
- Introduction to Python
- Basic Syntax & Structure
- Data Types
- Control Structures
- Functions
- Modules & Packages
- Practice Exercises
Basic Syntax & Structure
Python uses indentation to define code blocks, making it readable and concise.
Example: Hello World
print("Hello, World!") # Output: Hello, World!
Key Features
- No semicolons: Statements end with a newline.
- Whitespace-sensitive: Indentation defines scope.
- Comments: Use
#
for single-line comments.
Data Types
Python has dynamic typing, so variables automatically adapt to their assigned values.
Common Data Types
Type | Description |
---|---|
int |
Integer values (e.g., 42 ) |
float |
Decimal numbers (e.g., 3.14 ) |
str |
Strings (e.g., "Hello" ) |
list |
Ordered collections (e.g., [1, 2, 3] ) |
tuple |
Immutable collections (e.g., (1, 2, 3) ) |
dict |
Key-value pairs (e.g., {"name": "Alice"} ) |
Control Structures
Python supports if-else
, for
, and while
loops for logic control.
Conditional Statements
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
Loops
- For Loop:
for i in range(5): print(i)
- While Loop:
while x < 10: x += 1
Functions
Functions organize code into reusable blocks.
Defining a Function
def greet(name):
return f"Hello, {name}!"
Function Parameters
- Positional Arguments:
greet("Alice")
- Keyword Arguments:
greet(name="Bob")
- Default Values:
def greet(name="Guest"):
Modules & Packages
Use modules to organize related functions and packages to manage larger projects.
Importing Modules
import math
print(math.sqrt(16)) # Output: 4.0
Creating a Package
- Create a directory with an
__init__.py
file. - Add modules inside the directory.
- Use
import package.module
to access them.
Practice Exercises
Try these exercises to reinforce your knowledge:
- Write a program to calculate the sum of two numbers.
- Create a list of fruits and loop through it to print each item.
- Define a function that checks if a number is even or odd.
For more advanced topics, check out our Python Advanced Features guide! 🚀