Restarting a Python script with Input

Asked

Viewed 737 times

0

I have the following program below in Python with 2 functions, one to convert real in dollars according to the quotation, and one to convert dollars to real also according to the quotation, plus a simple menu to decide between the 2 functions:

def reaispdolar () :
  Reais = float (input("Quantos reais? R$: "))
  Cotação = float (input("Cotação de hoje é? "))
  conversão = Reais/Cotação
  print("Você possui US$" , ("%.2f" % conversão))


def dolarpreais () :
  Dolar = float(input("Quantos Dolares? US$: "))
  Cotação = float(input("Cotação de hoje é? "))
  Conversão = Cotação*Dolar
  print("Você possui: R$", ("%.2f" % Conversão))

print("O que deseja fazer? ")
print("1 - Converter reais em dolares")
print("2 - Converter dolares em reais")
menu = input("Deseje a opção desejada\n")
if menu == "1" :
    reaispdolar()
elif menu == "2" :
  dolarpreais()
else : 
    print("Valor inválido",)

What I would like is that on the menu being the input invalid or when the input is correct and the conversion gives its final value, the following message appears: "You want to restart S/N ?": ").

And when the user presses "S" or "s" the program returns to the "start menu". It is possible to do this without while?

  • 2

    wilhe It’s not a methodology, it’s a loop instruction, and a programmer who’s afraid to use a loop is a popcorn uncle’s future. Ps: Nothing against popcorn uncles, but I don’t believe anyone went to college to become popcorn.

  • @Augusto Vasques -> At what point has anyone mentioned fear of using ? I understand that While is important and can be used in this case, the only thing my question deals with is about other ways of performing the same operation without the while. Without fitting your comment.

  • 2

    You got an answer. But is it more beneficial for you? Or for those who are starting a career?

2 answers

3

The other answer suggests using recursion, which is a way of doing without while, but it is not the best way, because if the user stays in the loop several times, recursive calls will accumulate and this can cause a stack overflow (see here an example, scroll to the bottom of the page and see the RecursionError). Already using while, there is no such problem. Just because it is possible to do something, it does not mean that you should do it.


Why don’t you want to use while? Besides being one of the most basic structures of programming, it is the simplest way. Just make a loop and only stop it when the option is not "S" or "s":

while True:
    print("O que deseja fazer? ")
    print("1 - Converter reais em dolares")
    print("2 - Converter dolares em reais")
    menu = input("Deseje a opção desejada\n")
    if menu == "1" :
        reaispdolar()
    elif menu == "2" :
      dolarpreais()
    else: 
        print("Valor inválido")
    if input('Deseja reiniciar (S/N)? ') not in ('S', 's'):
        break # se digitar qualquer coisa diferente de "s" ou "S", sai do loop

In case, I check if the typed option was not "S" or "s" (ie if the person type anything different - not necessarily "N"), it exits the program.

Of course you can sophisticate more, for example, by checking whether the option is even "S" or "N" (and rejecting anything else):

while True:
    print("O que deseja fazer? ")
    print("1 - Converter reais em dolares")
    print("2 - Converter dolares em reais")
    menu = input("Deseje a opção desejada\n")
    if menu == "1" :
        reaispdolar()
    elif menu == "2" :
      dolarpreais()
    else: 
        print("Valor inválido",)
    while True:
        opcao = input('Deseja reiniciar (S/N)? ').lower() # converter para minúsculo
        if opcao not in ('s', 'n'):
            print('opcao invalida, deve ser S ou N')
        else: break # sai do while interno, pois a opção é S ou N
    if opcao == 'n': break # se for N, sai do loop externo

But the general idea is this: use break to get out of loop, and just call the break if the exit condition is met.

  • 3

    For those who gave the negative, consider the comment I posted after the issue about the use of recursion. Just because the AP asked without while, doesn’t mean it’s the best way, and I’m not going to suggest recursion in a case where clearly it’s the worst solution

  • I agree with you about not using recursion, as he quoted without while, I believed with the solution with while he should already have known, I answered with the example, so he knows the possibility of recursion and also the problems that it can bring.

  • 1

    I thank hkotsubo and Danielmendes for the clarifications. I understand that while is the best option and I thank you for having shown the example. I also appreciate the example using recursion, now that I know both and the risk of each one, I can choose better depending on the problem or project. Thank you both!

  • 2

    @Yagofdev while there are no "risks" in this case, it is the safe option without contraindications :-) Anyway, if you found the answers useful, you can vote in them. Also, you can choose the one that best solved your doubt (only one of them) and accept it - see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem

0


Yes, it is possible to continue in the program without using a while or for, a way is by using the recursion.

You can create a function that will be the body of your current menu:

def opcoes():
  print("O que deseja fazer? ")
  print("1 - Converter reais em dolares")
  print("2 - Converter dolares em reais")
  menu = input("Deseje a opção desejada\n")
  if menu == "1" :
    reaispdolar()
  elif menu == "2" :
    dolarpreais()
  else : 
    print("Valor inválido")

Now your code will have three functions, with this you will call the function opcoes soon after the declarations of the functions, thus initiating its program:

opcoes()

To create the recursion, its function opcoes, should call herself:

def opcoes():
  print("O que deseja fazer? ")
  print("1 - Converter reais em dolares")
  print("2 - Converter dolares em reais")
  menu = input("Deseje a opção desejada\n")
  if menu == "1" :
    reaispdolar()
  elif menu == "2" :
    dolarpreais()
  else : 
    print("Valor inválido")

  opcoes()

With this, you will have your program running constantly. However there is a problem, your program is in an infinite loop, so it is always important to think of a condition that will end the recursion, which in this case, is the question to the user if he wants to restart:

def opcoes () :
  print("O que deseja fazer? ")
  print("1 - Converter reais em dolares")
  print("2 - Converter dolares em reais")
  print("3 - Encerrar o programa")

  menu = input("Deseje a opção desejada\n")

  if menu == "1" :
    reaispdolar()
  elif menu == "2" :
    dolarpreais()
  else : 
    print("Valor inválido",)  

  reinicia = input("Deseja reiniciar S/N ?").upper()

 if reinicia == "S" :
   opcoes()

Okay, now there is the possibility to quit recursion and finish the program.


See the full code online: https://repl.it/repls/ParchedGummyServerapplication

Browser other questions tagged

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