我用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版本中,您必须使用括号,如下所示:

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

其他回答

如果你使用的是python 3.6或最新版本, f弦是最好的,也是最简单的

print(f"{your_varaible_name}")

两个

第一个

>>> births = str(5)
>>> print("there are " + births + " births.")
there are 5 births.

当添加字符串时,它们连接在一起。

第二个

此外,字符串的format (Python 2.6及更新版本)方法可能是标准方式:

>>> births = str(5)
>>>
>>> print("there are {} births.".format(births))
there are 5 births.

这种格式方法也可以用于列表

>>> format_list = ['five', 'three']
>>> # * unpacks the list:
>>> print("there are {} births and {} deaths".format(*format_list))  
there are five births and three deaths

或字典

>>> format_dictionary = {'births': 'five', 'deaths': 'three'}
>>> # ** unpacks the dictionary
>>> print("there are {births} births, and {deaths} deaths".format(**format_dictionary))
there are five births, and three deaths

编辑:

它是2022年,python3现在有f字符串。

>>> x = 15
>>> f"there are {x} births"
'there are 15 births'

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

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

# 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 "There are %d births" % (births,)

或者在这个简单的例子中:

print "There are ", births, "births"

从python 3.6开始,你可以使用文字字符串插值。

births = 5.25487
>>> print(f'If there was a birth every 7 seconds, there would be: {births:.2f} births')
If there was a birth every 7 seconds, there would be: 5.25 births