How to Restart a Python Program?

Asked

Viewed 269 times

0

I have to make a program that calculates the finite sum of a geometric progression, so I did:

a_1 = float(input('Primeiro Termo: '))
a_2 = float(input('Segundo Termo: '))
n = int(input('Número do Termo: '))
q = a_2 / a_1
a_n = (a_1) * (q) ** (n - 1)
S_n = a_1 * (q ** n - 1) / (q - 1)
print('a{} é igual à \033[1;31m{:.0f}\033[m'.format(n, a_n))
print('A soma dos {} primeiros termos da P.G. é igual à \033[1;31m{:.0f}\033[m'.format(n, S_n))

The problem is that I would like to turn it into an executable, and every time the program just runs, it just closes, and it’s really annoying when I have to do more than one account. So I’d like to give the user an option: 1 Hold another account, 2 Close the program.

When the user wanted to hold another account, the program would restart and he could do another account. I tried with:

import sys
import os
def restart_program():
    python = sys.executable
    os.execl(python, python, * sys.argv)

And Then:

print('[ 1 ] Realizar outra conta\n[ 2 ] Sair do Programa')
cu = int(input('Sua escolha: '))
if cu == 2:
    exit()
elif cu == 1:
    restart_program()
#Sim, com uma variável muito madura

But it didn’t work :( Could you help me?

  • 4

    That doesn’t make sense, make a whilehttps://answall.com/q/352398/10 or https://answall.com/q/385771/101.

  • 1

    I thought it was funny the name of your variable.

  • @Danizavtz will CU = Choose User, or Command User?

3 answers

2

You need to implement a loop loop. In this case, the best way is to use the while.

For this issue I implemented the following algorithm...

while True:
    a_1 = float(input('Primeiro Termo: '))
    a_2 = float(input('Segundo Termo: '))
    n = int(input('Número do Termo: '))
    q = (a_2 / a_1)
    a_n = (a_1 * q ** (n - 1))
    S_n = (a_1 * (q ** n - 1)) / (q - 1)
    print('O {}º termo é igual à \033[1;31m{:.0f}\033[m'.format(n, a_n))
    print('A soma dos {} primeiros termos da P.G. é igual à \033[1;31m{:.0f}\033[m'.format(n, S_n))

    resp = input('Desejas continuar? [S/N] ').upper()
    while (len(resp) != 1) or (resp not in 'SN'):
        print('\033[31mValor INVÁLIDO! Digite apenas "S" ou "N"!\033[m')
        resp = input('Desejas continuar? [S/N] ').upper()
    if resp == 'N':
        break

Note in this algorithm that who controls the flow of the typing of the values is the primeiro while. The second while serves to treat the user’s response. If the user’s response is S the algorithm will be run again. Otherwise the algorithm will be closed.

1

If you want something to happen over and over again, don’t make it up, use a loop. A very simple version would be:

while True:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    if input('Quer continuar? (S/N) ') == 'N':
        break

The other answers use a variable to control the condition of the loop, but in this case I find it unnecessary. The value typed in the last input will only be used there, to know whether to continue or not, and then will not be used for anything else. If you type N, the break interrupts the loop.

Of course you could do something like:

condicao = True
while condicao:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    if input('Quer continuar? (S/N) ') == 'N':
        condicao = False

But I find it simpler to do the break, which makes it clear that at that point the loop must be stopped.


Another detail is that if you type anything other than "N", the while continues. If you want to be more specific and only accept certain values, you can do this separately:

while True:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    while True: # outro loop só para validar a opção
        opcao = input('Quer continuar? (S/N) ')
        if opcao not in ('S', 'N'):
            print('Digite apenas S ou N')
        else:
            break # sai do while interno
    if opcao == 'N':
        break # sai do while externo

That is, another loop just to keep asking to type again if it’s not one of the valid options. Note that it now makes sense to have a variable to store the option, as I will use it more than once (to test if it is one of the valid values, and then to see if it is the option that terminates the program).


Of course, there you can sophisticate as much as you want/need. If you search around, you will see that "a lot of people" call upper() to capitalize the string (so you could type "n" or "N", for example), or input(...)[0] to pick only the first character (this has a flaw, which is in case the user type only ENTER, then input returns the empty string and when trying to access the first character gives error).

If you want, separate the option reading into a specific function:

def ler_opcao(mensagem, valores_validos = ['S', 'N']):
    validos = "/".join(valores_validos)
    while True:
        opcao = input(f'{mensagem} ({validos}) ')
        if opcao not in valores_validos:
            print(f'Digite apenas um dos valores válidos: {validos}')
        else:
            return opcao

while True:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    if ler_opcao('Quer continuar?') == 'N':
        break

Thus, the function ler_opcao receives the message and the list of valid values (and the message will already show these values based on the list). This way you can customize at will. For example, if you want the options to be 1, 2 or 3:

while True:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    opcao = ler_opcao('Digite 1 para fazer X, 2 para fazer Y, 3 para sair', ['1', '2', '3'])
    if opcao == '1':
        print('fazer X')
    elif opcao == '2':
        print('fazer Y')
    elif opcao == '3':
        break

Notice that in that case I don’t need to use int to turn the option into a number, because if a number is not entered, it will not be among the valid options. And in this case it also makes sense to have a variable because it’s used several times later to test which of the values was typed.


In your specific case, then it would be:

while True:
    # faz o que precisa aqui (lê os números, faz as contas, etc)

    if ler_opcao('[ 1 ] Realizar outra conta\n[ 2 ] Sair do Programa', ['1', '2']) == '2':
        break

0

An alternative to solve this problem is to place your code within the function restart_program, follows an example:

def restart_program():
    a_1 = float(input('Primeiro Termo: '))
    a_2 = float(input('Segundo Termo: '))
    n = int(input('Número do Termo: '))
    q = a_2 / a_1
    a_n = (a_1) * (q) ** (n - 1)
    S_n = a_1 * (q ** n - 1) / (q - 1)
    print('a{} é igual à \033[1;31m{:.0f}\033[m'.format(n, a_n))
    print('A soma dos {} primeiros termos da P.G. é igual à \033[1;31m{:.0f}\033[m'.format(n, S_n))

cu = ''
while cu != '2':
    restart_program()
    print('[ qualquer tecla ] Realizar outra conta\n[ 2 ] Sair do Programa')
    cu = input('Sua escolha: ')

In this solution I took advantage of your code to perform the expected behavior. the only thing is that now I read a string instead of casting a number 2, and I read any value so the guy can restart, if you want to use the values of the question, just modify the code.

Note that in this solution it is not necessary to use the functions sys and os, because if the user selects the option '2' (string) then already occurs the condition to output the loop.

Browser other questions tagged

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