社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在这个简单的Python代码中,我做错了什么?

Manan • 4 年前 • 2575 次点击  

--我的目标是制作一个代码,用户必须输入温度,然后用户必须输入单位(C或F),然后我想显示转换为F,如果用户输入C,反之亦然。这里出了什么问题请告诉我,我对python非常陌生,整天都在学习,谢谢。

print("Lets convert from C to F/ F to C")
temp = int(input("enter the temperature: "))
unit = input("enter the unit (C or F)")
if unit == C:
    F = temp * 1.8 + 32
    print(temp +"C is equal to"+F +"F")
elif unit == F:
    C = temp / 1.8 - 32
    print(temp + "F is equal to" +C + "C")
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131513
文章 [ 4 ]  |  最新文章 4 年前
plankton13
Reply   •   1 楼
plankton13    4 年前

在这种情况下,如果使用了被解释为变量的C和F,则应使用“marks”(“F”,“C”)。同样,在打印时,应将字符串传递给打印函数,因此使用str()将int变量(“item”以及F和C)转换为字符串

Alberto Hanna
Reply   •   2 楼
Alberto Hanna    4 年前
print("Lets convert from C to F/ F to C")

temp = int(input("enter the temperature: "))
unit = input("enter the unit (C or F)")

if unit == "C": #small typo
    F = temp * 1.8 + 32
    print(str(temp) + "C is equal to" + str(F) + "F") # you cant do int + str
elif unit == "F":
    C = temp / 1.8 - 32
    print(str(temp) + "F is equal to" + str(C) + "C")
kwinkunks
Reply   •   3 楼
kwinkunks    4 年前

你需要练习处理字符串和数字,并在两者之间进行转换。例如,请注意: input() 总是给你一些线索,而做数学总是需要数字。

所以这里有几件事:

  1. 比较 unit 到 "C" (一根绳子),不是吗 C (一个变量)。
  2. 在尝试做数学之前 temp ,用 float(temp) (不要使用 int() 因为如果有人进来 21.9 (比如说), int 我会取整的。
  3. 当你用 + ,所有元素都必须是字符串。所以,用 str(num) .

注意公式中的运算顺序!

j1-lee
Reply   •   4 楼
j1-lee    4 年前

你可能需要更加注意字符串。

  1. 使用字符串文字 'F' 和 'C' ( 不 光秃秃的 F 和 C )在 if 条件
  2. 显式转换 int 到 str 通过使用 str() ,当您连接 智力 和 str .或者更好,使用f字串。
print("Lets convert from C to F/ F to C")
temp = int(input("enter the temperature: "))
unit = input("enter the unit (C or F)")
if unit == 'C':
    F = temp * 1.8 + 32
    print(str(temp) +"C is equal to"+str(F) +"F")
elif unit == 'F':
    C = temp / 1.8 - 32
    print(str(temp) + "F is equal to" +str(C) + "C")

顺便说一句,这个公式恐怕有点错误。在另一个版本中,我更正了公式并使用了f-string,如下所示:

print("Let's convert from °C to °F or °F to °C!")
temp = int(input("Enter the temperature: "))
unit = input("Enter the unit (C or F): ")
if unit.upper() == 'C':
    F = temp * 1.8 + 32
    print(f"{temp}°C is equal to {F}°F")
elif unit.upper() == 'F':
    C = (temp - 32) / 1.8
    print(f"{temp}°F is equal to {C}°C")