Python, value percentage (result)

Asked

Viewed 3,405 times

0

is the following I need to make the program show the percentage of votes, only if I start the variable with zero does not give, because the program says that division by zero does not give, but if I start with 1, the account will go wrong, someone can give me a light ? the program shows how many votes had given operating system and the percentage in relation to the total.

listaWindows = []
listaUNIX = []
listaLinux = []
listaNetware = []
listaMacos = []
listaOutro = []
contW = contU = contL = contN = contM = contO = porcenW = porcenU = porcenL = porcenN = porcenM = porcenO = 0
soma = 1
while True:
    print('''
    1 - Windows Server
    2 - UNIX
    3 - Linux
    4 - Netware
    5 - Mac OS
    6 - Outro''')
    opcao = int(input("Informe a opção desejada: "))
    if opcao == 0:
        break
    while opcao > 6 or opcao < 1:
        opcao = int(input("Opção invalida, digite a opção novamente: "))
    if opcao == 1:
        listaWindows.append(contW)
        contW += 1
        porcenW = (contW / soma) * 100
    if opcao == 2:
        listaUNIX.append(contU)
        contU += 1
        porcenU = (contU / soma) * 100
    if opcao == 3:
        listaLinux.append(contL)
        contL += 1
        porcenL = (contL / soma) * 100
    if opcao == 4:
        listaNetware.append(contN)
        contN += 1
        porcenN = (contN / soma) * 100
    if opcao == 5:
        listaMacos.append(contM)
        contM += 1
        porcenM =  (contM / soma) * 100
    if opcao == 6:
        listaOutro.append(contO)
        contO += 1
        porcenO = (contO / soma) * 100
    soma = contW + contU + contL + contN + contM + contO
print(f'''
        Votos  %
Windows: {contW}    {porcenW:.2f}
UNIX:    {contU}    {porcenU:.2f}
Linux:   {contL}    {porcenL:.2f}
Netware: {contN}    {porcenN:.2f}
Mac      {contM}    {porcenM:.2f}
Outro    {contO}    {porcenO:.2f}''')

2 answers

2

This answer is based on this reply given by Anderson Carlos Woss. You can use a dictionary to store all options:

opcoes = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0 }

thus avoiding a large number of if followed. Set a list of system names:

sistemas = [ 'Windows', 'UNIX', 'Linux', 'Netware', 'Mac OS', 'Outro' ]

each option informed by the user, make the increment in the value of the selected option opcoes[opcao] += 1.

The class int raises an exception of the type ValueError when the value to be converted to integer is not numerical, therefore, to ensure that the value entered by the user is numerical, just treat the exception.

try:
  opcao = int(input(menu))
except ValueError:
  print("O valor deve ser um número inteiro")

the method porcentagem

def porcentagem(votos, total):
  return (votos / total) * 100 if total > 0 else 0

To check the percentage of each option, we sum all the values of the dictionary:

total = sum(opcoes.values())

To avoid unnecessary repetitions, we go through the dictionary keys and print the system name, the number of votes and the percentage:

print('Sistema ', ' Votos', ' Porcentagem')
print('----------------------------')
for chave, valor in opcoes.items():
  espacos = ' ' * (8 - (len(sistemas[chave-1])))
  print(sistemas[chave-1], espacos, valor, ' ' * 4, porcentagem(valor, total))
        # Nome do sistema           # Votos         # Porcentagem

the string espacos and ' ' * 4 serve only to enhance the view.

Complete code

opcoes = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0 }
sistemas = [ 'Windows', 'UNIX', 'Linux', 'Netware', 'Mac OS', 'Outro' ]

menu = """
1 - Windows Server
2 - UNIX
3 - Linux
4 - Netware
5 - Mac OS
6 - Outro

Escolha uma opção:"""
while True:
  try:
    opcao = int(input(menu))
    if opcao == 0: break
    opcoes[opcao] += 1
  except ValueError:
    print("O valor deve ser um número inteiro")
  except KeyError:
    print("Opção inválida")

def porcentagem(votos, total):
  return (votos / total) * 100 if total > 0 else 0

total = sum(opcoes.values())

print('Sistema ', ' Votos', ' Porcentagem')
print('----------------------------')
for chave, valor in opcoes.items():
  espacos = ' ' * (8 - (len(sistemas[chave-1])))
  print(sistemas[chave-1], espacos, valor, ' ' * 4, porcentagem(valor, total))
        # Nome do sistema           # Votos         # Porcentagem

Behold running on repl.it

1

I made some changes to the code, there was no need to use lists. It is possible to simplify even more, but since it is not objective, let’s go to the code.

I made the sum of all counters, and in the end I created method to take the percentage, in this method I make a check if the total value is not equal to 0, avoiding that it generates exception.

contW = contU = contL = contN = contM = contO = 0

while True:
    print('''
    1 - Windows Server
    2 - UNIX
    3 - Linux
    4 - Netware
    5 - Mac OS
    6 - Outro''')
    opcao = int(input("Informe a opção desejada: "))
    if opcao == 0:
        break
    while opcao > 6 or opcao < 1:
        opcao = int(input("Opção invalida, digite a opção novamente: "))        
    if opcao == 1:
        contW = contW + 1
    if opcao == 2:
        contU = contU + 1
    if opcao == 3:
        contL = contL + 1
    if opcao == 4:
        contN = contN + 1
    if opcao == 5:
        contM = contM + 1
    if opcao == 6:
        contO = contO + 1

def percent(indicador, total):
    if total is not 0:
        return (indicador / total) * 100
    else:
        return 0

total = contW + contU + contL + contN + contM + contO
porcenW = percent(contW, total)
porcenU = percent(contU, total)
porcenL = percent(contL, total)
porcenN = percent(contN, total)
porcenM = percent(contM, total)
porcenO = percent(contO, total)

print(f'''
        Votos  %
Windows: {contW}    {porcenW:.2f}
UNIX:    {contU}    {porcenU:.2f}
Linux:   {contL}    {porcenL:.2f}
Netware: {contN}    {porcenN:.2f}
Mac      {contM}    {porcenM:.2f}
Outro    {contO}    {porcenO:.2f}''')
  • Thanks, that way it worked

  • @punkoco If this answer solved your problem and there is no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

Browser other questions tagged

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