我用python计算出如果每7秒出生一个孩子5年内会有多少个孩子出生。问题在我的最后一行。我如何得到一个变量的工作时,我打印文本的任何一方?

这是我的代码:

currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60

# seconds in a single day
secondsInDay = hours * minutes * seconds

# seconds in a year
secondsInYear = secondsInDay * oneYear

fiveYears = secondsInYear * 5

#Seconds in 5 years
print fiveYears

# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7

print "If there was a birth every 7 seconds, there would be: " births "births"

当前回答

从Python-3.8开始,你可以使用带有变量名打印的f-string !

age = 19
vitality = 17
charisma = 16
name = "Alice"
print(f"{name=}, {age=}, {vitality=}, {charisma=}")
# name='Alice', age=19, vitality=17, charisma=16

命名错误在这里几乎是不可能的!如果您添加、重命名或删除一个变量,您的调试打印将保持正确 调试行非常简洁 不要担心对齐。第四个论点是魅力还是活力?好吧,你不在乎,不管它是正确的。

其他回答

在当前的python版本中,您必须使用括号,如下所示:

print ("If there was a birth every 7 seconds", X)

在中间用,(逗号)就可以了。

为了更好地理解,请参阅下面的代码:

# Weight converter pounds to kg

weight_lbs = input("Enter your weight in pounds: ")

weight_kg = 0.45 * int(weight_lbs)

print("You are ", weight_kg, " kg")

在打印时使用,分隔字符串和变量:

print("If there was a birth every 7 seconds, there would be: ", births, "births")

,打印功能用一个空格分隔项目:

>>> print("foo", "bar", "spam")
foo bar spam

或者更好的使用字符串格式:

print("If there was a birth every 7 seconds, there would be: {} births".format(births))

字符串格式是更强大的,并允许你做一些其他的事情,如填充,填充,对齐,宽度,设置精度等。

>>> print("{:d} {:03d} {:>20f}".format(1, 2, 1.1))
1 002             1.100000
  ^^^
  0's padded to 2

演示:

>>> births = 4
>>> print("If there was a birth every 7 seconds, there would be: ", births, "births")
If there was a birth every 7 seconds, there would be:  4 births

# formatting
>>> print("If there was a birth every 7 seconds, there would be: {} births".format(births))
If there was a birth every 7 seconds, there would be: 4 births

你可以使用字符串格式化来做到这一点:

print "If there was a birth every 7 seconds, there would be: %d births" % births

或者你可以给print多个参数,它会自动用一个空格分隔它们:

print "If there was a birth every 7 seconds, there would be:", births, "births"

使用字符串格式

print("If there was a birth every 7 seconds, there would be: {} births".format(births))
 # Will replace "{}" with births

如果你做一个玩具项目,使用:

print('If there was a birth every 7 seconds, there would be:' births'births) 

or

print('If there was a birth every 7 seconds, there would be: %d births' %(births))
# Will replace %d with births