简体   繁体   English

为什么我的代码在问题中多了一行?

[英]Why does my code create an extra line in problem?

I am on day 4 of HackerRank's 30 days of code and I am having a problem where the output will create an extra line.我在 HackerRank 的 30 天代码的第 4 天,我遇到了一个问题,即 output 将创建一个额外的行。 I have checked other's code but they are incredibly similar to mine and i can't find the problem我检查了其他人的代码,但它们与我的非常相似,我找不到问题所在

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("")

I assume it's due to your last line.我认为这是由于你的最后一行。 As print function will add a new line to the output and print("") will simply add a new line.因为print function 会在 output 中添加一个新行,而print("")只会添加一个新行。

The problem is the last statement.问题是最后一句话。 print("") will always print an empty string at the end of the for loop which will have an empty line at the end of the last iteration. print("")将始终在 for 循环的末尾打印一个空字符串,在最后一次迭代结束时将有一个空行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM