Skip to content
Advertisement

How to use if and else statements to achieve Age Classifier program

I have an assignment in my Python class. It says:

Write a program that asks the user to enter a person’s age. The program should display a message indicating whether the person is an infant, child, teenager, or adult. Here are the following guidelines:

  • If the person is 1 year old or less, he or she is an infant.
  • If the person is older than 1 year, but younger than 13 years, he or she is a child.
  • If the person is at least 13 years old, but less than 20 years old, he or she is a teenager.
  • If the person is at least 20 years old, he or she is an adult.

Here’s what I have so far. I’m assuming you use if and else statements.

JavaScript

Problem is, when I enter a number, example, the number ‘4’, the program runs as so:

JavaScript

That is all it reads to me. So how do I fix this? Because I thought I was on the right track.

Advertisement

Answer

Check out the use of chained if statements using the terms if, elif and else:

JavaScript

It seems like there are two points you should be learning from this exercise. The first is how to chain together if/elif/else statements. It’s more efficient to do this than to evaluate each clause separately. As you can see above, you do this by using ‘if’ on the first statement, ‘elif’ on the following statements, an ‘else’ on the final statement.

This is also useful for error checking. You could do something as follows:

JavaScript

The second is the difference between < > and <= >=. Notice the assignment classifies someone as an infant if they are under the age of 1. This does not include the age of one, only people who have not yet reached the age of 1, therefore you would use ‘< 1’ to get everything up to 364 days old.

This is different than when it classifies someone who is ‘at least’ 13 as a teenager. This means they can be 13 or above, therefore you would use ‘>= 13’.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement