Python, percentage of values (result)

0

This is what I need to do for the program to show the percentage of votes, but if I start the variable with zero it does not, because the program says that division by zero does not, but if I start with 1, It's going to go wrong, can someone give me a light? the program shows how many votes a given operating system had and the percentage over 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}''')
    
asked by anonymous 22.04.2018 / 03:31

2 answers

1

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

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

In doing so, it avoids a large number of if followed. Define a list of system names:

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

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

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

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

method porcentagem

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

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

total = sum(opcoes.values())

To avoid unnecessary repetition, we go through the dictionary keys and print out the system name, number of votes, and 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

string espacos and ' ' * 4 serve only to improve visualization.

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

See running at repl.it

    
22.04.2018 / 06:26
0

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

I made the sum of all counters, and in the end I created a method to get the percentage, in this method I make a check if the total value does not equal 0 , preventing it from generating an 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}''')
    
22.04.2018 / 03:52