我的ifelse语句与我使用的列表不兼容

2024-09-30 03:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我输入3作为我的眼睛颜色(绿色),它显示“你是一个乐观的人”,而不是“你是一个好奇的人”。为什么会这样?它不是应该显示其他的吗

eyeList = ["blue", "brown","green","hazel","grey","none"]

print(eyeList)

eyecolor = int(input("Pick your eye color: "))

if eyecolor == 1 or 2:

  print("you are a  optimistic person")

else:
  print("you are a curious person")

Tags: noneyou颜色greenbluearegreyperson
3条回答
  1. personality可能是string,使用int(input(...))获得int
  2. 无法将intstring进行比较
  3. 相等运算符是==,而不是=
  4. 在每一行ifelif之后都需要冒号:

类似的方法可能会奏效:

myList = ["shy","sociable","loud"]
print(myList)
try :
    personality = int(input("Pick a trait from the list: "))
except ValueError :
    sys.exit("Invalid input: " + str(personality))

if personality == 0 :
  print("You are a person who doesn't doesn't like talking to other people")
elif personality == 1 :
  print("you talk to people, but aren't really loud")
elif personality == 2 :
  print("You love talking to people and you are very loud")

有三个问题:

a)输入作为字符串,您需要在int中转换它

b)检查语法错误,应该是两个等号==

c)跳过if结尾处的:

固定代码:

myList = ["shy","sociable","loud"]
print(myList)
personality = int(input("Pick a trait from the list: "))

if personality == 0:
  print("You are a person who doesn't doesn't like talking to other people")
elif personality == 1:
  print("you talk to people, but aren't really loud")
elif personality == 2:
  print("You love talking to people and you are very loud")

Python语法:

if condition:
    Indented expressions
elif condition2:
    Other expressions
else:
    Further expressions

您只是缺少每个条件之后的冒号:

此外,要检查某物是否等于其他某物,必须使用==。单个=执行赋值

if variable == 42:
    variable = 7

最后,不能将整数与字符串进行比较(input()函数返回字符串)。要执行此操作,请将字符串转换为整数:

IntegerValue = int(stringFormat)

最后提示:您的控制台为您提供了有关代码错误的有用提示。听他们说

相关问题 更多 >

    热门问题