Skip to content

Commit b5d74c1

Browse files
Update 100+ Python challenging programming exercises.txt
An easy hackerrank challenge from 30 days of Code.
1 parent 478f4df commit b5d74c1

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

β€Ž100+ Python challenging programming exercises.txt

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2371,5 +2371,47 @@ solutions=solve(numheads,numlegs)
23712371
print solutions
23722372

23732373
#----------------------------------------#
2374+
Level: Easy
2375+
Question:
2376+
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:
2377+
2378+
1. yearPasses() should increase the instance variable by 1.
2379+
2. amIOld() should perform the following conditional actions:
2380+
* If age < 13, print "You are young.".
2381+
* If age > or equal to 13 and age < or equal to 18, print "You are a teenager.".
2382+
* Otherwise, print "You are old.".
2383+
2384+
(credit: HackerRank (30 days of Code))
2385+
2386+
Answer:
2387+
2388+
class Person:
2389+
def __init__(self,initialAge):
2390+
self.age = initialAge
2391+
2392+
def amIOld(self):
2393+
if self.age<13:
2394+
if self.age<0:
2395+
self.age=0
2396+
print("Age is not valid, setting age to 0.")
2397+
print("You are young.")
2398+
elif 13<=self.age<18:
2399+
print("You are a teenager.")
2400+
else:
2401+
print("You are old.")
2402+
2403+
def yearPasses(self):
2404+
self.age+=1
2405+
2406+
t = int(input())
2407+
for i in range(0, t):
2408+
age = int(input())
2409+
p = Person(age)
2410+
p.amIOld()
2411+
for j in range(0, 3):
2412+
p.yearPasses()
2413+
p.amIOld()
2414+
print("")
2415+
#----------------------------------------#
23742416

23752417

0 commit comments

Comments
 (0)