Skip to content

Python Programming

100 companion flashcards · AI-assisted study content · Open the deck →

Welcome to this Python Programming flashcard deck! These cards are designed to help you build a strong foundation in Python, starting from the very basics like what Python is and who created it, all the way through core concepts such as variables, data types, operators, and how to interact with users through functions like print() and input(). Whether you are completely new to coding or brushing up on fundamentals, this deck walks you through the building blocks step by step.

Python is one of the most beginner-friendly programming languages, known for its readable syntax and versatility. The cards in this set focus on foundational knowledge rather than advanced topics, making them ideal for students, self-learners, or anyone preparing for an introductory programming course or interview. If you are just starting your coding journey, working through these questions will give you the confidence to write your first scripts and understand what is happening under the hood.

To get the most out of this deck, try to study in short, focused sessions rather than cramming everything at once. Spacing your reviews over several days helps move information from short-term to long-term memory, which is especially helpful for remembering syntax rules and the differences between data types. As you go through each card, try to type out a small example in a Python editor or the REPL to reinforce what you have learned, since hands-on practice is one of the best ways to truly internalize programming concepts.

Introduction to Python

Python is a high-level, interpreted programming language renowned for its readability and simplicity. Created by Guido van Rossum with the first version released in 1991, Python was named after the British comedy series Monty Python. The language supports multiple programming paradigms, including procedural, object-oriented, and functional programming, making it versatile for many kinds of projects.

Among Python's key features are dynamic typing, automatic memory management, an extensive standard library, and cross-platform compatibility. The language emphasizes code readability through significant whitespace, meaning indentation is part of the syntax itself rather than just a stylistic choice. This design encourages developers to write clean, well-structured code.

To run a Python script, save your code in a file with the .py extension and execute python filename.py in the terminal. If Python 2 is also installed, you may need to use python3 instead. For interactive experimentation, Python provides a REPL, which stands for Read-Eval-Print Loop. It can be launched by typing python in the terminal, where it reads each line of input, evaluates it, prints the result, and waits for the next line, making it an excellent tool for testing small snippets of code.

Variables, Types, and Operators

Variables in Python are names that reference objects storing data. They are created automatically on first assignment, as in x = 5, and because Python uses dynamic typing, the type of a variable is determined at runtime rather than at compile time. This means a single variable can hold different types sequentially; for instance, you could write x = 5 followed by x = 'hello' without any type errors.

The basic immutable data types in Python include int for integers, float for floating-point numbers, str for strings, and bool for True and False values. Mutable types include lists and dictionaries. A special value called None represents the absence of a value and is a singleton object often used as a default return for functions without explicit return statements. When converting between types, you can use built-in functions like int(), float(), str(), and bool(); for example, int('42') converts the string '42' into the integer 42.

Python provides a rich set of operators for working with values. Arithmetic operators include +, -, *, /, // (floor division), % (modulo), and ** (exponentiation). Comparison operators such as ==, !=, >, <, >=, and <= return a boolean value: True or False. Logical operators include and (true when both operands are true), or (true when either operand is true), and not (negation), and they short-circuit evaluate, meaning they stop as soon as the result is determined.

For basic input and output, the print() function outputs objects to standard output, converting them to strings and using sep=' ' between arguments and end='\n' at the end by default. The input(prompt) function reads a line from standard input, strips the newline, and returns it as a string. To work with numeric input, you typically need to wrap input() with int() or float() to convert the result.

Control Flow

Python's control flow begins with the if statement, written as if condition: followed by an indented block. The condition is evaluated for truthiness; in Python, non-empty and non-zero values are considered truthy, while empty collections, zero, and None are falsy. To chain additional conditions, you can use elif (else-if) clauses, and a final else clause executes when no prior conditions match.

Loops allow you to repeat actions. The while loop, written as while condition:, repeatedly executes its indented block as long as the condition remains truthy. Care must be taken to avoid infinite loops by ensuring the condition eventually becomes false. The for loop, written as for item in iterable:, iterates over sequences such as lists, strings, or the numbers produced by range(). The expression range(n) generates the sequence from 0 to n-1.

Three special statements give you fine-grained control within loops. The break statement exits the loop entirely, while continue skips the rest of the current iteration and proceeds to the next one. The pass statement is a no-op placeholder, useful when syntax requires a statement but no action is needed, such as defining an empty class or function body.

Functions

Functions are defined using the def keyword, followed by the function name, parameters in parentheses, and a colon, as in def function_name(parameters):. The indented body contains the function's logic, and you call the function by writing its name followed by arguments, like function_name(args). It is important to distinguish between parameters, which are the variables listed in the function definition, and arguments, which are the actual values passed when calling the function. Keyword arguments can be passed using the name=value syntax.

The return statement, written as return value, exits the function and sends a value back to the caller. Without an explicit return, a function automatically returns None. Default parameters let you assign a default value to a parameter so the caller can omit it: def func(param=default):. This is helpful when a parameter has a common value most callers will want.

For more flexible function signatures, Python supports *args and **kwargs. The *args syntax packs extra positional arguments into a tuple, while **kwargs packs extra keyword arguments into a dictionary. These constructs allow a function to accept any number of arguments without specifying them all in advance.

Data Structures

Lists are mutable, ordered sequences defined with square brackets, such as mylist = [1, 2, 3]. You access elements by index using mylist[0] for the first element, and negative indices count from the end. Common list methods include append(x) to add an item at the end, pop() to remove and return the last item, insert(i, x) to insert at a specific position, remove(x) to remove the first occurrence of a value, sort() to sort in place, and reverse() to reverse the order.

Tuples are immutable sequences created with parentheses or simply by separating values with commas, like t = (1, 2, 3). Because they cannot be changed after creation, tuples are useful for representing fixed collections of related data, such as coordinates or RGB color values. Dictionaries map keys to values using the syntax d = {'key': 'value'}. Keys must be immutable types, and you access values with d['key']. Sets are unordered collections of unique elements defined with curly braces, like s = {1, 2}, and they support operations such as add(), remove(), union, and intersection.

Strings are immutable sequences of characters, and you can extract substrings using slicing. The expression s[1:3] returns a substring from index 1 up to but not including index 3, and you can provide a step with s[::2] to skip every other character. Common string methods include upper(), lower(), strip() for removing whitespace, split() for breaking into a list, join() for combining an iterable into a string, find() for locating a substring, and replace() for substituting characters. F-strings, introduced in Python 3.6, offer a concise way to interpolate values into strings: f'Hello {name}' substitutes the value of the variable name directly into the string.

Object-Oriented Programming

Python supports object-oriented programming through classes. You define a class with the class keyword, like class MyClass:, followed by indented methods. Instances are created by calling the class as if it were a function: obj = MyClass(). The special __init__ method, defined as def __init__(self, args):, serves as the constructor and is automatically called when an instance is created. The first parameter, conventionally named self, refers to the instance being created.

Classes can have both instance variables and class variables. Instance variables are unique to each object and typically set via self.var, while class variables are shared across all instances of the class and accessed through MyClass.var. Methods are functions defined inside a class that take self as their first parameter, allowing them to access and modify the instance's attributes. They are called on instances using dot notation, as in obj.method().

Inheritance lets you create a subclass that inherits methods and attributes from a parent class. You define a subclass with class Child(Parent):, and the child automatically gains the parent's functionality. To customize behavior, you can override a method by defining one with the same name in the child class. This mechanism enables code reuse and the creation of class hierarchies that model real-world relationships.

Modules, Exceptions, and Advanced Features

Python's modular system allows you to organize and reuse code across files and projects. You can import a module with import module and access its functions as module.func, or bring specific names into scope with from module import func. The standard library provides many built-in modules such as math for mathematical functions, os for operating system interactions, and sys for system-specific parameters. A package is a directory containing an __init__.py file along with modules, and you can import from it using from pkg.module import func.

Exception handling in Python uses the try/except construct. You place code that might raise an error inside a try block, follow it with except clauses that catch specific exception types like ValueError, and optionally add an else block for code that runs only if no exception occurred, plus a finally block for cleanup that always runs. To signal an error condition yourself, you can use the raise statement, such as raise ValueError('message').

Python also offers several advanced features for concise and expressive code. Lambda functions are anonymous functions defined with a single expression, like lambda x: x*2, and they are commonly used with map(), filter(), and sorted(). List comprehensions provide a compact way to build lists; for example, [x*2 for x in range(5) if x%2==0] generates doubled values of even numbers from 0 to 4. Generators are functions that use yield to produce values lazily, one at a time, which saves memory when working with large sequences. Decorators are functions that wrap other functions to modify their behavior, applied with the @decorator syntax above the function definition; common examples include @staticmethod and @classmethod. Context managers handle resource setup and cleanup automatically, as seen in with open('file.txt', 'r') as f:, and you can create custom context managers using classes with __enter__ and __exit__ methods or with the @contextmanager decorator. Finally, async and await enable concurrent programming through the asyncio module, allowing non-blocking I/O operations; an async def coroutine can pause with await asyncio.sleep(1) while other tasks run.

Frequently asked questions

What is Python?

Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple paradigms including procedural, object-oriented, and functional programming.

What are arithmetic operators in Python?

They include + (addition), - (subtraction), * (multiplication), / (division), // (floor division), % (modulo), and ** (exponentiation).

How do you define a function?

Use def function_name(parameters): followed by indented body. Call with function_name(args).

How do you slice strings?

Strings are immutable: s[1:3] gets substring from index 1 to 3 (exclusive). Use step: s[::2].

How do you import modules?

import module or from module import func. Standard lib: math, os, sys.

What is the walrus operator in Python?

The walrus operator := (Python 3.8+) assigns a value to a variable within an expression: if (n := len(items)) > 10: print(f"Too many: {n}"). It reduces redundancy by allowing both assignment and use in a single expression.

What is the requirements.txt file?

A requirements.txt lists all project dependencies: flask==2.3.0 or flask>=2.3.0. Generate with pip freeze > requirements.txt and install with pip install -r requirements.txt. It ensures reproducible builds.

What is collections.defaultdict in Python?

collections.defaultdict(default_factory) provides a default value for missing keys: dd = defaultdict(list); dd['key'].append(1). Avoids KeyError and simplifies dictionary operations where keys may not exist.

What is the __slots__ attribute in Python?

__slots__ limits which attributes an instance can have and reduces memory usage by eliminating the per-object __dict__. Example: class Point: __slots__ = ('x', 'y'). Objects with slots cannot have arbitrary attributes.

What is the @classmethod and @staticmethod decorator?

@classmethod takes cls as first argument and can access class state. @staticmethod does not receive a first implicit argument (works like a regular function inside the class namespace). Use classmethod for alternative constructors.

Drill this topic

100 flashcards on Python Programming — free, no signup needed to start.

Study Python Programming flashcards

LearnWiki pages are generated with AI assistance from LearnCoachAssist's reviewed study catalog and may contain errors — verify anything critical against your course materials.