首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的If-Else条件代码接收用户输入并按“热”或“冷”对数据进行分类,这是怎么回事?

我的If-Else条件代码接收用户输入并按“热”或“冷”对数据进行分类,这是怎么回事?
EN

Stack Overflow用户
提问于 2020-02-16 11:24:24
回答 2查看 65关注 0票数 1
代码语言:javascript
复制
HighTemp1= input()
print(‘Temperature 1:’ +  HighTemp1)
LowTemp2= input()
print(‘Temperature 2:’ + LowTemp2)
if (HighTemp1>80):
   print( ‘The high temperature was Hot’)
elif(HighTemp1> 40 and <80):
   print(‘The high temperature was Average’)
else:
   print(‘The high temperature was Cold’)

if (LowTemp2>80):
   print( ‘The low temperature was Hot’)
elif(LowTemp2> 40 and <80):
   print(‘The low temperature was Average’)
else:
   print(‘The low temperature was Cold’)

因此,我假设确定一天内两个用户输入温度的类别,并以以下方式输出:

代码语言:javascript
复制
Temp        Category
>80         Hot
40 to 80    Average
<40         Cold

Example#1:温度1: 81温度2: 37高温为热低温为冷

我在这段代码中遇到了太多的错误,我不确定哪里出了问题。代码不会在IDLE中运行,因为当我逐行运行它时(因为我得到了一个多语句错误),要么是类型错误"cannot use > operator with The int and string“,要么是语法错误。我有什么不理解的地方使我的代码无法运行?

EN

回答 2

Stack Overflow用户

发布于 2020-02-16 11:40:00

我假设您使用的是Python3。您的代码中有许多错误

代码语言:javascript
复制
HighTemp1= int(input())  #to take int input, you need to parse it to int. as input() directly reads a string
print("Temperature 1:" +  str(HighTemp1)) #print in python3 assumes string in "" 
LowTemp2= int(input())
print("Temperature 2:" + str(LowTemp2)) #int can't be directly concatenated to string. You need to parse it to string using str() to concat it with string
if (HighTemp1>80):
    print( "The high temperature was Hot")
elif(HighTemp1> 40 and  <80):
    print("The high temperature was Average")
else:
    print("The high temperature was Cold")

if (LowTemp2>80):
    print( "The low temperature was Hot")
elif(LowTemp2> 40 and <80):
    print("The low temperature was Average")
else:
    print("The low temperature was Cold")
票数 0
EN

Stack Overflow用户

发布于 2020-02-16 12:06:41

首先,input()返回一个字符串。为了进行比较,您需要将其转换为int类型。第二,注意你的“语录”。在字符串中用作引号的字符不是简单的ASCII。我把它们都换了。第三,你的比较是有缺陷的。我重做了“高”的部分,只修复了“低”的部分。你可以看到不同之处。此外,input()方法将字符串作为输入参数输出给用户,这样他/她就知道要输入什么了。这可能是一件好事。

代码语言:javascript
复制
HighTemp1 = int(input('High: ').strip())
print('Temperature 1: %d' %  HighTemp1)
LowTemp2= int(input('Low: ').strip())
print('Temperature 2: %d' % LowTemp2)
if HighTemp1 > 80:
   print('The high temperature was Hot')
# elif 40 < HighTemp1 <= 80: # simplifies to next line
elif HighTemp1 > 40:
   print('The high temperature was Average')
else:
   print('The high temperature was Cold')

if (LowTemp2 > 80):  # parens not required here
   print('The low temperature was Hot')
elif(LowTemp2 > 40):  # and LowTemp2<=80):
#                     # the above is redundant
# note that your original "and LowTemp2<80" introduced a bug for value 80
   print('The low temperature was Average')
else:
   print('The low temperature was Cold')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60245135

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档