Please write a Python program that asks the user for the year he was born. Calculate how old the user will be by the end of the current year. Output the users age at the end of the current year and if the user is a teenager at the end of the year (13-19) than also output “teenager” on the same line as the age separated by a “ “..
from datetime import date
birth_year = int(input("Please tell me the year you were born (integer): "))
current_year = date.today().year
age = current_year - birth_year
if age > 12 and age < 20:
That's a nice challenging question :)
Often if a question proves difficult to grade it's easier to ask a different question with the same pedagogical goals. For example, if you're just interested in whether a student can extract information from a date object, maybe you'd be happy
with a question like:
Write a function age_at_year(year_of_birth, now) that takes as parameters an integer year_of_birth and a date object now and returns the age of the person with the given birth year at the end of the 'now' year.
However, if what you're trying to test in your question is the use of date.today() then you have a problem because the expected output will fundamentally vary with time, preventing the use of literal strings for the Expected outputs.
There are two ways to grade the question in the form you're currently asking it.
- Use Twig to compute the expected output
- Use a template grader
1. Using Twig
If you check the Twig All checkbox, the Twig template engine, which is usually used only to expand the question template, is also applied to the question text and all the test cases as well. So you could embed Twig code in the Expected field of each test case, such as the following (which assumes the use of the python3_w_input question type, which echoes the standard input to standard output):
This approach has the advantage that you can still click the Use as example checkbox on any test and have the correct output showing in the For example table regardless of when the question is run. The downside is that you have to write the answer in Twig code as well as in your sample answer, and you have to repeat it in every test case.
2. Using a template grader
If you totally trust your sample answer (dangerous!), you can use a template grader to compare the output from the student's code with that from your code. There is some discussion of that approach in this forum discussion and one of my postings there includes the xml for a question type that grades code using the sample answer. However, I don't recommend this approach for newcomers to CodeRunner nor for the faint-of-heart.