Python Programming Basics
Python Programming: Core Concepts and Practical Foundations
Python and the Development Environment
Python is a general-purpose programming language used for tasks such as automation, scripting, application development, and data processing. Its relatively small amount of required syntax makes it accessible to beginners, while its broad capabilities and ecosystem also support complex projects.
Programming consists of giving a computer a set of instructions. A Python program contains instructions that the Python interpreter executes in sequence. Clear organization, appropriate data structures, and reusable functions help programs remain manageable as they grow.
Python versions
Python has had two major versions: Python 2 and Python 3. Python 2 is a legacy version and is no longer officially maintained. Python 3 is the actively supported version and is the recommended choice for new learners and projects.
The versions share many concepts, but some syntax and behavior differ. Learning Python 3 provides a strong foundation for understanding Python generally.
Installing Python and choosing an editor
Python can be installed from the official Python website. During installation, the operating system receives the Python interpreter and tools needed to run Python programs.
Python code can be written in any text editor, but an integrated development environment (IDE) provides additional programming tools. An IDE commonly helps users:
Write and organize code.
Run programs.
Detect or highlight possible errors.
Navigate files and project folders.
PyCharm is one example of a Python IDE. A project groups related files together. When creating a project, the IDE must use the intended Python interpreter; for Python 3 coursework, the selected interpreter should be Python 3.
Writing and Running a First Program
A Python source file contains instructions for the interpreter. Python usually executes those instructions from top to bottom, so the order of lines can affect the program’s result.
The print function displays information in the console, an output area used to show text and other program results. A first program can print a message:
print("Hello, world!")The text inside quotation marks is a string. When the program runs, Python executes the print instruction and displays the string in the console.
A program can also print several lines to create a simple shape. Each print instruction contributes output in sequence:
print(" /|")
print(" / |")
print(" / |")
print("/___|")Changing the order of these instructions changes the order of the printed lines. The console is therefore useful not only for displaying final results, but also for inspecting what a program is doing.
Variables and Basic Data Types
A variable is a named reference used to store a value so the program can use it later. Variables make data easier to manage: when a value is used in many places, changing it once in its variable can update its use throughout the program.
An assignment connects a variable name to a value:
character_name = "John"
character_age = 35The variable character_name stores text, while character_age stores a number. Variable names should describe the values they represent. In Python, multiple words are commonly separated with underscores, as in character_name.
A variable can be assigned a new value later:
character_name = "Mike"Subsequent uses of character_name then refer to the new value.
Strings
A string stores text and is written inside matching single or double quotation marks:
name = "Jordan"Quotation marks distinguish text from variable names and other kinds of values.
Numbers
Python supports whole numbers, called integers, and numbers with decimal parts, called floating-point numbers:
age = 35
price = 50.56Numbers do not need quotation marks. A number written inside quotation marks is text rather than numeric data.
Booleans
A Boolean represents one of two logical values: True or False. Booleans are useful for representing conditions, such as whether a student is on probation or whether an account is active.
is_active = TrueStrings, numbers, and Booleans are common foundational data types. Programs use them individually and combine them into larger structures.
Working with Strings
A string is a sequence of characters. Strings can be displayed, combined, inspected, and transformed.
Escape characters
A backslash introduces special sequences inside a string. For example, \n inserts a new line:
print("First line\nSecond line")A backslash can also mark a character to be treated literally. For example, \" allows a quotation mark to appear inside a double-quoted string:
print("She said, \"Hello.\"")The escape sequence \\ represents a literal backslash.
Concatenation
Concatenation combines strings. In Python, the + operator can join string values:
phrase = "Python"
message = phrase + " is useful"The resulting string is Python is useful. Concatenation is useful when combining fixed text with values stored in variables, though values of different types generally need conversion before they can be joined as strings.
Common string operations
String methods provide operations on strings. A method is called using dot notation after a value:
phrase.lower()
phrase.upper()lower()returns a lowercase version of the string.upper()returns an uppercase version.isupper()returnsTrueif all cased letters in the string are uppercase; otherwise it returnsFalse.len(phrase)returns the number of characters in the string.phrase.index(value)returns the index where the first matching substring begins. It raises an error if the requested value is absent.phrase.replace(old, new)returns a string in which occurrences ofoldare replaced bynew.
String methods usually return a result; they do not necessarily change the original string.
Indexing and character positions
Characters in a string can be accessed by index, or position. Python uses zero-based indexing: the first character is at index 0, the next at index 1, and so on.
word = "Python"
first_character = word[0]The value of first_character is P. An index that is outside the valid range causes an error. Negative indices count from the end of the string; for example, index -1 refers to the last character.
Numbers and Arithmetic
Numbers can be printed directly, assigned to variables, and used in arithmetic expressions. Python supports addition, subtraction, multiplication, and division:
total = 3 + 4.5
difference = 10 - 2
product = 3 * 4
quotient = 12 / 3Parentheses control the order in which parts of an expression are evaluated. For example, parentheses can make addition happen before multiplication.
The modulus operator % returns the remainder after division. For example, 10 % 3 evaluates to 1, because dividing 10 by 3 leaves a remainder of 1. Modulus is useful for tasks such as checking whether a number is evenly divisible by another number.
Converting numbers and strings
str(value) converts a value to a string. This is useful when displaying a number alongside text:
age = 35
print("Age: " + str(age))Common numeric functions include:
abs(number): returns the absolute value.pow(base, exponent): raises a base to a power.max(a, b): returns the largest supplied value.min(a, b): returns the smallest supplied value.round(number): rounds to the nearest integer according to Python’s rounding behavior.
The math module supplies additional mathematical operations. It must be imported before its functions are used:
import math
math.floor(3.8)
math.ceil(3.2)
math.sqrt(36)floor()rounds down to the next integer.ceil()rounds up to the next integer.sqrt()calculates a square root.
A module is a file or library that provides reusable code.
User Input and Type Conversion
The input() function pauses a program and allows a user to enter information. It can display a prompt:
name = input("Enter your name: ")
print("Hello, " + name)The result of input() is a string, even if the user types digits. If input is intended to be numeric, it must be converted.
int(value)converts compatible input to an integer.float(value)converts compatible input to a floating-point number.
For example:
first_number = float(input("Enter a number: "))
second_number = float(input("Enter another number: "))
print(first_number + second_number)Using int() is appropriate when only whole numbers are expected. Using float() permits decimal values. If the input cannot be converted, Python raises an error unless the program handles that error.
A basic calculator
A calculator can collect two numbers and an operator, then use conditional logic to choose the requested operation:
first = float(input("Enter the first number: "))
operator = input("Enter an operator (+, -, *, /): ")
second = float(input("Enter the second number: "))
if operator == "+":
print(first + second)
elif operator == "-":
print(first - second)
elif operator == "*":
print(first * second)
elif operator == "/":
print(first / second)
else:
print("Invalid operator")This example combines input, type conversion, comparison, and conditional execution.
A Mad Libs-style program
A Mad Libs program collects several words from a user and inserts them into a prepared story. Each response can be stored in a separate variable:
color = input("Enter a color: ")
plural_noun = input("Enter a plural noun: ")
celebrity = input("Enter a celebrity: ")
print("Roses are " + color + ",")
print(plural_noun + " are blue,")
print("I love " + celebrity + ".")This illustrates how input and string concatenation can make a program interactive. More prompts and story lines can be added using the same approach.
Lists and List Operations
A list stores multiple values in an ordered collection. Lists are useful for organizing related data, such as names, scores, or records.
friends = ["Kevin", "Karen", "Jim"]A list can contain values of different types, though lists are often easiest to use when their values have a related purpose.
Accessing and changing elements
List elements are accessed by zero-based index. In the example above, friends[0] is "Kevin", friends[1] is "Karen", and friends[2] is "Jim".
Negative indices count backward from the end: friends[-1] refers to the final element.
A slice selects a portion of a list:
friends[1:]
friends[1:3]The first slice selects elements beginning at index 1 through the end. The second selects indices beginning at 1 and ending before index 3. A slice’s ending index is excluded.
List elements can be changed by assigning a new value at an index:
friends[1] = "Michael"Unlike a tuple, a list is mutable: its contents can be changed after the list is created.
Common list methods
extend(other_list)adds all elements from another iterable to the end of the list.append(value)adds one element to the end.insert(index, value)inserts one element at a chosen position and shifts later elements.remove(value)removes the first matching value.clear()removes all elements.pop()removes and returns the final element by default. A supplied index can specify another element.index(value)returns the index of the first matching value; it raises an error if the value is absent.count(value)returns the number of matching elements.sort()sorts the list in place, in ascending order by default.reverse()reverses the list in place.copy()creates a shallow copy of the list.
Methods such as sort(), reverse(), and append() modify the existing list; they generally do not return a new sorted or modified list. A copied list provides a separate list object, although a shallow copy still shares references to any mutable objects nested inside it.
Tuples
A tuple is an ordered collection that, like a list, can contain multiple values. Tuples are commonly written with parentheses:
coordinates = (4, 5)Tuple elements are accessed by index, beginning at 0, in the same way as list elements.
The key distinction is that a tuple is immutable: its elements cannot be reassigned, added, or removed after it is created. Tuples are appropriate for fixed groups of values, such as a coordinate pair, that should remain unchanged.
Lists and tuples can also be combined. For example, a list can contain several coordinate tuples. The outer list can be modified, while the individual tuples remain immutable.
A single-element tuple requires a trailing comma, such as (4,); parentheses alone do not always create a tuple.
Functions, Parameters, and Return Values
A function is a named block of code designed to perform a task. Functions organize programs into reusable parts and reduce repeated code.
A function is defined with def, followed by a name, parentheses, and a colon. The indented lines beneath the definition form its body:
def say_hi():
print("Hello, user")Defining a function does not run it. The function runs only when it is called:
say_hi()Python executes the function body when it reaches the call, then returns to the point in the program after the call.
Parameters and arguments
A parameter is a variable named in a function definition. It allows a function to receive information. An argument is the actual value supplied when the function is called.
def say_hi(name):
print("Hello, " + name)
say_hi("Mike")Here, name is the parameter, and "Mike" is the argument. Functions can have multiple parameters, allowing them to work with several supplied values.
Return statements
A function can provide a result to the code that called it by using return:
def cube(number):
return number * number * number
result = cube(3)The returned value can be stored, printed, or used in another expression. A return statement also ends the function immediately. Statements placed after a return on the same execution path will not run.
Functions can return values of different data types, including numbers, strings, Booleans, and collections.
Building an exponent function
A function can raise a base to a power by repeatedly multiplying it by itself:
def raise_to_power(base, exponent):
result = 1
for _ in range(exponent):
result *= base
return resultThe initial value of result is 1, the multiplicative identity. The loop multiplies it by base once per iteration, so the result becomes baseexponent for a nonnegative integer exponent.
Conditional Statements and Comparisons
An if statement allows a program to make decisions. It tests a condition, which evaluates to either True or False. If the condition is true, the indented block runs; otherwise, that block is skipped.
if is_male:
print("The condition is true")
else:
print("The condition is false")The else branch provides instructions for the case where the if condition is false. An elif branch (“else if”) tests another condition when earlier conditions were false. Multiple elif branches can be used before an optional else.
Indentation determines which statements belong to each branch. In Python, indentation is part of the program’s structure.
Logical operators
Logical operators combine or alter conditions:
andis true only when both conditions are true.oris true when at least one condition is true.notreverses a Boolean condition: true becomes false and false becomes true.
For example, a condition using and can identify a person who meets two requirements, while or can identify someone who meets either requirement.
Comparison operators
Comparison operators compare values and produce a Boolean result:
==checks whether two values are equal.!=checks whether two values are not equal.>and<test whether one value is greater or less than another.>=and<=include equality in the comparison.
A single = assigns a value; == compares values. Confusing these operators can cause errors or unintended behavior.
Comparisons can be used with numbers and strings, subject to compatible types and Python’s comparison rules.
Selecting the largest of three numbers
A function can use comparisons and conditional branches to select a maximum:
def max_num(first, second, third):
if first >= second and first >= third:
return first
elif second >= first and second >= third:
return second
else:
return thirdEach branch tests whether one input is at least as large as the others. The final else handles the remaining case.
Calculator decision logic
A more complete calculator uses the operator supplied by the user as a string and compares it with supported operator symbols. Each matching branch performs a different calculation. An else branch can report an unsupported operator, preventing the program from silently treating invalid input as a valid operation.
While Loops and a Guessing Game
A while loop repeatedly executes an indented block as long as its condition remains true. The condition is checked before each iteration.
count = 1
while count <= 10:
print(count)
count += 1The variable is updated during the loop so that the condition eventually becomes false. If the condition never becomes false, the loop continues indefinitely; this is an infinite loop. A loop’s condition is sometimes called its guard.
Guessing a secret word
A guessing game can use a while loop to continue requesting guesses until the correct word is entered:
secret_word = "draft"
guess = ""
while guess != secret_word:
guess = input("Enter a guess: ")
print("You win")The loop ends when the guess equals the secret word. To limit the number of attempts, the program can track a guess count, compare it with a guess limit, and use a Boolean such as out_of_guesses to indicate when no attempts remain.
A limited game must distinguish between two possible reasons for leaving the loop:
The player guessed the secret correctly.
The player ran out of attempts.
An if statement after the loop can check which outcome occurred and print the appropriate result. The count should be incremented each time a guess is accepted, and the loop guard should stop when either the answer is correct or the attempt limit has been reached.
For Loops and Iteration
A for loop processes items in an iterable collection, such as a string, list, or range of numbers. The loop variable takes on each item’s value in turn.
for letter in "Python":
print(letter)This loop prints each character in the string. A list can be traversed in the same way:
friends = ["Jim", "Karen", "Kevin"]
for friend in friends:
print(friend)The loop variable is assigned a new element during each iteration.
The range() function
range() produces a sequence of integers that a loop can iterate over:
for index in range(5):
print(index)This iterates over 0,1,2,3,4. The endpoint is excluded. A start and endpoint can also be supplied, as in range(3, 10), which includes 3 but excludes 10.
Looping by index
A list can be traversed by index using range(len(items)). Directly looping over the items is usually clearer when the index is not needed. When both an index and a value are needed, Python’s enumerate() function is often a convenient choice.
Conditional statements can be placed inside loops to handle particular iterations differently—for example, to print a special message during the first iteration.
Two-Dimensional Lists and Nested Loops
A two-dimensional list is a list whose elements are themselves lists. It can represent a grid, table, or other row-and-column structure:
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]The first index selects a row; the second selects an element within that row. For example, number_grid[2][1] selects the element at row index 2 and column index 1, which is 8.
A nested loop is a loop inside another loop. It can process every element in a two-dimensional structure:
for row in number_grid:
for value in row:
print(value)The outer loop visits each row. For each row, the inner loop visits each value in that row. Nested loops are useful for grids and tables, including structures where different rows may contain different numbers of elements.
Translating Text with Loops and Conditions
A simple text translator can examine a phrase character by character and build a new string. For example, a made-up rule might replace every vowel with g.
A translation function can:
Start with an empty result string.
Loop through each character in the input phrase.
Check whether the character is a vowel.
Add
gto the result when it is a vowel; otherwise, add the original character.Return the completed result.
A membership test using in checks whether a character occurs in a collection, such as a string of vowels. Methods such as lower() can make the check case-insensitive. If capitalization must be preserved, the program can check whether the original character was uppercase and select an uppercase replacement when appropriate.
This pattern—looping through input, testing each item, and accumulating a result—is useful for text transformations and many other programming tasks.
Comments
A comment is text in a source file that Python ignores during execution. Comments explain code to human readers or temporarily disable code.
A # begins a single-line comment:
# This line explains the following operation.
print("Comments are useful")A line of code can also be commented out by placing # before it. The code remains in the file but is not executed.
Python also has triple-quoted strings, often used to write multiline documentation strings, or docstrings, for modules, classes, and functions. They are string literals rather than ordinary comments, so they should be used for documentation rather than treated as a general replacement for # comments.
Handling Errors with Exceptions
An error can stop a program while it is running. A try/except block allows a program to handle certain exceptions instead of terminating unexpectedly.
try:
number = int(input("Enter a whole number: "))
except ValueError:
print("The input was not a valid integer")The code in try runs first. If it raises the specified exception, Python runs the matching except block. If no such exception occurs, the except block is skipped.
Different errors call for different handling. For example:
ValueErrorcan occur when a value cannot be converted to the requested type.ZeroDivisionErroroccurs when a number is divided by zero.
Catching a specific exception makes behavior more precise than a broad except clause, which may hide unrelated problems. An exception can be captured with as, allowing the program to inspect or display the error object.
Error handling is especially important when programs depend on user input, files, or external systems, because those operations may fail for reasons the program cannot assume away.
Reading, Writing, and Appending Files
Python can work with files outside the program’s source file. Files may store text or other data that a program needs to read or change.
Opening and reading a file
The open() function opens a file and returns a file object. A mode specifies how the file will be used:
"r"opens a file for reading."w"opens a file for writing, replacing existing contents or creating the file if needed."a"opens a file for appending to the end."r+"permits reading and writing.
A file can be read with methods such as:
read(): reads the file’s contents.readline(): reads one line at a time.readlines(): reads the lines into a list.Iteration over the file object: processes lines one at a time.
A file object can be checked with readable() when needed. A file should be closed after use so that system resources are released and data is properly finalized.
A modern and safer pattern is a context manager, which closes the file automatically:
with open("employees.txt", "r") as employee_file:
contents = employee_file.read()Writing and appending
The write() method writes a string to a file. In "a" mode, new text is added at the end. In "w" mode, existing contents are overwritten, so the mode must be chosen carefully.
A newline character, \n, can separate appended text from existing content:
with open("employees.txt", "a") as employee_file:
employee_file.write("\nKelly, Customer Service")Repeatedly running an append operation adds the text repeatedly. Writing to files changes persistent data, so it is important to understand exactly which file and mode are being used.
Writing can also create new files, including files with formats such as HTML, provided that the written contents follow the format’s requirements.
Modules and Package Management
A module is a Python file containing reusable code, such as functions, classes, or variables. Importing a module allows a program to use that code without copying it into the current file.
import useful_tools
result = useful_tools.roll_dice(6)When a module is imported by its module name, its members can be accessed with dot notation. Specific members can also be imported directly:
from useful_tools import roll_dicePython includes standard-library modules, and third-party developers provide additional packages. The Python documentation describes standard-library functionality. Third-party modules can extend Python with capabilities such as document creation, data analysis, or web development.
Installing packages with pip
pip is Python’s package-management tool. It can install and remove many third-party packages:
pip install package_name
pip uninstall package_nameThe package’s installation name and its import name are not always identical. A package’s documentation should be consulted for its installation and usage instructions. A compatible Python interpreter and package version are also important, especially when a project depends on particular library features.
Modules make programs more reusable: code can be written once, organized in a separate file or package, and imported wherever it is needed.
Classes and Objects
A class defines a custom data type: a description of the information and behavior that a kind of object should have. An object is a particular instance of that class.
Classes allow programs to model entities that cannot be represented usefully by a single string, number, or Boolean. A student, for example, may have a name, major, grade-point average, and probation status.
class Student:
def __init__(self, name, major, gpa, is_on_probation):
self.name = name
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probationThe special method __init__ runs when a new object is created. It initializes that object’s attributes. The parameter self refers to the particular object being initialized. Assignments such as self.name = name store supplied values as attributes of that object.
An object can then be created by calling the class:
student = Student("Jim", "Business", 3.1, False)
print(student.name)The class is the template; student is an object created from it. Different objects can have different attribute values while sharing the same class definition.
Classes can be organized into separate modules and imported where needed.
Class Methods
A method is a function defined inside a class. An instance method receives self as its first parameter, giving it access to the current object’s attributes. Methods can calculate information about an object or perform actions using its data.
class Student:
def __init__(self, name, gpa):
self.name = name
self.gpa = gpa
def is_on_honor_roll(self):
return self.gpa >= 3.5Calling student.is_on_honor_roll() evaluates the current student’s GPA and returns a Boolean result. A method can therefore keep behavior close to the data that behavior uses.
Inheritance
Inheritance allows one class to reuse and specialize another class. The class being inherited from is the parent or base class; the inheriting class is the child or subclass.
class Chef:
def make_chicken(self):
print("The chef makes chicken")
def make_special_dish(self):
print("The chef makes barbecue ribs")
class ChineseChef(Chef):
def make_fried_rice(self):
print("The chef makes fried rice")
def make_special_dish(self):
print("The chef makes orange chicken")ChineseChef inherits the methods of Chef, so an instance can use make_chicken() without that method being rewritten in the subclass. The subclass can also add new methods, such as make_fried_rice().
When a subclass defines a method with the same name as an inherited method, it overrides that method. In the example, ChineseChef provides its own version of make_special_dish(). Inheritance supports code reuse while allowing more specialized behavior.
The Python Interpreter
The Python interpreter executes Python code. Python’s interactive interpreter provides a prompt where individual expressions and statements can be entered and evaluated immediately. It is useful for quick experiments, such as testing a function, checking a calculation, or exploring how a method behaves.
The interpreter is often accessed through a terminal or command prompt. These command-line environments accept text commands rather than relying entirely on graphical controls. Depending on the installation, the command may be python, python3, or a version-specific command.
The interactive interpreter is convenient for short tests, but source files and an IDE are generally more suitable for larger programs. Files preserve code, support organization across multiple modules, and make it easier to develop and rerun a complete application.

Ask anything
We've read this whole study set, so questions about it get the best answers.