python-3.x 为什么我的代码在problem中创建了一个额外的行?

vuktfyat  于 2023-01-06  发布在  Python
关注(0)|答案(2)|浏览(120)

我在第4天的HackerRank的30天的代码,我有一个问题,输出将创建一个额外的行。我已经检查了别人的代码,但他们是令人难以置信的相似,我找不到问题

class Person:
    def __init__(self,initialAge):
        # Add some more code to run some checks on initialAge
        if (initialAge > 0):
            self.initialAge = initialAge
        else:
            self.initialAge = 0
            print ("Age is not valid, setting age to 0")
    def amIOld(self):
        # Do some computations in here and print out the correct statement to the console
        if (self.initialAge < 13):
            print("You are young.")
        elif (self.initialAge >= 13 and self.initialAge < 18):
            print("You are a teenager")
        else: 
            print("You are old")
    def yearPasses(self):
        # Increment the age of the person in here
        self.initialAge = self.initialAge + 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("")
jgovgodb

jgovgodb1#

我想这是由于你的最后一行。因为print函数将添加一个新行到输出和print("")将简单地添加一个新行。

m1m5dgzv

m1m5dgzv2#

问题出在最后一条语句上。print("")总是在for循环的末尾打印一个空字符串,而在最后一次迭代的末尾打印一个空行。

相关问题