Python Programming Basics
1/20/2024• 3 min read
Introduction to Python programming language fundamentals
programmingpythonbasicssyntax
Python Programming Basics
Python is a high-level, interpreted programming language known for its simplicity and readability.
Introduction
Python was created by Guido van Rossum and first released in 1991. It emphasizes code readability and allows programmers to express concepts in fewer lines of code.
Key Features
- Simple and Easy to Learn: Clean syntax, easy to read
- Interpreted Language: No compilation needed
- Dynamically Typed: No need to declare variable types
- High-Level Language: Abstracts low-level details
- Extensive Libraries: Rich standard library and third-party packages
Basic Syntax
Variables and Data Types
# Numbers
x = 10 # Integer
y = 3.14 # Float
z = 5 + 3j # Complex
# Strings
name = "Python"
message = 'Hello, World!'
# Boolean
is_active = True
is_complete = False
# Lists
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
# Dictionaries
person = {"name": "John", "age": 30}
Control Flow
# If-else statements
if x > 10:
print("Greater than 10")
elif x == 10:
print("Equal to 10")
else:
print("Less than 10")
# Loops
for i in range(5):
print(i)
while x > 0:
print(x)
x -= 1
Functions
def greet(name):
return f"Hello, {name}!"
# Lambda functions
square = lambda x: x ** 2
Classes and Objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"I'm {self.name}, {self.age} years old"
person = Person("Alice", 25)
print(person.introduce())
Python Collections
Lists
my_list = [1, 2, 3]
my_list.append(4)
my_list.insert(0, 0)
my_list.remove(2)
Tuples
Immutable sequences: (1, 2, 3)
Sets
Unordered collections of unique elements: {1, 2, 3}
Dictionaries
Key-value pairs: {"key": "value"}
File Handling
# Reading files
with open("file.txt", "r") as f:
content = f.read()
# Writing files
with open("file.txt", "w") as f:
f.write("Hello, World!")
Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("This always executes")
List Comprehensions
# Traditional way
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension
squares = [x**2 for x in range(10)]
Popular Python Libraries
- NumPy: Numerical computing
- Pandas: Data manipulation and analysis
- Matplotlib: Data visualization
- Django/Flask: Web development
- Requests: HTTP library
- Scikit-learn: Machine learning