xbe.at

Python / Core language

Fundamental Python Concepts

3 min read, 15 sections

Contents
  1. Introduction to Python
  2. Variables and Data Types
  3. Operators and Expressions
  4. Control Flow (Conditionals)
  5. Control Flow (Loops)
  6. Functions
  7. Lists
  8. Tuples
  9. Dictionaries
  10. File Operations
  11. Modules and Packages
  12. Exception Handling
  13. Object-Oriented Programming (OOP)
  14. Next Steps
  15. Meta

Introduction to Python

Welcome to Python Python is a versatile, high-level programming language known for its simplicity and readability. It's widely used for web development, data analysis, automation, and more.

print("Hello, World!")

Variables and Data Types

Storing and Manipulating Data Python supports various data types, such as integers, floats, strings, and booleans. Variables are used to store and manipulate data.

name = "Alice"  # String
age = 25  # Integer
height = 1.68  # Float
is_student = True  # Boolean

Operators and Expressions

Performing Calculations and Operations Python provides a range of operators (arithmetic, assignment, comparison, logical, etc.) to perform calculations and manipulate data.

x = 10
y = 3
sum = x + y  # Addition: 13
diff = x - y  # Subtraction: 7
prod = x * y  # Multiplication: 30
div = x / y  # Division: 3.3333333333333335
mod = x % y  # Modulus: 1

Control Flow (Conditionals)

Making Decisions with Conditionals Conditional statements allow your program to make decisions and execute different code blocks based on certain conditions.

age = 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Control Flow (Loops)

Repeating Tasks with Loops Loops enable you to execute a block of code repeatedly, either a specific number of times (for loop) or until a certain condition is met (while loop).

# For loop
for i in range(5):
    print(i)  # Prints 0, 1, 2, 3, 4

# While loop
count = 0
while count < 5:
    print(count)
    count += 1  # Prints 0, 1, 2, 3, 4

Functions

Modularizing Code with Functions Functions allow you to encapsulate reusable code blocks and enhance code organization and readability.

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

greet("Alice")  # Output: Hello, Alice!

Lists

Working with Lists Lists are ordered collections of items, which can be of different data types. They are mutable, meaning you can modify their contents.

fruits = ["apple", "banana", "orange"]
print(fruits[0])  # Output: apple
fruits.append("grape")
print(fruits)  # Output: ['apple', 'banana', 'orange', 'grape']

Tuples

Working with Tuples Tuples are ordered collections of items, similar to lists, but they are immutable, meaning their contents cannot be modified after creation.

point = (3, 4)
print(point[0])  # Output: 3
# point[0] = 5  # This will raise an error (tuples are immutable)

Dictionaries

Working with Dictionaries Dictionaries are unordered collections of key-value pairs, where keys must be unique and immutable (e.g., strings, numbers).

person = {"name": "Alice", "age": 25, "city": "New York"}
print(person["name"])  # Output: Alice
person["age"] = 26
print(person)  # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}

File Operations

Reading and Writing Files Python provides built-in functions to read from and write to files, which is essential for working with data and persisting information.

# Writing to a file
with open("data.txt", "w") as file:
    file.write("Hello, World!")

# Reading from a file
with open("data.txt", "r") as file:
    content = file.read()
    print(content)  # Output: Hello, World!

Modules and Packages

Reusing and Organizing Code Modules and packages allow you to organize and reuse code across different parts of your application, promoting code modularization and maintainability.

# Import a module
import math

result = math.sqrt(16)  # Using a function from the math module
print(result)  # Output: 4.0

Exception Handling

Handling Errors Gracefully Exception handling allows you to catch and handle errors that occur during program execution, preventing crashes and ensuring graceful error handling.

try:
    result = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
else:
    print(result)

Object-Oriented Programming (OOP)

Introducing Object-Oriented Programming OOP is a programming paradigm that revolves around the concept of objects, which encapsulate data (attributes) and behavior (methods).

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        print(f"{self.name} says: Woof!")

my_dog = Dog("Buddy", "Labrador")
my_dog.bark()  # Output: Buddy says: Woof!

Next Steps

Continuing Your Python Journey This slideshow covered fundamental topics in Python, but there's much more to explore! Consider learning about libraries and frameworks, web development, data analysis, and more.

print("Keep learning and practicing Python!")

Meta

Unleash Your Coding Potential with Python Fundamentals

Embark on an exciting journey through the world of Python programming with our comprehensive slideshow. Designed for beginners and intermediate learners, this educational resource unveils the essential building blocks of this versatile language. Explore variables, data types, control flow, functions, and more, through concise explanations and actionable code examples. Unlock the power of Python and lay the foundation for mastering this in-demand skill. #PythonFundamentals #CodeEducation #LearnToCode #ProgrammingBasics #TechKnowledge

Hashtags: #PythonFundamentals #CodeEducation #LearnToCode #ProgrammingBasics #TechKnowledge

More in Core language

  1. Introduction to Python Utility Function2 min

    1. Single-purpose 2. Pure (no side effects) 3. Well-documented 4. Easily testable

  2. Factorial Calculator in Python5 min

    A factorial is the product of all positive integers less than or equal to a given number. It's denoted by an exclamation mark (!). For example, 5! = 5 × 4 ×...

  3. Leveraging Itertools for Efficient Python Iteration7 min

    The itertools module in Python provides a collection of fast, memory-efficient tools for creating iterators for efficient looping. It offers a set of...

  4. Explaining Generators in Python with Fibonacci7 min

    A generator in Python is a special type of function that allows for lazy evaluation of values, creating elements only when needed. Unlike regular functions...

  5. Leveraging Python Descriptors for Robust Attribute Management12 min

    Descriptors are a powerful feature in Python that provide a way to customize attribute access in classes. They enable fine-grained control over how...

  6. Executing Python Projects as Directories3 min

    Python projects are typically run by invoking a specific script file. However, there's a more elegant and user-friendly approach: executing the entire...