How do I create a list for possible answers in python?

Asked

Viewed 82 times

2

Well... I wanted to make a list for possible user responses to input, for example:

nom = str(input('Você gosta de mim? '))

lista = ['sim','claro','obvio']


if nom == lista:
  print('obrigado, bom saber')
else:
  print('Que pena')

Good... What I wanted is that if the user typed one of the words that are on that list would print the msg "Thank you, good to know"

But since I’m new to python, I don’t even know if it’s right to do so with the list, when I put one of the words that are on the list appeared the other msg "what a pity"

I wanted you to help me if it has how to do so with a list or has to be doing the possible answers in if even without the list

  • 1

    if nom in lista:

  • 1

    Vlw man, you helped me a lot

  • here nom = str(input('Você gosta de mim? ')) don’t need to use str() for input() returns string.

4 answers

3

nom = str(input('Você gosta de mim? '))

lista = ['sim','claro','obvio']


if nom in lista:
  print('obrigado, bom saber')
else:
  print('Que pena')

1

nom = input("Você gosta de mim?")

nom = nom.lower()

lista =["sim", "claro", "obvio"]

if nom in lista:
    print("Obrigado bom saber")

else:
    print("Que pena")


I changed some things, for example:

the str() it is not crucial, python itself considers as string.

I also added the .lower, because, if he typed some capital letter or minuscula he would go to the else.

1

If you want to test if an element is contained in a sequence use the operator in.
x in s returns True if x is a member of s, otherwise returns False.

str.lower() returns a copy of the string in lowercase alphabetic characters. It is necessary to convert the user input to lowercase because comparison and Python membership operators are sensitive to the box (whether it is uppercase or lowercase) of the character.

The return of function print() is string not required to convert with str().

If the purpose of the comparison is just to return one of two values without performing processing one can use a conditional expression of the kind x if C else y where the condition is C for True returns x otherwise returns y.

p = 'Você gosta de mim? '
r1 = 'obrigado, bom saber'
r2 = 'Que pena'
opts = ['sim','claro','obvio']
#Se a entrada do usuário em minusculas estiver em opts retorna r1 senão retorna r2
resp = r1 if input(p).lower() in opts else r2
print(resp)

0

For simple conditions, you can use the if ternary of Python:

print('obrigado, bom saber') if input('Você gosta de mim? ') in ['sim','claro','obvio'] else print('Que pena')

Some people consider this to be the "Pythonic" way of doing it. Others will say it impairs readability.

How your goal seems to be to learn how to use the if, stays there one more possibility.

However, in a real program, always handle all user entries.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.