Python Challenges

Challenge 1

Write a program that:

  • asks the user their age
  • outputs "Your age is " and then show their age

Knowledge

Sequencing

Variables

Difficulty: 1

'''
Challenge 1 a program that asks the user their age and then outputs their age.

David James 10/12/19
'''

# Get the users age
print("What is your age? ")

# Store the user input in memory
age = input()

# Output the users age to screen
print(f"You are {age} years old.") # version 3.6 onwards
print("You are {} years old." .format(age)) # alternative option

Challenge 2

Write a program that:

  • asks the user to input two numbers
  • calculates the average of the numbers
  • outputs this average

Knowledge

Sequencing

Variables

Difficulty: 1

'''
Challenge 2
Input two numbers
Calculate the average of the two numbers
Output the average value

David James 10/12/19
'''

# Store the first number
num1 = input("What is the first number? ")
num1 = int(num1) # Two lines but easier to read

# Store the second number
num2 = int(input("What is the second number? ")) # One line, harder to read

# Calculate the average of the two numbers
average = (num1 + num2) / 2

# Output the average
print(f"The average of {num1} and {num2} is {average}.")
#print("The average of {} and {} is {}.".format(num1, num2, average))

Challenge 3

Write a program that:

  • asks the user to input the width and height of a rectangle
  • calculates the area of the rectangle
  • outputs this area

Knowledge

Sequencing

Variables

Difficulty: 1

'''
Challenge 3
  input the width and height of a rectangle
  calculate the area of the rectangle
  output the area

David James 10/12/19
'''

# Get the dimensions of the rectangle
print("Enter the dimensions of the rectangle...")
width = input("width = ")
width = float(width) # Convert from a string to a floating point value 
height = input("height = ")
height = float(height) # Convert from a string to a floating point value 

# Calculate the area of the rectangle
area = width * height
area = round(area, 1) # Rounds to one decimal place

# Output the area of the rectangle
print(f"The area of this triangle is {area}")
#print("The area of this triangle is {}".format(area))

Challenge 4

Write a program that:

  • asks the user to input two numbers
  • calculate the first number divided by the second number
  • outputs this division

Knowledge

Sequencing

Variables

Difficulty: 1

'''
Challenge 4 : Calculate the division of two numbers

David James 10/12/19
'''

# Get two numbers
num1 = input("What is the first number? ")
num1 = float(num1) # Convert from a string to a floating point value 
num2 = input("What is the second number? ")
num2 = float(num2) # Convert from a string to a floating point value 

# Calculate the area of the rectangle
result = num1 / num2
result = round(result, 2) # Rounds to two decimal places

# Output the result
print(f"{num1} / {num2} = {result}")

Challenge 5

Write a program that:

  • asks the user their name
  • asks the user, using their name, what their favourite subject is
  • outputs "'subject' is my favourite too!"

Knowledge

Sequencing

Variables

Difficulty: 1

'''
Challenge 5 : Combining text

David James 10/12/19
'''

# Get the user's name
name = input("What is your name? ")

# Get the user's favourite subject
subject = input(f"{name} what is your favourite subject? ")
#subject = input("{} what is your favourite subject? ".format(name))

# Print nice message
print(f"{subject} is my favourite subject too!")
#print("{} is my favourite subject too!".format(subject))

Challenge 6

Write a program that:

  • asks the user their name
  • if the name is the same as your name, output "Cool {name} is my name too."
  • otherwise outputs "Nice to meet you {name}"

Knowledge

Selection

Variables

Difficulty: 2

'''
Challenge 6 : Checking a condition

David James 10/12/19
'''

# Get the user's name
name = input("What is your name? ")

# Set the constant MY_NAME
MY_NAME = "David"

# Check if the users name is the same as my name
# Any conditional or looping keyword requires a colon and indentation
if name == MY_NAME: 
    # Note the use of == to compare two values
    print("You are cool")
else:
    print(f"Hello {name}")

Challenge 7

Write a program that:

  • asks the user how many hours of tv they watch per day
  • if the value is less than 2, output "That will not rot your brain too much."
  • if the value is less than 4, output " You will get square eyes."
  • otherwise output "Fresh air is better than channel flicking."

Knowledge

Selection

Variables

Difficulty: 2

'''
Challenge 7 : if-elif-else
David James 10/12/19
'''

# Ask how long the user watches TV each day
tv_time = int(input("How many hours of TV do you watch per day? "))

# Check whether tv_time falls into less than 2, between 2 and 4 or greater than 4 hours
if tv_time < 2:
    print("That will not rot your brain too much.")
elif tv_time < 4:
    print("You will get square eyes.")
else:
    print("Fresh air is better than channel flicking.")

Challenge 8

Write a program that:

  • converts an exam mark into a grade using the following conversion

Knowledge

Selection

Variables

Difficulty: 2

Mark Grade
greater than or equal to 75 A
greater than or equal to 60 B
greater than or equal to 35 C
less than 35 D
'''
Python Challenge 8
David James
2020-07-22

Ask for the mark to convert to a grade
If the mark is greater than or equal to 75 output A
If the mark is greater than or equal to 60 output B
If the mark is greater than or equal to 35 output C
Otherwise output D
'''

#Ask for the mark to convert to a grade
mark = int(input("What was the number of marks? "))

# If the mark is greater than or equal to 75 output A
if mark >= 75:
    grade = 'A'
# If the mark is greater than or equal to 60 output B
elif mark >= 60:
    grade = 'B'
# If the mark is greater than or equal to 35 output C
elif mark >= 35:
    grade = 'C'
# Otherwise output D
else:
    grade = 'D'
    
print(f"{mark} marks is a grade {grade}")

Challenge 9

Write a program that:

  • asks the user to name one of the values from the Wadham Wellbeing Wheel (respect, ...)
  • if they answer correctly, output "Correct, well done."
  • otherwise output "Try again."

Knowledge

Selection

Variables

Difficulty: 2

'''
Python Challenge 9
David James
2020-07-22

Ask for one of the Wadham wheel principles
If they correctly name one, output 'That is correct, well done.'
Otherwise output 'Try again.'
'''

# Wadham principles
wellbeing = ['Relationships', 'Respect', 'Belonging', 'Aspiration', 'Acheivement']

# Ask for one of the Wadham wheel principles
principle = input('Name one of Wadham Wheel principles: ')

# If they correctly name one, output 'That is correct, well done.'
# Otherwise output 'Try again.'
if principle in wellbeing:
    print('That is correct.')
else:
    print('Try again.')

Challenge 10

Write a game that:

  • allows the user to play 'rock, paper, scissors' against the computer
  • must display the computer's choice and show the result of the game

Knowledge

Selection

Variables

Difficulty: 2

Tip:
The computer's answer must be random
'''
Python Challenge 10
David James
2020-07-22

Ask for one of 'rock', 'paper', 'scissors'
Assign randomly either 'rock', 'paper', 'scissors' to the computer
Display the computers choice
Calculate the win, lose or draw
'''

from random import randint

# Options
choices = ['Rock', 'Paper', 'Scissors']

# Get users choice
print('Rock, paper, scissors')
usersChoice = input('Make your choice: ').title()

# Get computers choice
computersChoice = choices[randint(0,2)]
print(f'The computer chose {computersChoice}')

if usersChoice == computersChoice:
    print('Draw')
elif usersChoice == 'Rock':
    if computersChoice == 'Paper':
        print('You lose')
    else:
        print('You win')
elif usersChoice == 'Paper':
    if computersChoice == 'Scissors':
        print('You lose')
    else:
        print('You win')
else:
    if computersChoice == 'Rock':
        print('You lose')
    else:
        print('You win')

Challenge 11

Write a program that:

  • asks the user to input a sentence
  • calculates and outputs how many characters there are in a sentence

Knowledge

Variables

String Manipulation

Difficulty: 3

'''
Python Challenge 11
David James
2020-07-23

Input a sentence
Output how many characters in the sentence
'''

# Input a sentence
print('Type a sentence and press return.\n')
sentence = input()

# Calculate the number of characters
characters = len(sentence)

# Output how many characters in the sentence
print(f'"{sentence}" has {characters} characters')

Challenge 12

Write a program that:

  • asks the user to input a sentence
  • outputs the sentence in upper case

Knowledge

Variables

String Manipulation

Difficulty: 3

'''
Python Challenge 12
David James
2020-07-23

Input a sentence
Output the sentence in upper case
'''

# Input a sentence
print('Type a sentence and press return.\n')
sentence = input()

# Output the sentence in upper case
print(sentence.upper())
print()

Challenge 13

Write a program that:

  • asks the user to input a sentence
  • asks the user to input
    • the word they want to replace
    • the word they want to replace it with
  • outputs the new sentence

Knowledge

Variables

String Manipulation

Difficulty: 3

'''
Python Challenge 13
David James
2020-07-23

Input a sentence
Input a word to replace
Input a word to replace the previous word with
Output the sentence
'''

# Input a sentence
print('Type a sentence and press return.\n')
sentence = input()

# Word to replace
findWord = input('Word to find: ')

# Word to replace the previous word with
replaceWord = input('Word to replace with: ')

# Output the sentence in upper case
print(sentence.replace(findWord, replaceWord))
print()

Challenge 14

Write a program that:

  • asks the user to input a sentence
  • outputs the number of times the word 'the' occurs in it

Knowledge

Variables

String Manipulation

Difficulty: 3

'''
Python Challenge 14
David James
2020-07-23

Input a sentence
Output the number of times the word "the" appears in the sentence
'''

# Input a sentence
print('Type a sentence and press return.\n')
sentence = input()

countThe = sentence.count('the ')

# Output the number of times "the" occurs
print(f'The word "the" appears {countThe} times')
print()

Challenge 15

Write a program that:

  • asks the user to input a sentence
  • outputs the sentence in lower case

Knowledge

Variables

String Manipulation

Difficulty: 3

'''
Python Challenge 15
David James
2020-07-23

Input a sentence
Output the sentence in lower case
'''

# Input a sentence
print('Type a sentence and press return.\n')
sentence = input()

# Output the sentence in upper case
print(sentence.lower())
print()

Challenge 16

Write a program that:

  • outputs all the numbers between 1 and 10

Knowledge

Variables

Repetition

Difficulty: 3

Tip: 
You must use a FOR loop for this challenge
'''
Python Challenge 16
David James
2020-07-23

Output the numbers 1 to 10
'''

# Output the number 1 to 10
for num in range(1,11):
    print(num)

Challenge 17

Write a program that:

  • outputs all the odd numbers between 1 and 99

Knowledge

Variables

Repetition

Difficulty: 3

Tip: 
You must use a FOR loop for this challenge
'''
Python Challenge 17
David James
2020-07-23

Output the odd numbers between 1 and 99
'''

# Output the odd numbers between 1 and 99
for num in range(1,100,2):
    print(num)

Challenge 18

Write a program that:

  • asks the user to input a number
  • outputs the times table for that number

Knowledge

Variables

Repetition

Difficulty: 3

Tip: 
You must use a FOR loop for this challenge
'''
Python Challenge 18
David James
2020-07-23

Ask for a number
Output the times table for a chosen number
'''

# Ask for a number
table = int(input("Which times table do you want to print? "))

# Output the times table for the chosen number
for num in range(1,13):
    print(f"{num} × {table} = {num * table}")

Challenge 19

Write a program that:

  • asks the user to input a number
  • outputs the times table for that number
  • starts again every time it finishes

Knowledge

Variables

Repetition

Difficulty: 3

Tip: 
You must use a FOR loop and a WHILE loop for this challenge
'''
Python Challenge 19
David James
2020-07-23

Ask for a number
Output the times table for a chosen number
Repeats for ever or Ctrl-C is pressed
'''

print('''
        Warning, this will repeat for ever or until Ctrl-C is pressed!
    ''')

# Ask for a number
table = int(input("Which times table do you want to print? "))

while True:
# Output the times table for the chosen number
    for num in range(1,13):
        print(f"{num} × {table} = {num * table}")

Challenge 20

Write a program that:

  • asks the user to input a number and repeats until they guess the number 7
  • congratulates the user with a 'Well Done' message, when they guess correctly

Knowledge

Variables

Repetition

Difficulty: 3

'''
Python Challenge 20
David James
2020-07-23

# Ask the user to guess the answer to life, the universe and everything
# Whilst the guess is not correct keep asking
# When the answer is correct, output 'Well done'
'''

print('''
        WARNING: This will repeat for ever or until you guess the correct value.
    ''')

answer = 42
guess = -1

while guess != answer:
# Ask the user to guess a number
    guess = int(input('Guess the answer: '))

# Whilst the guess is not correct keep asking
    if guess == answer:
        print('Correct, well done!')
    else:
        print('Incorrect, try again...')

Challenge 21

Write a program that converts between centimetres, and inches and vice versa, by:

  • asking the user to input a number
  • asking the user to choose between converting from centimeters to inches or from inches to centimeters
  • calculating and outputting the result using functions

Knowledge

Variables

Selection

Functions

Difficulty: 3

TIP
1 inch = 2.54 cm
1 cm = 0.393700787 inches
'''
Python Challenge 21
David James
2020-07-23

Ask for a number.
Ask whether converting from inches to centimetres or vice versa.
Call a function to do the conversion.
Output the conversion.
'''

# Function to convert between inches and centimeters
def convert(number, unit):
    conversion = 2.54
    if unit == 'I':
        print(f"{number} centimeters is {number/conversion} inches")
    elif unit == 'C':
        print(f"{number} inches is {number * conversion} centimeters")

# Ask for a number.
value = float(input('What value do you want to convert? '))

# Ask whether converting from inches to centimetres or vice versa.
measurement = input('Do you want to convert to inches (I) or centimeters (C)? ').upper()

# Call a function to do the conversion.
convert(value, measurement)

Challenge 22

Write a program that:

  • asks the user for the distance (in metres)
  • asks the user for the time (in seconds) that the journey was completed in
  • calculates and outputs the average speed using a function

Knowledge

Variables

Selection

Functions

Difficulty: 3

TIP
speed = distance / time
'''
Python Challenge 22
David James
2020-07-23

Ask for a distance.
Ask for a time.
Call a function to calculate the speed.
Output the speed.
'''

# Function to calculate the average speed
def speed(distance, time):
    return distance/time

# Ask for the distance and time
measuredDistance = float(input('How far was travelled (metres)? '))
measuredTime = float(input('How long was the journey (seconds)? '))

# Calculate the speed
averageSpeed = speed(measuredDistance, measuredTime)

# Output the speed
print(f'You travelled at an average speed of {averageSpeed} m/s.')

Challenge 23

A gardener needs to buy some turf for a project they are working on. The garden is rectangular with a circular flower bed in the middle.

Knowledge

Variables

Selection

Functions

Difficulty: 4

TIP
circle area = Pi × radius²

Write a program that:

  • asks the user for the dimensions of the lawn and the radius of the circle (metres)
  • uses a function to calculate and output the amount of turf needed
'''
Python Challenge 23
David James
2020-07-23

Ask for the length and width of the lawn..
Ask for the radius of the circle.
Call a function to calculate the area of turf.
Output the area of turf.
'''

# Import the radius function from math
from math import pi, ceil

# Function to calculate the area of turf
def turf(length, width, radius):
    areaCircle = pi * radius * radius
    areaTurf = length * width - areaCircle
    return ceil(areaTurf)

# Ask for the length, width and radius
measuredLength = float(input('How long is the lawn in metres? '))
measuredWidth = float(input('How wide is the lawn in metres? '))
measuredRadius = float(input('What is the radius of the flower bed in metres? '))

# Output the area of the turf
print(f'You need {turf(measuredLength, measuredWidth, measuredRadius)} m³ of turf.')

Challenge 24

Write a function that takes two numbers.

The first number indicates the number of spaces that should be displayed and the second indicates the number of Xs that should be displayed on the same line.

Knowledge

Variables

Selection

Repetition

Functions

Difficulty: 4

     X
    XXX
   XXXXX
  XXXXXXX
 XXXXXXXXX
    XXX
    XXX

New write another function that makes multiple calls to your first function and draws the tree picture with Xs.

'''
Python Challenge 24
David James
2020-07-23

Function to display spaces and X's
Function to draw picture
'''

def drawLine(numSpace, numX):
    print(numSpace*' ' + numX*'X')

def drawTree():
    print()
    drawLine(5,1)
    drawLine(4,3)
    drawLine(3,5)
    drawLine(2,7)
    drawLine(1,9)
    drawLine(4,3)
    drawLine(4,3)
    print()

if __name__ == '__main__':
    drawTree()

Challenge 25

Write a sign-up program for an after-school club; it should ask the user for the following details and store them in a file:

  • First name
  • Last name
  • Gender
  • Tutor group

Knowledge

Variables

Selection

File handling

Difficulty: 4

'''
Python Challenge 25
David James
2020-07-23

Ask for first name, last name, gender, tutor group
Store data in a text file
'''

print('=== Sign-up Form ===')

# Ask for the personal details
# Note the use of formatting functions
firstName = input('First name: ').title()
lastName = input('Last name: ').title()
gender = input('Male or Female? ').title()
tutor = input('Tutor group: ').upper()

# Generate the line to be written to the file
# Note the new line character
record = f'{firstName} {lastName}, {gender}, {tutor}\n'

# Open file, create if it does not exist
with open('sign-up.txt', 'a') as f:
    f.write(record)
    f.close()

Challenge 26

Write a maths quiz with three questions.

It must ask the user to input their name at the start.

At the end it should display a message informing the user of their score.

Write a function that saves the user's name and quiz result in a text file.

Knowledge

Variables

Selection

Functions

File handling

Difficulty: 4

'''
Python Challenge 26
David James
2020-07-23

Ask for the users name
Function to create maths questions
Display the users score
Store the name and score in a file
'''

# Import random integer function
from random import randint

# Constants
QUESTIONS = 3

# Generate multiplication question
def question():
    num1 = randint(1,10)
    num2 = randint(1,10)
    response = int(input(f'{num1} × {num2} = '))
    if response == (num1 * num2):
        return 1
    else:
        return 0

# Save score
def saveScore(name, score):
    record = f'{name}: {score} correct\n'
    print(record)
    with open('math-1.txt', 'a') as f:
        f.write(record)
        f.close

if __name__ == '__main__':
    print('=== Maths Quiz I ===')

    user = input('What is your name? ').title()

# Create three questions and add to the file
    total = 0
    for n in range(0,QUESTIONS):
        total = total + question()

# Save users name and score
    saveScore(user, total)

Challenge 27

Extend your maths quiz program from Challenge 26 by including a list of the scores of people that have taken the quiz before.

Knowledge

Variables

Selection

File handling

Difficulty: 5

'''
Python Challenge 27
David James
2020-07-23

Ask for the users name
Displays previous scores
Function to create maths questions
Display the users score
Store the name and score in a file
'''

# Import random integer function
from random import randint

# Constants
QUESTIONS = 3

# Generate multiplication question
def question():
    num1 = randint(1,10)
    num2 = randint(1,10)
    while True:
        try:
            response = int(input(f'{num1} × {num2} = '))
            break
        except ValueError:
            print('Not an integer, try again...')
            continue
    if response == (num1 * num2):
        return 1
    else:
        return 0

# Print scores
def printScores():
    with open('math-2.txt', 'a') as f:
        f.close
    with open('math-2.txt', 'r') as f:
        line = f.readline().strip()
        while line:
            print(line)
            line = f.readline().strip()
        f.close

# Save score
def saveScore(name, score):
    record = f'{name}: {score} correct\n'
    print(record)
    with open('math-2.txt', 'a') as f:
        f.write(record)
        f.close

if __name__ == '__main__':
    print('=== Maths Quiz II ===')

    user = input('What is your name? ').title()

# Create three questions and add to the file
    total = 0
    for n in range(0,QUESTIONS):
        total = total + question()

# Save users name and score
    saveScore(user, total)

# Print the previous scores
    printScores()

Challenge 28

Write a random name generator that asks for the user to input 5 names, stores them in an array and then outputs one of them at random.

Knowledge

Variables

Repetition

Arrays

Difficulty: 5

'''
Python Challenge 28
David James
2020-07-25

Ask for five names
Store the names in an array (list)
Randomly chooses one of the names
'''

# Import random integer function
from random import choice

# Constants
NAMES = 5

def displayTitle():
    print('=== Random Name Generator ===')

def getNames():
    names = []
    for n in range(NAMES):
        name = input('Name: ').title()
        names.append(name)
    return names

def chooseName(names):
    print(choice(names))

if __name__ == '__main__':
    displayTitle()
    usersNames = getNames()
    chooseName(usersNames)

Challenge 29

Write a program that allows the user to create and store a checklist for a holiday.

It should start by asking them the destination of the holiday, how many things they need to pack and how many tasks they need to complete to prepare.

The user should then be able to enter each item they need to pack and each task they need to complete. 

Knowledge

Variables

Repetition

Arrays

File handling

Difficulty: 5

'''
Python Challenge 29
David James
2020-07-25

Holiday Checklist
Ask for the destination
Ask for the number of things to take and how many tasks to complete
Ask for each item and each task
Store the information in a text file
'''

def displayTitle():
    print('=== Holiday Checklist ===')

def getNum(message):
    while True:
        try:
            num = int(input(message))
            break
        except ValueError:
            print('Needs to be an integer...')
            continue
    return num

def getList(message, total):
    listing = []
    for n in range(total):
        item = input(message)
        listing.append(item)
    return listing

def saveChecklist(destination, totalItems, items, totalTasks, tasks):
    with open('checklist.txt', 'w') as f:
        f.write('\n')
        f.write(f'Destination: {destination}\n')
        f.write('\n')
        f.write(f'Items to take: {totalItems}')
        f.write('\n')
        for item in items:
            f.write(f'- {item}')
            f.write('\n')
        f.write('\n')
        f.write(f'Tasks to do: {totalTasks}')
        f.write('\n')
        for task in tasks:
            f.write(f'- {task}')
            f.write('\n')
        f.close

def printChecklist():
    with open('checklist.txt', 'r') as f:
        print(*f.readlines())
        f.close

if __name__ == '__main__':
    displayTitle()

    destination = input('Where are you going? ')

    numItems = getNum('How many items are you taking? ')
    items = getList('Item: ', numItems)
    
    numTasks = getNum('How many tasks do you need to complete? ')
    tasks = getList('Task: ', numTasks)

    saveChecklist(destination, numItems, items, numTasks, tasks)
    printChecklist()

Challenge 30

Improve your maths quiz from Challenge 27 by storing all the questions and possible answers in a two-dimensional array.

Write a function that can be reused to ask each of the questions.

Knowledge

Global variables

Repetition

Functions

2D arrays

Difficulty: 5

'''
Python Challenge 30
David James
2020-07-25

Ask for a name
Display the questions
Ask for an answer
Display correct or the answer
Store results in a file
'''

# Constants
# -------------------------------------------------------------
HEADER = '''
    ---------------------
    Computer Science Quiz
    ---------------------

    '''
QUESTIONS = [
        ['How many bits is one byte', '8'],
        ['How many values can be represented by one byte', '256'],
        ['How many bytes is one kilobyte', '1000'],
        ['How many bytes is one kibibyte', '1024'],
        ]

# -------------------------------------------------------------

# Functions
# -------------------------------------------------------------
def printQuestion(data):
    numQuestions = len(data)
    for q in range(numQuestions):
        print(data[q][0])

def printAnswers(data):
    numQuestions = len(data)
    for q in range(numQuestions):
        print(f'{data[q][0]}: {data[q][1]}')

def askQuestions(data):
    total = 0
    numQuestions = len(data)
    for q in range(numQuestions):
        answer = input(f'{data[q][0]}?\n')
        if answer == data[q][1]:
            print('Correct\n')
            total += 1
        else:
            print(f'Incorrect, the answer is {data[q][1]}\n')
    return total

def createScores():
    with open('compsci.txt', 'a') as f:
        f.close

def saveScores(name, score):
    record = f'{name}: {score}'
    with open('compsci.txt', 'a') as f:
        f.write(record)
        f.write('\n')
        f.close

def printScores():
    with open('compsci.txt', 'r') as f:
        print(*f.readlines())
        f.close

# ---------------------------------------------------------------

# Main Program
# ---------------------------------------------------------------
if __name__ == '__main__':
    createScores() # Creates the scores file if not already existing
    print(HEADER)
    user = input('What is your name? ').title()
    print()
    score = askQuestions(QUESTIONS)
    saveScores(user, score)
    printScores()

Python Challenges

By David James

Python Challenges

30 graduated Python programming challenges

  • 1,200