Loops & Functions
Intro to Python · Lesson 4 of 4 (Capstone)
for loops
A for loop repeats a block of code once per item in a sequence. range(n) generates the numbers 0 through n - 1:
for i in range(5):
print(i)
# prints 0, 1, 2, 3, 4
while loops
A while loop repeats as long as a condition stays True. You control when it stops — make sure something inside the loop eventually makes the condition False, or it'll run forever.
count = 0
while count < 3:
print("Still going:", count)
count = count + 1
print("Done!")
Functions
A function is a named, reusable block of code, defined with def. Functions can take parameters (inputs) and return a value (output):
def square(number):
return number * number
print(square(4)) # 16
print(square(7)) # 49
Without functions, you'd have to copy-paste the same logic every time you need it. With them, you write it once and call it as many times as you like.
Putting it together: random numbers
Python's random module can pick a random number for you. Add this line at the very top of your file:
import random
secret = random.randint(1, 100) # a random number from 1 to 100
Try it yourself
Write a function called is_even(number) that returns True if the number is even and False otherwise (reuse the % trick from Lesson 3). Then use a for loop to call it on every number from 1 to 10 and print the result.
Capstone Assignment: Number Guessing Game
Combine everything from all four lessons into one program:
- Use
random.randint(1, 100)to pick a secret number. - Use a
whileloop that keeps asking the player to guess withinput()until they get it right. - After each guess, use
if/elif/elseto tell them "Too high!", "Too low!", or "You got it!". - Keep count of how many guesses it took, using a variable you increase inside the loop.
- Wrap the whole game in a function called
play_game()and call it at the bottom of your file.
Guess a number between 1 and 100: 50
Too high!
Guess a number between 1 and 100: 25
Too low!
Guess a number between 1 and 100: 37
You got it in 3 guesses!
When you're done, copy your Replit link and submit it below — and congratulations on finishing your first course!
