如何在if-elif语句的列表中使用数字?我不知道为什么这段代码不起作用?

问题描述 投票:-2回答:3
myList = ["shy","sociable","loud"]
print(myList)
personality = 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
3个回答
2
投票
  1. [personality可能是string,请使用int(input(...))获得int
  2. 您无法比较intstring
  3. 等于运算符是==,不是=
  4. :if行后需要冒号elif

类似的事情可能起作用:

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")

0
投票

有3个问题:

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")

0
投票

Python语法:

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

每个条件之后,您只是缺少colons:)。

此外,要检查某项是否等于其他项,必须使用==。单个=执行分配。

if variable == 42:
    variable = 7

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

IntegerValue = int(stringFormat)

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

© www.soinside.com 2019 - 2024. All rights reserved.