繁体   English   中英

如何在打印函数(Python)中打印多个变量?

[英]How can I print more than one variable in my print function(Python)?

我是python的新手,我的老师向我展示了一个如何在打印函数中编写多个变量的示例,但出现语法错误。 我写错了吗? 我怎样才能解决这个问题?

def fahrenheit_to_celcius(num):
    celciusTemp=(num-32)*0.556
    print("When you convert %s to celcius the result is %s",%(num, 
celciusTemp))

以上只是我在一些初学者练习中编写的一个简单函数。 但是,当我运行代码时,它说我的打印功能语法无效。

使用此代码。

def fahrenheit_to_celcius(num):
    celciusTemp=(num-32)*0.556
    print("When you convert %s to celcius the result is %s" % (num, 
celciusTemp))

因为您似乎正在使用Python 3,所以有一种非常酷的方式来格式化我绝对喜欢的字符串。 使用此方法,您的print()看起来像

print(F"When you convert {num} to Celsius, the result is
{celsiusTemp}.")

使用此方法,您可以在{}之间编写几乎所有的python,并且python会自动将该代码的返回输出放入您的字符串中。

在这里,我修复了您的代码。 我还添加了几行额外的代码,以使您的教授更具可读性。 它应该足够容易让您理解。 这是代码:

def fahrenheit_to_celcius(num):
    celciusTemp=(num-32)*0.556
    print("When you convert {} fahrenheit to celcius the result is {:f}".format(num,celciusTemp))
num = int(input("Input the degrees of fahrenheit you want to convert to celcius:"))
fahrenheit_to_celcius(num)

希望能帮助到你 :)

您可以使用格式。 就你而言。 :f(显示定点编号(默认值:6))

string = "when you convert {} to celcius the result is {:f}".format(num,celciusTemp)
print(string) 

更多信息请检查此链接https://www.programiz.com/python-programming/methods/string/format

删除百分号前的逗号。

暂无
暂无

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

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