How to ask questions for the user in Python, without running constantly?

Asked

Viewed 6,045 times

2

I’m creating a code in Python that asks for the nick of a player and, as the user responds, he will receive a reply, check:

player = (input('Digite o nick desejado:'))

if player == 'Phil' :
  print('Player encrenqueiro,nível de habilidades:razoável.')
elif player == 'Knuckles' :
    print('Ótimo player,muito cooperativo,nível de habilidades:alta!')
elif player == 'Bubble':
    print('Considerado um dos melhores players no game,extremamente flexível e\n adaptável ao jogo de seu parceiro,nível de habilidades:altíssima!')

The problem is that I do not know how to make the program not stop, until the user type all the nicknames that he wants. I don’t want him running again every time to get an answer, I want to continuously...

Each one will receive a different message for each nick typed, and that’s what I want done, after they type in a nick and get an answer, I want you to get a "Type the next player" and so on...

  • 1

    The ideal would be for you to post the code in text instead of image. On your question, you can make a repeat loop, or repeat the snippet that reads the input once for each if instead of Elif

  • Could you demonstrate that? I only know how to use while and again with some message, purely this,I don’t know how to use after the user replies something,e yes,next post the code instead of the image,.

  • EDIT: text code now.

  • Have you solved it yet? With a while cycle you do it

  • Not yet Miguel, I need a small demonstration, if possible, I understand better by looking,I looked a lot before coming to ask here,but all I think is how to use the while and for PURELY(only this),and my goal is to repeat the question after the user has received an answer to the nick he typed,example: type a nickname: strawberry/answer: strawberry is a great player,:

  • https://wiki.python.org/moin/WhileLoop

  • Leonardo Alves Machado Do you really think I didn’t read about while/for before I came here to ask? as I said,I know how to use them purely,and not put them to give a particular answer,for every nick the user types,and after that ask to type in the next player,and so on,understand? is confusing to explain, haha,.

  • Take a look at my answer, it is not to show again the phrase if it has already been typed?

Show 3 more comments

2 answers

3

Although the other answer produces the expected result, I do not think it is a good solution, since if you need to add more options nicknames, you will have to add other conditions in the structure. Not good for application maintenance.

The solution I propose is to store the nicknames together with their sentences in a dictionary:

NICKNAMES = {
    'Phil': 'Player encrenqueiro, nível de habilidades: razoável.',
    'Knuckles': 'Ótimo player, muito cooperativo, nível de habilidades: alta!',
    'Bubble': 'Considerado um dos melhores players no game, extremamente flexível e\n adaptável ao jogo de seu parceiro, nível de habilidades: altíssima!',
    'Woss': 'Pica das galáxias. Com certeza o melhor! Boa escolha, nível de habilidades: mais que 8000!'
}

And, already predicting that the user can enter another option other than these, set a message to display by default:

DEFAULT = 'Huum, não sei o que dizer sobre esse player :('

To read the user input, use an infinite loop until it confirms the nick that he wishes to use.

while True:
    print("Qual nick gostaria de utilizar?")
    print("Que tal essas opções:", list(NICKNAMES.keys()), '?')

    nick = input("Nick: ")

    print(NICKNAMES.get(nick, DEFAULT))

    confirm = input('Gostaria de manter esse nick? [S/n] ')

    if confirm in ['S', 's', '']:
        break
    else:
        print()

print('Ok, seu nick será {}'.format(nick))

See working on Repl.it

So if you need to define others nicknames, just add in the dictionary, which could be a structure stored in a database or even in a JSON file, for example.

A possible exit from this code would be:

Qual nick gostaria de utilizar?
Que tal essas opções: ['Phil', 'Knuckles', 'Bubble', 'Woss'] ?
Nick:  Phil
Player encrenqueiro, nível de habilidades: razoável.
Gostaria de manter esse nick? [S/n]  n

Qual nick gostaria de utilizar?
Que tal essas opções: ['Phil', 'Knuckles', 'Bubble', 'Woss'] ?
Nick:  Knuckles
Ótimo player, muito cooperativo, nível de habilidades: alta!
Gostaria de manter esse nick? [S/n]  n

Qual nick gostaria de utilizar?
Que tal essas opções: ['Phil', 'Knuckles', 'Bubble', 'Woss'] ?
Nick:  Bubble
Considerado um dos melhores players no game, extremamente flexível e
 adaptável ao jogo de seu parceiro, nível de habilidades: altíssima!
Gostaria de manter esse nick? [S/n]  n

Qual nick gostaria de utilizar?
Que tal essas opções: ['Phil', 'Knuckles', 'Bubble', 'Woss'] ?
Nick:  Horacio
Huum, não sei o que dizer sobre esse player :(
Gostaria de manter esse nick? [S/n]  n

Qual nick gostaria de utilizar?
Que tal essas opções: ['Phil', 'Knuckles', 'Bubble', 'Woss'] ?
Nick:  Woss
Pica das galáxias. Com certeza o melhor! Boa escolha, nível de habilidades: mais que 8000!
Gostaria de manter esse nick? [S/n]  s
Ok, seu nick será Woss
  • Very good tip, mainly on the dictionary(highlight for the player "Woss" huh!) saved your answer here in the documents friend, very useful ;)

0

So? If it is I comment on the code later.

Demo: https://repl.it/repls/FumblingNaturalModes

nicks_consultados = []

while len(nicks_consultados) < 3:
  print("Quantidade {}".format(len(nicks_consultados)))

  player = (input('Digite o nick desejado:'))

  if player == 'Phil':
    print('Player encrenqueiro,nível de habilidades:razoável.')

    if 'Phil' not in nicks_consultados:
      nicks_consultados.append('Phil')

  elif player == 'Knuckles' :
    print('Ótimo player,muito cooperativo,nível de habilidades:alta!')

    if 'Knuckles' not in nicks_consultados:
      nicks_consultados.append('Knuckles')
  elif player == 'Bubble':
    print('Considerado um dos melhores players no game,extremamente flexível e\n adaptável ao jogo de seu parceiro,nível de habilidades:altíssima!')

    if 'Bubble' not in nicks_consultados:
      nicks_consultados.append('Bubble')

print("Terminou")

Explanation

I created a vector nicks_consultados, where I will save which nicks have already been typed.

while len(nicks_consultados) < 3:

In this excerpt I get the number of items in the list while it is less than 3 (the user has not typed all the nicks at least once I repeat the process.

Inside ifs I check if the nick is not on the list if it is not added.

  • Exactly Laerte, perfect, thank you,now I will try to understand the code,!

  • See if you can understand.

  • Yes, I understand perfectly now,.

  • Booa, python is very cool, good studies. :)

Browser other questions tagged

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