More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
Python IDE Dashboard

Automatic Petrol Pump Algorithm

petrol-pumpIn this challenge we will implement an algorithm to be used in an Automatic Petrol Pump to interact with the customer and calculate the total cost of filling up their vehicle.

The fuel options and tariffs at this petrol station are as follows:

  • Unleaded: £1.17 per litre,
  • Super Unleaded: £1.27 per litre,
  • Diesel: £1.21 per litre,
  • Diesel Premium: £1.34 per litre,

The petrol pump will interact with the customer by asking the following questions:

  • What fuel do you require?
  • Do you want to fill up (full tank capacity) and if not how many litres of fuel do you require?

The petrol pump will use this information provided by the customer as well as the tariffs provided above to calculate the total cost of this order.

To simulate a real life situation, we will assume that the customer’s vehicle has a tank capacity of 55 litres.
We will also assume that when the customer reaches the petrol station, the vehicle still has some fuel left. To simulate this we will generate a random number between 0 and 55. This number will represent the number of litres left in the tank before filling up.

If the customer requires a full tank, the algorithm will calculate the quantity needed as follows:

Quantity Needed = Full Tank Capacity – Current Fuel Level

If the customer specifies a desired quantity (in litres), the algorithm will fill up the tank with the required quantity. However, if the required quantity combined with the current level of fuel in the tank exceeds the full tank capacity, the required quantity will be replaced to just the quantity that is needed using the same formula as mentioned above.

Petrol Pump Algorithm: Pseudocode


The suggested pseudocode for our Automatic Petrol Pump is as follows:

currentFuelLevel = RANDOM NUMBER BETWEEN 1 AND 55
OUTPUT "You have " + currentFuelLevel + " litres left in your tank."
 
tankCapcacity = 55 
unleadedPrice = 1.17
superUnleadedPrice = 1.27
dieselPrice = 1.21
dieselPremiumPrice = 1.34

OUTPUT " ---- Our Tariffs ----"
OUTPUT "A - Unleaded: £" + unleadedPrice + " per litre"
OUTPUT "B - Super Unleaded: £" + superUnleadedPrice + " per litre"
OUTPUT "C - Diesel: £" + dieselPrice + " per litre"
OUTPUT "D - Diesel Premium: £" + dieselPremiumPrice + " per litre"

fuelChoice =  INPUT("What fuel do you need?")
pricePerLitre = 0
IF fuelChoice == "A" THEN
	pricePerLitre = unleadedPrice
ELSEIF fuelChoice == "B" THEN
	pricePerLitre = superUnleadedPrice
ELSEIF fuelChoice == "C" THEN
	pricePerLitre = dieselPrice
ELSEIF fuelChoice == "D" THEN
	pricePerLitre = dieselPremiumPrice
ELSE
	OUTPUT "Invalid Option"
END IF

fullTank = INPUT "Would you like to fill up to a full tank?"
IF fullTank == "Yes" THEN
	quantityNeeded = tankCapacity – currentFuelLevel
ELSE
	quantityNeeded = INPUT("How many litres do you need?")
	IF (currentFuelLevel + quantityNeeded) > tankCapacity THEN
		quantityNeeded = tankCapacity – currentFuelLevel
	END IF
END IF

cost =  quantityNeeded * pricePerLitre

OUTPUT "Fuel Choice: " + fuelChoice
OUTPUT "Quantity: " + quantityNeeded + " litres."
OUTPUT "Total Cost: £" + cost

Your task is to use this pseudocode to implement this algorithm using Python.

Extension Task


Add some input validation to ensure that, if the user does not provide a valid answer, the same question is being asked again.

You should use:

  • A Lookup Check to check that the user is answering either A, B, C or D when being asked about their fuel choice?
  • A Lookup Check to check that the user is answering either Yes or No to the question: Would you like to fill up to a full tank?
  • A Type Check to ensure that the user is entering a valid positive number when asked about the number of litres they do require.

Pseudocode for Lookup validation

fullTank = INPUT "Would you like to fill up to a full tank?"
WHILE fullTank NOT IN ["Yes", "No"]
	OUTPUT "Invalid Answer. Please answer the question with Yes or No"
	fullTank = INPUT "Would you like to fill up to a full tank?"
END WHILE

petrol-station

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,

ATM Algorithm

debit-cardsAn ATM, a.k.a. Cash Withdrawal Machine, uses a computer program to interact with the customer and count the number of banknotes to dispense based on the customer’s requested amount.

In the UK, ATM’s tend to only stock £20 banknotes and £10 banknotes and apply the following rules:

  • The minimal amount that can be withdrawn is £10,
  • The maximal amount that can be withdrawn is £200,
  • The amount to be withdrawn must be a multiple of 10 e.g. £10, £20, £30, £40, … £180, £190, £200.

Quotient (DIV) and Remainder (MOD)


To calculate how many £20 banknotes and how many £10 banknotes correspond to the requested amount, the ATM program uses two arithmetic operators called DIV and MOD.

The quotient (DIV) returns the result of the whole division. For instance:

70 DIV 20 = 3

The remainder (MOD) returns the remainder of the whole division. For instance:

70 MOD 20 = 10

By using these operators we can deduct that £70 pounds will result in:

  • 70 DIV 20 = 3 banknotes of £20
  • 70 MOD 20 = 10 (= 1 banknote of £10)

Note that in Python the DIV operator is // whereas the MOD operator is %.
For instance:

  • quotient = 70 // 20
  • remainder = 70 % 20

Also to find out if a number is a multiple of 10, we can check if number MOD 10 == 0. Effectively, if the remainder of dividing this number by 10 is null, we can conclude that this number is a multiple of 10.

ATM Algorithm: Pseudocode


The suggested pseudocode for our ATM is as follows:

WHILE TRUE
   DISPLAY "Welcome to Python Bank ATM - Cash Withdrawal"
   amount = INPUT "How much would you like to withdraw today?"
   IF (amount MOD 10) != 0 THEN
      DISPLAY "You can only withdraw a multiple of ten!"
   ELSE
      IF amount<10 OR amount>200 THEN
         DISPLAY "You can only withdraw between £10 and £200"
      ELSE
         notes20 = amount DIV 20
         notes10 = (amount MOD 20) / 10
         DISPLAY "Collect your money: "
         DISPLAY "    >> £20 Banknotes: " + notes20
         DISPLAY "    >> £10 Banknotes: " + notes10
         DISPLAY "Thank you for using this Python Bank ATM."
         DISPLAY "Good Bye."
      END IF
   END IF
END WHILE

Your task is to use this pseudocode to implement this algorithm using Python.

Extension Task 1


The bank reloads the ATM to its full capacity every morning. The ATM has a full capacity of £1,000.
Adapt this code so that:

  1. When you run the code, the ATM starts with a full capacity of £1,000.
  2. After each withdrawal, take away the amount withdrawn from the ATM total capacity.
  3. If the ATM is empty a message is displayed to inform that the ATM is not operational.
  4. If the ATM is not empty, change your code to check that it contains enough cash left to meet the amount requested by a customer before dispensing the banknotes.
  5. If the customer requested amount cannot be met, inform the customer of the maximum amount that is still available to withdraw.

Extension Task 2


When the bank reloads the ATM, it ensures that the ATM contains exactly:

  • 30 banknotes of £20.
  • 40 banknotes of £10.

Adapt your code to ensure that the ATM checks that there are enough banknotes of £20 or £10 before dispensing the banknotes. Note that if the ATM runs out of £20 banknotes, it may still be able to dispense the requested amount using £10 banknotes instead.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

Maths Homework Generator

maths-operatorsIn this challenge we have created a client-side script using HTML, CSS and JavaScript to help a Maths teacher create homework worksheets for their class.

Our HTML page uses a web form, for the teacher to select various options based on the Maths skills they want to cover and the desired level of difficulty.

The JavaScript code attached to the “Create Worksheet” button is retrieving the user inputs from the various drop down lists. It then uses these to generate list of arithmetic equations and display these on the HTML page.

HTML, CSS & JavaScript Code

See the Pen Maths Homework Generator by 101 Computing (@101Computing) on CodePen.

Your Task


Reverse engineer this JavaScript code to understand how it works. For instance can you identify:

  • The purpose of the getDropDownListValue() function defined on lines 1 to 4?
  • The purpose of lines 7 to 49?
  • The purpose of the switch case on lines 12 to 33?
  • The purpose of the for loop on line 37?
  • The purpose of lines 38, 39 and 40?
  • The purpose of line 42?
  • The purpose of line 44?

Challenge #1: 2 or 3 operands per equation?


Now that you understand how this code works, complete it in order for the Maths teacher to be able to chose the number of operands per equations. For instance, if the Maths teacher chooses two operands it will generate equations such as “2+7”. If the teacher chooses three operands, an example of equation could be “2+4-7”.

Challenge #2: Find the missing operand


Change the code to generate equations with a missing operand. For instance: “2 + ??? = 9”

Challenge #3: Linear Equations


Change the code to generate linear equations. For instance: “3x + 2 = 11”

Challenge #4: Quadratic Equations


Change the code to generate quadratic equations. For instance: “4x2 + 5x + 2 = 0″

Prolog – Sorting Hat Challenge

hogwarts-sorting-hatProlog is a language built around the Logical Paradigm: a declarative approach to problem-solving.

There are only three basic constructs in Prolog: facts, rules, and queries.

A collection of facts and rules is called a knowledge base (or a database) and Prolog programming is all about writing knowledge bases. That is, Prolog programs simply are knowledge bases, collections of facts and rules which describe some collection of relationships that we find interesting.

So how do we use a Prolog program? By posing queries. That is, by asking questions about the information stored in the knowledge base. The computer will automatically find the answer (either True or False) to our queries.

Source: http://www.learnprolognow.org/

Knowledge Base (Facts & Rules)


Check the following knowledge base used by the Sorting Hat in the Harry Potter story:

/* Facts */
brave(harry).
loyal(harry).
loyal(cedric).
loyal(luna).
fair(harry).
fair(hermione).
patient(cedric).
clever(cedric).
clever(hermione).
curious(luna).

friend(harry,hermione).
friend(harry,ron).
enemy(harry,malfoy).

/* Rules */
belongToGriffindor(X):-brave(X), loyal(X).
belongToGriffindor(X):-friend(harry,X).
belongToHufflepuff(X):-patient(X), loyal(X).
belongToRavenclaw(X):-curious(X).
belongToSlytherin(X):-enemy(harry,X),\+loyal(X).

Note that \+ means NOT

Queries


We can now query this database. For each of the queries listed below, what do you think the computer will return?

True or False Queries:

?-belongToGriffindor(harry).
?-belongToGriffindor(malfoy).
?-belongToGriffindor(hermione).
?-belongToSlytherin(hermione).
?-belongToSlytherin(malfoy).
?-belongToHufflepuff(cedric).

Other Queries:

?-belongToGriffindor(harry).
?-brave(X).
?-fair(X).
?-friend(harry,X).
?-belongToGriffindor(X).
?-belongToSlytherin(X).

Task #1: Try It Online


Test all of the above queries online to see what they return:
https://swish.swi-prolog.org/p/Harry%20Potter%20-%20Sorting%20Hat.pl

Task #2: Griffindor or Ravenclaw?


Can you add a few more facts for a student called “Cho-Chang” who would meet all the requirements to belong to both Griffindor and Ravenclaw.

As a student should only belong to one house, update the rule for belongToRavenclaw() to make sure this rule only returns True for students who are curious but do not already belong to Griffindor.

Extension Task:


Add a few facts and rules to this knowledge base. Create your own queries using the new facts and rules you have added.

Tagged with:

Python Syntax

python-logo
This page summarises the syntax of the Python language. When using Python always remember two key rules:

  • Rule #1: Python is white-space dependent; code blocks are indented using spaces.
  • Rule #2: Python language is case sensitive. It matters for variables, functions and any keyword in general.
Input / OutputSelection (IF Statements)Iteration (Loops)ListsSubroutinesFile HandlingInput Validation

Annotations

# Single Line Comment

"""
Multi-line comment
by 101Computing.net
"""

Variables & Assignment Operator

myInteger = 1
myFloat = 3.14
myString = "Hello World"
myList = ["John","James","Laura"]

Input

# Text Input
playerName = input("What's your name?")

# Number/Integer Input
playerAge = int(input("How old are you?"))

# Number/Decimal Input
cost = float(input("How much does it cost?"))

Output

print("Hello World")

print("Hello " + playerName)

print("You are " + str(playerAge) + " years old.")

Casting

str(100)	# To convert a value to a string

int("100")	# To convert from a string to an integer

float("3.14")	# To convert from a string to a float

score = 5
print("Your score = " + str(score))

String Manipulation

# String Concatenation
playerName = "John"
myString = "Hello " + playerName + "!"

score = 5
print("Your score = " + str(score))


# Changing the case of a string
myString = "Hello World"
print(myString.upper())   # to print HELLO WORLD
print(myString.lower())   # to print hello world


# Extracting Characters of a String
myString = "Hello World"

print(myString[0])	# "H"
print(myString[0:5])	# "Hello"
print(myString[-5:])	# "World"


# Finding out the length of a string
print(len(myString))	# 11


# Splitting a string into a list of values
names = "John;James;Laura"
data = names.split(";") 
print(data[0]) # This would print: John

Random Library

#Import the random library
import random

#Generate a random number between 1 and 100
randomNumber = random.randint(1,100)

#Pick a value in a list at random
names = ["John","James","Luke"]
randomName = random.choice(names)

Arithmetic Operators

x = a + b	# Add
x = a – b	# Take away
x = a / b	# Divide
x = a * b	# Multiply
x = a ** 2	# to the power of
x = a // b    	# Quotient DIV
x = a % b   	# Remainder MOD

x += 1 # Increment x by 1
x -= 1 # Decrement x by 1
x *= 2 # Multiply x by 2
x /= 2 # Divide x by 2

Rounding a Number

pi = 3.14159
pi2 = round(pi,2)

print("Pi rounded to two decimal places: " + str(pi2))   # 3.14

IF Statements / Selection


Warning: Use the 4 spaces rule!!! (Indentation)

if numberOfLives == 0:
    print("Game Over!")


if number == 7:
    print("Seven")
else:
    print("Not seven!")


if number < 0:
    print("Negative Number")
elif number == 0:
    print("Zero")
else:
    print("Positive Number")


if number == 7:
    print("Seven")
elif number == 8:
    print("Eight")
elif number == 9:
    print("Nine")
else:
    print("Not seven, eight or nine")

Comparison Operators


The main comparison operators are:

Comparison Operator Meaning Example
== is equal to 4==4
!= is different from 4!=7
< is lower than 3<5
> is greater than 9>2
<= is lower or equal to 3<=5
5<=5
>= is greater or equal to 9>=2
5>=5

Comparison operators are used to check if a condition is true or false.

Boolean operators such as AND, OR and NOT can also be used to check multiple conditions at the same time.

e.g.

if timer>0 and numberOfLives>0:
    print("Carry on playing!")
else:
    print("Game Over")

Loops / Iteration


Warning: Use the 4 spaces rule!!! (Indentation)

for i in range(1,11):   # Using a range
    print i


for i in range(0,101,5):   # Using a step - e.g. count in 5
    print i

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
#Iterate through all the values of a list
for i in range(0,len(daysOfTheWeek)):
    print(daysOfTheWeek[i])

#Iterate through all the values of a list - Alternative method
for day in daysOfTheWeek :
    print(day)


string = "Hello World"
for character in string:  # Using a string
    print(character)


i=0
while i<=100:
    print i
    i = i + 1

# To exit from a loop at any time:
    break

Lists

days = ["Mon","Tue","Wed","Thu","Fri","Sat"]

days.append("Sun")

print(days[0]) 	 # "Mon"
print(days[1]) 	 # "Tue"
print(days[2]) 	 # "Wed"
…
print(days[6]) 	 # "Sun"

#Finding out the number of items in a list (length of a list)
print(len(days)) # 7

#Iterate through all the values of a list
for i in range(0,len(days)):
    print(days[i])

#Iterate through all the values of a list - Alternative method
for value in days:
    print(value)

Procedures


Warning: Use the 4 spaces rule!!! (Indentation)

def displayBanner(message) :
    print("---------------")
    print(message)
    print("---------------")

displayBanner("Hello World!")

Functions


Warning: Use the 4 spaces rule!!! (Indentation)

def add(x, y) :
    sum = x + y
    return sum

total = add(1,3)
print(total)  # this would display 4

File Handling – (Over)Writing a text file

file = open("myTextFile.txt","w")

file.write("Hello World\n");
  
file.close()

Be careful, when using the write command, you are overwriting the content of your file. If instead of overwriting the content of your file you want to append (write at the end of the file) check the next tab: “Append to a text file”.

File Handling – Appending data to a text file

file = open("myTextFile.txt","a")

file.write("Hello World\n");
  
file.close()

File Handling – Reading a text file line by line

file = open("myTextFile.txt","r")

for line in file:
    print(line)
  
file.close()

File Handling – Reading a CSV file line by line


CSV files (Comma Separated Values) are text files that store data where each record is stored on a line and each field is separated using a divider symbol such as a comma “,”, a semi-colon “;” or a pipe “|”.

In this case when reading a line of the text file you can use the split() method to then access each field one by one.

file = open("myTextFile.txt","r")

for line in file:
    data = line.split(";")
    print(data[0] + " - " + data[1] + " - " + data[2])
  
file.close()

File Handling – Reading a text file using a list

file = open("myTextFile.txt","r")

lines = file.readlines()

file.close()

for line in lines:
  print(line)

Input Validation: Presence Check

name = input("Enter your name:")

if name=="":
    print("Empty name!")
else:
    print("Thank you!")

Input Validation: Type Check – Integer?

number = input("Type a number:")

if number.isdigit():
    print("This is a number")
else:
    print("This is not a whole number")

Input Validation: Range Check

number = int(input("Type a number between 1 and 5:"))

if number>=1 and number<=5:
    print("Valid number")
else:
    print("Invalid number")

Input Validation: Lookup Check

drive = input("Can you drive?").lower()

if drive in ["yes","no"]:
    print("Valid answer")
else:
    print("Invalid answer")

Input Validation: Character Check

email = input("Type your e-mail address:")

if "@" in email:
    print("Valid e-mail address")
else:
    print("Invalid e-mail address")

Input Validation: Length Check

password = input("Type a password:")

if len(password)>=8:
    print("Valid password")
else:
    print("Invalid password")

Try Again! Using a While Loop:

name = input("Enter your name:")

while name=="":
    print("You must enter your name! Please try again!")
    name = input("Enter your name:")

print("Welcome " +  name)

You can investigate more advance approaches to implement validation subroutines on this blog post.

Othello Game

othello-gridOthello (a.k.a. Reversi) is a strategy board game for two players, played on an 8×8 board. There are sixty-four identical game pieces called discs which are white on one side and black on the other. Players take turns placing discs on the board with their assigned color facing up. During a play, any discs of the opponent’s color that are in a straight line and bounded by the disc just placed and another disk of the current player’s color are turned over to the current player’s color.

The object of the game is to have the majority of disks turned to display your color when the last playable empty square is filled.

Read more about the rules of the Othello game: https://en.wikipedia.org/wiki/Reversi.

Othello Challenge


In this challenge you will use HTML, CSS, and JavaScript to complete this game of Othello for two players.

You will first need to reverse-engineer the code provided. The code so far is used to:

  • Display the 8×8 grid using HTML and CSS.
  • Add a disc on the grid when the user clicks on a cell of the grid using the selectCell()
    function in JavaScript.
  • Refresh the grid on the screen using the refreshGrid() function in JavaScript.

The code provided uses a variable called grid, use to store a two-dimensional array (8×8) of integer values. Within this array, a 0 represents an empty place, a 1 represents a white disc and a 2 represents a black disc.

Your Task


Your task consists of:

  • Amend the selectCell() function in JavaScript in order to:
    • Check if user is allowed to place a disc on the selected cell.
    • Reverse any discs of the opponent’s color that are in a straight line and bounded by the disc just placed and another disk of the current player’s color.
    • Count the number of white and black discs and display the score on the page.
    • Check if the grid is full.
  • Add code to the resetGrid() JavaScript function to start a new game with an empty grid.

HTML, CSS and JavaScript Code

See the Pen OthelloChallenge by 101 Computing (@101Computing) on CodePen.

Tagged with: , ,

Moroccan Mosaic

ZelligeMoroccan mosaic, aka Zellige (الزليج‎‎), is a form of Islamic art and one of the main characteristics of Moroccan architecture. It consists of geometrically patterned mosaics, used to ornament walls, ceilings, fountains, floors, pools and tables. Each mosaic is a tilework made from individually chiseled geometric tiles set into a plaster base.

You can google examples of Zellige using this link.

In this challenge, we will investigate how to create our own mosaic using various geometric patterns. We will use Python Turtle to draw a regular polygon (e.g. pentagon, hexagon, etc.) and repeat and rotate this shape several times to create a circular pattern/mosaic.

Mosaic Code: Using one polygon shape:


Amend the code below by changing the value of the three parameters used by the drawMosaic() function. View the impacts of these changes on your final mosaic.

python-turtle-mosaics-1

Mosaic Code: Combining two polygon shapes:


The code below combines two different types of regular polygons to create a more complex pattern:

python-turtle-mosaics-2

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,

2D Shapes using Python Turtle

In this challenge we will use Python Turtle to draw regular polygons including:

  • An equilateral triangle
  • A square
  • A pentagon
  • An hexagon
  • etc.

Did you know?


In Euclidean geometry, a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Regular polygons may be convex or star.

Convex Regular Polygons


Looking at the following three polygons, we can work out a formula to calculate the external angle of a convex regular polygon based on its number of sides.
exterior-angle-triangle

exterior-angle-square

exterior-angle-pentagon

Exterior Angle = 360 / number of sides

Python Code


Based on this formula we have implanted a function called drawPolygon() which takes one parameter called numberOfSides. This function will draw the corresponding convex regular polygon on screen.

Star Regular Polygons


star-polygons
Your challenge consists of coding a similar function, called drawStar(), used to draw star regular polygons on the screen. This function will take two parameters called numberOfSides and multiplier.

This time we will use a different formula to calculate the exterior angle:

Exterior Angle = multiplier * (360 / number of sides)

You can test your code with the following parameter values:

Star # Number of Sides Multiplier
#1 5 2
#2 8 3
#3 9 4
#4 10 3
#5 12 5
Tagged with:

Print Command Quiz

The first instruction you will most likely learn when using Python is the print() instruction. It is used to display/output a message on screen.

print("Hello World")

Using Variables
The print command can be used to output the content of a variable:

username="admin"
print("You are logged as:")
print(username)

Using String Concatenation
You can join multiple strings together (string concatenation using +) to print them on a single line:

username="admin"
print("You are logged as:" + username)

Casting numbers (e.g integers) into string and vice-versa:
You can convert (cast) a number (e.g integer) into a string using the str() function or convert/cast a string into an integer using the int() function:

score=10
print("Your score:" + str(score))

Take the Quiz! (open full screen)


How Old is Your Cat?

catIn this challenge we are going to create a cat’s age convertor find out how old a cat is in “human years”. This is very useful to understand more about cats and the care they need and to find out at what stage of life a cat is.
To convert the age of a cat in human years you have to do the following:

  • Year 1 counts for 15 Human Years
  • Year 2 counts for 9 Human Years
  • Thereafter each year counts for 4 Human Years

For example:

  • A 1 year old cat is 15 Human Years old,
  • A 2 years old cat is 15 + 9 = 24 Human Years old,
  • A 3 years old cat is 15 + 9 + 4 = 28 Human Years old,
  • A 4 years old cat is 15 + 9 + 4 + 4 = 32 Human Years old,
  • A 5 years old cat is 15 + 9 + 4 + 4 + 4= 36 Human Years old,
  • A 10 years old cat is 15 + 9 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 = 56 Human Years old.

You can check the full cat’s age conversion chart at the bottom of this post.

Your Challenge

Complete the following code to ask the user to input the age of a cat in years and return the equivalent in human years.

Extension #1

Amend your code so that it also works for cats under 1 year old. In this case you will have to ask for the cat’s age in months and use the conversion chart below (At the bottom of this post) to return the cat’s age in human years.

Extension #2

The stages of life of a cat are as follows:

  • Kitten – from birth to 6 months,
  • Junior – from 7 months to 2 years,
  • Prime – from 3 years to 6 years,
  • Mature – from 7 years to 10 years,
  • Senior – from 11 years to 14 years,
  • Geriatic – from 15 years above.

Extend your code to tell the end-user what stage of life their cat’s age is corresponding to.

Extension #3

Create another program where the user enters their age in human years and the program tells the user how old they would be if they were a cat!

Cat’s age conversion chart:

Life Stage Cat years Human years
Kitten2 months9 to 10 months
3 months2 to 3 years
4 months5 to 6 years
5 months8 to 9 years
6 months10 years
Junior8 months13 years
1 year15 years
2 years24 years
Prime3 years28 years
4 years32 years
5 years36 years
6 years40 years
Mature7 years44 years
8 years48 years
9 years52 years
10 years56 years
Senior11 years60 years
12 years64 years
13 years68 years
14 years72 years
Geriatric15 years76 years
16 years80 years
17 years84 years
18 years88 years
19 years92 years
20 years96 years
21 years and above100 years
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,