簡體   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