Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 100+ Python challenging programming exercises.txt #149

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions 100+ Python challenging programming exercises.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2371,5 +2371,47 @@ solutions=solve(numheads,numlegs)
print solutions

#----------------------------------------#
Level: Easy
Question:
Write a Person Class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative; if a negative argument is passed as initialAge, the constructor should set age to 0 and print "Age is not valid, setting age to 0.". In addition, you must write the following instance methods:

1. yearPasses() should increase the instance variable by 1.
2. amIOld() should perform the following conditional actions:
* If age < 13, print "You are young.".
* If age > or equal to 13 and age < or equal to 18, print "You are a teenager.".
* Otherwise, print "You are old.".

(credit: HackerRank (30 days of Code))

Answer:

class Person:
def __init__(self,initialAge):
self.age = initialAge

def amIOld(self):
if self.age<13:
if self.age<0:
self.age=0
print("Age is not valid, setting age to 0.")
print("You are young.")
elif 13<=self.age<18:
print("You are a teenager.")
else:
print("You are old.")

def yearPasses(self):
self.age+=1

t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")
#----------------------------------------#