简体   繁体   English

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

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

I'm brand new to python and my teacher showed me an example on how to write multiple variables in a print function but I am getting a syntax error. 我是python的新手,我的老师向我展示了一个如何在打印函数中编写多个变量的示例,但出现语法错误。 Did I write it wrong? 我写错了吗? How can I fix this? 我怎样才能解决这个问题?

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

Above is just a simple function I'm writing as part of some beginner exercise. 以上只是我在一些初学者练习中编写的一个简单函数。 But when I run the code it says my print function has invalid syntax. 但是,当我运行代码时,它说我的打印功能语法无效。

Use this code. 使用此代码。

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

Because you seem to be working in Python 3, there is a really cool way to format strings that I absolutely love. 因为您似乎正在使用Python 3,所以有一种非常酷的方式来格式化我绝对喜欢的字符串。 With this method, your print() would look like 使用此方法,您的print()看起来像

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

With this method, you can write pretty much any python in between {} and python automatically puts the returned output of that code in your string. 使用此方法,您可以在{}之间编写几乎所有的python,并且python会自动将该代码的返回输出放入您的字符串中。

Here I fixed your code. 在这里,我修复了您的代码。 I also added a few lines of extra code so that it is a bit more readable for your prof. 我还添加了几行额外的代码,以使您的教授更具可读性。 It should be easy enough for you to understand. 它应该足够容易让您理解。 Here's the code: 这是代码:

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)

Hope it helps :) 希望能帮助到你 :)

You can use Format. 您可以使用格式。 In your case. 就你而言。 :f (Displays fixed point number (Default: 6)) :f(显示定点编号(默认值:6))

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

More information please check this link https://www.programiz.com/python-programming/methods/string/format 更多信息请检查此链接https://www.programiz.com/python-programming/methods/string/format

删除百分号前的逗号。

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

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