Python Functions, Loops, and Basic Operations, CS124 – Study Notes
offline

Difficulty: Beginner | Prerequisites: Basic Python syntax (variables, data types, print statements)

TL;DR

This covers the building blocks you will use in every Python program: writing functions that take inputs and return outputs, using loops to repeat work, and performing basic arithmetic and random number operations. If you can define a function, write a for loop, and understand how return differs from print, you have the foundation for everything else in CS124.

Key Terms

Function

A named, reusable block of code defined with def that takes zero or more inputs and optionally returns a value. Think of it as a mini-program inside your program that you can call whenever you need it.

Parameter

A variable listed inside the parentheses of a function definition. It acts as a placeholder for the data the function will receive. In def add(a, b):, both a and b are parameters.

Argument

The actual value you pass into a function when you call it. In add(3, 5), the numbers 3 and 5 are arguments. In simple terms, parameters are the names, arguments are the values.

Return value

The result a function sends back to the caller via the return statement. Without return, a function returns None by default. Think of it as the answer the function hands back after doing its work.

Loop (for / while)

A control structure that repeats a block of code. A for loop iterates over a sequence (like range()); a while loop runs as long as its condition stays True. In simple terms, loops let you avoid writing the same line dozens of times.

Iteration

One single pass through the body of a loop. If a loop runs 10 times, that is 10 iterations.

Modulo operator (%)

Returns the remainder after integer division. 7 % 2 gives 1. This is the standard way to check whether a number is even (n % 2 == 0) or divisible by another number.

Type casting

Converting a value from one data type to another, e.g. int("5") turns the string "5" into the integer 5. In simple terms, you are telling Python to treat the data differently.

random module

Python's built-in library for generating pseudo-random numbers. random.randint(a, b) returns a random integer between a and b inclusive. You must import random before using it.

Core Content

Defining and Calling Functions

  • Every function starts with def, followed by the function name, parentheses (with any parameters), and a colon.

  • The body is indented one level (4 spaces by convention).

  • return sends a value back to wherever the function was called. If you omit it, the function returns None.

  • Example: a function that adds two numbers:

    • def add(a, b):

    • return a + b

    • Calling add(3, 5) evaluates to 8.

  • Functions can call other functions, and you can store the return value in a variable: result = add(3, 5).

For Loops and Range

  • for i in range(n): runs the body n times, with i going from 0 to n - 1.

  • range(start, stop) goes from start up to but not including stop.

  • range(start, stop, step) lets you skip values, e.g. range(0, 40, 2) produces 0, 2, 4, ... 38.

  • Printing the first 20 even numbers: loop through range(1, 21) and multiply each by 2, or use range(2, 42, 2).

While Loops

  • while condition: repeats as long as the condition is True.

  • You must update something inside the loop to eventually make the condition False, otherwise you get an infinite loop.

  • Useful when you do not know in advance how many iterations you need (e.g. a guessing game that keeps going until the user gets it right).

Arithmetic and the Modulo Operator

  • +, -, *, / (float division), // (integer division), ** (exponentiation), % (modulo).

  • n % 2 == 0 checks if n is even. n % 2 != 0 checks if n is odd.

  • Integer division // truncates toward negative infinity: 7 // 2 gives 3, -7 // 2 gives -4.

Working with the Random Module

  • import random at the top of your file.

  • random.randint(a, b) returns a random integer from a to b, inclusive on both ends.

  • Simulating two dice: call random.randint(1, 6) twice and sum the results.

Computing Averages

  • Sum all elements, then divide by the count.

  • Watch out for integer division in Python 2 (CS124 uses Python 3, where / gives a float by default).

  • An empty list has no average; your function should handle that edge case.

Formulas and Patterns

Factorial

n! = n x (n-1) x (n-2) x ... x 1, with 0! = 1 by definition. Implemented iteratively with a loop that multiplies a running product, or recursively by returning n * factorial(n - 1) with a base case of n == 0.

Nth triangular number

T(n) = n x (n + 1) / 2. This is the sum of all integers from 1 to n. You can also compute it with a simple loop that accumulates a running total.

Leap year logic

A year is a leap year if it is divisible by 4, except that years divisible by 100 are not leap years, unless they are also divisible by 400. In code: (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0).

Even/odd detection

n % 2 == 0 for even, n % 2 != 0 for odd. This pattern appears constantly in filtering and summing problems.

Average

average = sum of elements / number of elements. In Python: sum(lst) / len(lst), or compute both manually with a loop.

Common Misconceptions

  • Students often confuse return with print. print displays text to the console but does not send a value back to the caller. If your function uses print instead of return, any variable assigned to that function call will be None.

  • Students sometimes write range(1, 20) expecting 20 values. range(1, 20) produces 1 through 19 (19 values). To get 1 through 20, use range(1, 21). The stop value is always excluded.

  • Confusing / and //. In Python 3, 7 / 2 gives 3.5 (float), while 7 // 2 gives 3 (integer). When computing averages, you almost always want /.

  • Forgetting to initialise an accumulator variable before a loop. If you are summing values, you need total = 0 before the loop begins, not inside it.

Why It Matters / Exam Flags

  • ⚠️ Expect at least one question asking you to write a function from scratch (define it, accept parameters, return a value). Get the syntax automatic.

  • ⚠️ range() boundary questions are common. Know that range(a, b) excludes b.

  • ⚠️ Tracing through a loop and predicting its output is a classic exam format. Practice stepping through small loops by hand.

  • ⚠️ The modulo operator appears in many contexts: even/odd checks, divisibility tests, leap year logic, cycling through values. Understand % thoroughly.

  • ⚠️ Know the difference between return and print cold. This is one of the most frequently tested distinctions in introductory CS.

Quick Self-Test

  1. True or False: range(5) produces the values 1, 2, 3, 4, 5. (Answer: False. It produces 0, 1, 2, 3, 4.)

  1. Fill in the blank: A function without a return statement returns ______ by default. (Answer: None)

  1. True or False: 15 % 3 == 0 evaluates to True. (Answer: True. 15 is divisible by 3 with no remainder.)

  1. Fill in the blank: To generate a random integer between 1 and 6 inclusive, you call random._______(1, 6). (Answer: randint)

  1. True or False: 10 // 3 gives 3.33. (Answer: False. It gives 3 because // performs integer division.)

Practice Q&A

Q: Write a Python function that takes two numbers and returns their sum.

A: def add(a, b): return a + b. Define the function with two parameters, then use return to send back their sum.

Q: Write a loop that prints the first 20 even numbers.

A: Use for i in range(1, 21): print(i * 2). Alternatively, for i in range(2, 42, 2): print(i). Both produce 2, 4, 6, ... 40.

Q: Create a Python function that returns the factorial of a given integer.

A: Initialise a result variable to 1, then loop from 1 to n (inclusive), multiplying result by each value. Return the result. Handle the edge case where n is 0 by returning 1.

Q: Write a program to find the maximum and minimum in a list without using max() or min().

A: Set both current_max and current_min to the first element. Loop through the rest of the list, updating each whenever you find a larger or smaller value.

Q: Implement a function to count the number of vowels in a given string.

A: Loop through each character, check if it is in 'aeiouAEIOU', and increment a counter. Return the counter.

Q: Write a Python program that simulates rolling two dice and outputs their sum.

A: import random, then die1 = random.randint(1, 6) and die2 = random.randint(1, 6). Print die1 + die2.

Q: Implement a function to calculate the nth triangular number.

A: Return n * (n + 1) // 2. Alternatively, use a loop to sum all integers from 1 to n.

Q: Write a function to check if a given year is a leap year.

A: Return True if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0). Otherwise return False.

Q: Given a list of integers, return the sum of all odd numbers.

A: Loop through the list, check n % 2 != 0 for each element, and add matching values to a running total. Return the total.

Q: Write a Python function that takes a list of integers and returns their average.

A: Return sum(lst) / len(lst). Guard against an empty list first, since dividing by zero raises an error.

Connections to Other Topics

Functions are the foundation of code reuse and abstraction. Once you are comfortable defining and calling functions, you will use them to build recursive solutions (covered in the Recursion and Algorithms notes) and to organise list and string processing into clean, testable units.

Loops connect directly to list traversal, string manipulation, and searching/sorting algorithms. Every algorithm in the later notes relies on the loop patterns covered here.

The modulo operator reappears in prime-checking, GCD computation (Euclidean algorithm), and hash functions later in the course.


Related Terms / Search Tags

Python functions, def keyword, return statement, for loop, while loop, range(), iteration, modulo operator, remainder, factorial, triangular number, leap year, even odd check, random module, randint, integer division, floor division, type casting, accumulator pattern, CS124, UIUC, Intro to Computer Science I, Python basics, loop tracing