我用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"

当前回答

使用字符串格式

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

其他回答

如果你在字符串和变量之间使用逗号,就像这样:

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

我将您的脚本复制并粘贴到一个.py文件中。我用Python 2.7.10运行它,并收到相同的语法错误。我还在Python 3.5中尝试了脚本,并收到以下输出:

File "print_strings_on_same_line.py", line 16
print fiveYears
              ^
SyntaxError: Missing parentheses in call to 'print'

然后,我修改了打印出生数的最后一行:

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: " + str(births) + " births"

输出是(Python 2.7.10):

157680000
If there was a birth every 7 seconds, there would be: 22525714 births

我希望这能有所帮助。

你可以使用f-string或.format()方法

使用f-string

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

使用.format ()

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

你首先要创建一个变量:例如:D = 1。然后这样做,但替换字符串与任何你想要:

D = 1
print("Here is a number!:",D)

PYTHON 3

最好使用格式选项

user_name=input("Enter your name : )

points = 10

print ("Hello, {} your point is {} : ".format(user_name,points)

或将输入声明为字符串并使用

user_name=str(input("Enter your name : ))

points = 10

print("Hello, "+user_name+" your point is " +str(points))