Zum Inhalt springen

English:Programming with Python

Aus MOOCsWiki Staging
Version vom 1. September 2026, 07:10 Uhr von Glanz (Diskussion | Beiträge) (aiMOOC über GPT aiMOOC Action erstellt)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
aiMOOC-Siegel

Programming with Python



Introduction

Programming with Python is a university-level aiMOOC about computational thinking, software construction, and problem solving with Python. You will learn to design algorithms, express them in readable Python, select suitable data structures, build reusable functions, work with files and modules, test programs, and justify design decisions.

Python is used in education, science, data analysis, automation, web development, and artificial intelligence. Its readable syntax makes it well suited to learning core ideas such as state, control flow, abstraction, data structures, modularity, and testing.

Python was created by Guido van Rossum and is developed by an international community. Language changes are discussed through Python Enhancement Proposals.


Learning Goals

By the end of the course, you should be able to write and explain Python programs, use conditionals and loops, define functions, work with lists, tuples, sets, and dictionaries, organize code into modules, read and write files, use classes when appropriate, create automated tests, and improve code for clarity and maintainability.


Working Environment and First Programs

You can use Python interactively, run scripts from a terminal, or work in an integrated development environment. Jupyter notebooks are common in universities because they combine executable code, explanation, equations, and output in one document.

course = "Programming with Python"
students = 24
message = f"{course}: {students} students"
print(message)

A variable name refers to a Python object. Assignment binds a name to a value. Common built-in types include int, float, bool, and str.


Expressions and Decisions

Expressions produce values. Arithmetic operators include +, -, *, /, //, and %. The built-in pow function performs exponentiation. Comparison operators produce Boolean values.

temperature = 21.5
is_warm = temperature >= 20.0
print(is_warm)

An if statement selects a branch according to a condition.

score = 78

if score >= 90:
    grade = "excellent"
elif score >= 60:
    grade = "pass"
else:
    grade = "revise"

print(grade)


Loops and Iteration

A for loop visits items from an iterable. A while loop repeats while a condition remains true. Use the construct that makes the stopping rule easiest to understand.

values = [12, 7, 19, 4]
total = 0

for value in values:
    total += value

print(total)

Turtle graphics can make iteration visible because repeated commands create geometric patterns.


Functions and Abstraction

A function groups behavior behind a name and a clear interface. Parameters describe input to the function, while a return value communicates a result to the caller.

def mean(values):
    return sum(values) / len(values)

sample = [4.0, 7.5, 9.5]
print(mean(sample))

Good functions usually have one coherent responsibility. Their names should communicate intent, and their interfaces should make them easy to test and reuse.


Scope and Arguments

Names created inside a function are normally local to that function. Arguments can be passed positionally or by keyword. Default parameter values can make interfaces convenient when the meaning remains clear.

def format_measurement(value, unit="m", precision=2):
    return f"{value:.{precision}f} {unit}"

print(format_measurement(3.14159))
print(format_measurement(3.14159, unit="cm", precision=1))


Data Structures

Choosing a data structure is a design decision. A list is an ordered mutable sequence. A tuple is an ordered sequence often used for fixed groups of values. A set stores unique elements. A dictionary maps keys to values.

student = {
    "name": "Amina",
    "program": "Computer Science",
    "credits": 72
}

modules = ["Algorithms", "Databases", "Statistics"]
skills = {"Python", "Git", "Testing"}

student["credits"] += 6
modules.append("Software Engineering")
skills.add("Documentation")

Comprehensions are useful for concise transformations when the result remains readable.

squares = [pow(n, 2) for n in range(10)]
even_squares = [value for value in squares if value % 2 == 0]


Robust Programs and Exceptions

Programs should anticipate unusual input and external conditions. Python uses exceptions to signal that normal execution cannot continue in the expected way. You should validate assumptions, keep recovery logic focused, and avoid hiding unexpected situations.

A simple input check can prevent unsuitable values from reaching later calculations:

def is_positive_integer(text):
    return text.isdigit() and int(text) > 0

print(is_positive_integer("12"))
print(is_positive_integer("-4"))

In larger programs, targeted try and except blocks can be used around operations that may fail for known reasons. The goal is to respond deliberately rather than ignore problems.


Files and Structured Data

Programs often exchange information through files. A context manager created with with ensures that a file is closed after use.

from pathlib import Path

path = Path("results.txt")

with path.open("w", encoding="utf-8") as file:
    file.write("experiment,score\n")
    file.write("alpha,0.82\n")

Formats such as CSV and JSON are useful when data needs to be exchanged with other tools.


Modules, Packages, and Environments

A module is a Python file that defines reusable code. A package organizes related modules. Imports let you reuse tested components instead of duplicating them.

from statistics import mean, median

values = [2, 3, 5, 8, 13]
print(mean(values))
print(median(values))

Third-party packages extend Python. For university projects, use an isolated virtual environment and record project dependencies so that others can reproduce the setup.

python -m venv .venv
python -m pip install package_name


Object-Oriented Programming

A class defines a type, and an instance is a concrete object of that type. Attributes hold state, while methods implement behavior.

class Counter:
    def __init__(self, start=0):
        self.value = start

    def increment(self, step=1):
        self.value += step

counter = Counter(10)
counter.increment(3)
print(counter.value)

Classes are useful when a problem contains entities with persistent state and related operations. They are not automatically better than functions. Choose the simplest design that models the problem clearly.


Testing, Debugging, and Code Quality

Automated tests give evidence that a program behaves as intended for selected cases. Unit tests focus on small units such as functions or methods. Good tests include normal cases and boundary cases.

import unittest

def clamp(value, lower, upper):
    return max(lower, min(value, upper))

class ClampTests(unittest.TestCase):
    def test_inside_range(self):
        self.assertEqual(clamp(5, 0, 10), 5)

    def test_above_range(self):
        self.assertEqual(clamp(15, 0, 10), 10)

Debugging is a process of forming and testing hypotheses about why observed behavior differs from intended behavior. Useful techniques include reproducing a problem with a small example, inspecting values, stepping through code, and adding a regression test after a fix.

PEP 8 provides widely used style guidance for Python code. Meaningful names, focused functions, useful documentation, and consistent formatting improve maintainability.


Python for Data and Scientific Work

Python has a large ecosystem for scientific and data work. Libraries such as NumPy, pandas, Matplotlib, and SciPy support numerical arrays, tabular data, visualization, and scientific methods.

When you visualize data, select a chart type that matches the question. A line plot can show change across an ordered dimension, a scatter plot can show relationships between numerical variables, and a histogram can show a distribution.


Performance and Computational Thinking

Correctness comes before optimization. When performance matters, measure where time or memory is being spent. Algorithm and data-structure choices often matter more than small syntax changes.

Generators and iterators can process values one at a time instead of constructing every result in memory.

def positive_measurements(values):
    for value in values:
        if value > 0:
            yield value

for measurement in positive_measurements([3, -1, 4, 0, 5]):
    print(measurement)


Version Control and Responsible Practice

Use version control such as Git to record changes, collaborate, and review contributions. Write commit messages that explain intent and keep credentials out of repositories.

Responsible programming includes respecting software licenses, protecting sensitive data, documenting limitations, checking outputs, and evaluating third-party dependencies before relying on them.


Interactive Tasks


Quiz: Test Your Knowledge

Which built-in data structure maps unique keys to values? (Dictionary) (!List) (!Tuple) (!String)




What is the main purpose of a function return statement? (To send a result back to the caller) (!To import a package) (!To start a class definition) (!To install software)




Which statement selects between alternative branches? (if) (!import) (!yield) (!pass)




What does a for loop normally do? (Iterates over items from an iterable) (!Creates a package) (!Defines a class automatically) (!Installs a dependency)




Why is a virtual environment useful? (It isolates project dependencies) (!It encrypts source code) (!It replaces all tests) (!It creates documentation automatically)




Which structure is designed to store unique elements? (Set) (!String) (!Float) (!Boolean)




What does a unit test primarily examine? (A small unit of program behavior) (!Only the graphical interface) (!Only the operating system) (!Only network speed)




What is an instance in object-oriented Python? (A concrete object created from a class) (!A package index) (!A Git branch) (!A source file extension)




What should you usually do before optimizing code for speed? (Measure where the real bottleneck is) (!Remove tests) (!Replace every function with a class) (!Rewrite every loop recursively)




Which practice improves maintainability? (Using clear names and focused functions) (!Duplicating code across files) (!Hiding project dependencies) (!Avoiding documentation)





Memory Game

List Mutable ordered sequence
Tuple Ordered sequence commonly used for fixed groups
Dictionary Mapping from keys to values
Set Collection of unique elements
Function Reusable unit of behavior with an interface
Class Definition used to create objects





Drag and Drop

Match the correct terms. Topic
Conditional branching if statement
Iteration over items for loop
Reusable behavior function
Key-value storage dictionary
Automated verification unit test




...


Crossword Puzzle

Iteration What process repeats operations over successive items?
Dictionary Which mapping structure stores values under keys?
Function What reusable block of behavior can receive arguments?
Inheritance What mechanism derives one class from another?
Generator What construct can yield values lazily one at a time?
Debugging What process investigates incorrect program behavior?





LearningApps


Cloze Text

Complete the text.
Python uses

to mark suites of statements in blocks. A function sends a result to its caller with

. A mapping from keys to values is called a

. A loop processes a sequence of items through

. Project dependencies can be isolated inside a

. Automated checks of small program units are called

. A class is used to create concrete objects called

.




Open-Ended Tasks


Easy

  1. Python Code Reading: Choose a short Python program, annotate each line in plain English, and explain how data changes while the program runs.
  2. Small Automation Script: Write a script that automates a simple study task such as converting units or summarizing a list of values.
  3. Algorithm Poster: Create an image or poster that compares sequence, selection, and iteration and add one Python example for each.
  4. Peer Interview on Programming: Interview another student about one programming difficulty and write a short reflection on possible strategies.


Standard

  1. Data Analysis Mini Project: Obtain a small open dataset, clean it with Python, compute meaningful summaries, create one visualization, and explain the result.
  2. Testing Laboratory: Design a function, create tests for normal and boundary cases, then alter the function and observe which tests detect the change.
  3. Python Tutorial Video: Produce a short instructional video that teaches one Python concept through a worked example.
  4. Code Review Workshop: Exchange a program with a peer, review naming, decomposition, documentation, and tests, then revise your own program.


Advanced

  1. Reproducible Research Workflow: Build a small research workflow that reads data, performs an analysis, creates a figure, records dependencies, and can be rerun from a clean environment.
  2. Software Architecture Comparison: Solve the same problem once with functions and once with classes, then compare extensibility, clarity, and testing effort.
  3. Performance Experiment: Form a hypothesis about two data structures or algorithms, design a controlled timing experiment, visualize the measurements, and discuss limitations.
  4. Open Source Field Study: Visit a public Python repository, study its issues, tests, documentation, and contribution guide, then write an evidence-based report on collaboration practices.



Learning Assessment

  1. Program Design Assessment: Decompose a real-world problem into functions, choose suitable data structures, implement the solution, and justify your design decisions.
  2. Debugging Assessment: Analyze a faulty program, reproduce the unwanted behavior, repair it, and add a test that demonstrates the intended result.
  3. Data Structure Transfer: Compare two possible representations for the same dataset and explain how each choice changes readability, operations, and performance.
  4. Reproducibility Assessment: Package a small project with clear setup instructions and isolated dependencies so that another student can run it from a clean environment.
  5. Object Model Assessment: Design a class-based model for a small domain, identify important state and methods, and explain where composition is preferable to inheritance.
  6. Critical Code Review: Review an unfamiliar Python program for correctness, test quality, style, documentation, and maintainability, then prioritize improvements.




Evidence of Learning

Evidence of learning includes working Python programs, accurate explanations of control flow and data structures, functions with clear interfaces, appropriate use of modules and files, automated tests, reproducible environments, readable code, reasoned design decisions, visual or written communication of results, and transfer of programming concepts to unfamiliar problems.

Strong evidence also includes your ability to explain trade-offs. You should be able to justify why a data structure, algorithm, interface, testing strategy, or object model was chosen and identify limitations in your solution.




OERs on the Topic

The official Python tutorial and standard-library documentation provide authoritative reference material. The Python Packaging User Guide explains virtual environments and packaging. MIT OpenCourseWare and Harvard CS50P provide university-level programming instruction. PEP 8 offers widely used style guidance.



Linked Learning Areas

Programming with Python connects with Computer science, Software engineering, Algorithms, Data science, Artificial intelligence, Scientific computing, Statistics, Cybersecurity, Web development, Automation, and Reproducible research.


aiMOOC Projects

MOOCwiki · Deutsch

Nach dem Lernen ist vor dem Lernen

Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.

Zur MOOCwiki-Hauptseite
Inhalte werden geladen ...

Mediathek wird aus dem Wiki geladen ...