Obafemi Emmanuel

Python Fundamentals

Published 1 month ago

Python is one of the most popular and beginner-friendly programming languages. It is widely used in web development, data science, artificial intelligence, and automation. In this guide, we will explore the fundamental concepts of Python programming, including variables, data types, operators, control flow, functions, modules, and exception handling.


Variables and Data Types

Variables

A variable in Python is used to store data values. Unlike other programming languages, Python does not require explicit declaration of variable types; it infers the type based on the assigned value.

Example:

name = "John"  # String
age = 25  # Integer
height = 5.9  # Float
is_student = True  # Boolean

Data Types

Python has several built-in data types:

  1. Numeric Types: int, float, complex
  2. Sequence Types: list, tuple, range
  3. Text Type: str
  4. Set Types: set, frozenset
  5. Mapping Type: dict
  6. Boolean Type: bool
  7. Binary Types: bytes, bytearray, memoryview

Example:

number = 10  # int
decimal = 3.14  # float
message = "Hello, Python!"  # str
items = [1, 2, 3, 4]  # list
tuple_example = (10, 20, 30)  # tuple
details = {"name": "Alice", "age": 22}  # dict

Operators in Python

Operators in Python are symbols used to perform operations on variables and values.


Types of Operators:

  1. Arithmetic Operators: +, -, *, /, %, ** (exponentiation), // (floor division)
  2. Comparison Operators: ==, !=, >, <, >=, <=
  3. Logical Operators: and, or, not
  4. Bitwise Operators: &, |, ^, ~, <<, >>
  5. Assignment Operators: =, +=, -=, *=, /=, %=, **=, //=
  6. Identity Operators: is, is not
  7. Membership Operators: in, not in

Example:

a = 10
b = 5
print(a + b)  # Addition
print(a > b and b < 20)  # Logical AND
print(a is not b)  # Identity operator

Control Flow in Python

Control flow structures allow us to make decisions and repeat actions.


if-else Statements

These are used to execute code based on conditions.

Example:

num = 10
if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")

Loops

Loops help in executing a block of code multiple times.

For Loop:

for i in range(5):
    print(i)

While Loop:

x = 0
while x < 5:
    print(x)
    x += 1

Functions and Modules

Functions

Functions in Python are reusable blocks of code that perform a specific task.


Example:

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))

Modules

Modules are Python files that contain reusable functions and variables.

Example (Creating a module):

Save this in mymodule.py:

def add(a, b):
    return a + b

Use the module in another script:

import mymodule
print(mymodule.add(3, 4))

Exception Handling

Exceptions are errors that occur during execution. Python provides a way to handle exceptions using try-except blocks.


Example:

try:
    x = 10 / 0  # This will raise an exception
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Execution completed.")

Conclusion

Understanding these Python fundamentals is crucial for writing efficient and error-free programs. As you progress, you will explore more advanced topics like object-oriented programming, file handling, and database interactions. Happy coding!


Leave a Comment


Choose Colour