Python exercise

Asked

Viewed 107 times

0

Hi, I have python as one of my second semester classes and I need a little help. I have an exercise where I can’t make it work properly; here is the statement:"Write a program that reads a set of numbers from the keyboard until the user enters a negative number. In final you must print the largest of these numbers." The following code was what I did but as I said above, it doesn’t work properly.

def read():
  list=[]
  n = int(input("Introduza um nº negativo para terminar:"))
  while True:
    if n > 0:
        n = int(input("Introduza um nº negativo para terminar:"))
        list.append(n)
    else:
        break
  print("O maior nº é:"+max(list))

read()

2 answers

0

n = int(input('Introduza um número inteiro (negativo para sair): '))
maiorDeTodos = -1

while n > 0:
    if maiorDeTodos < n:
        maiorDeTodos = n
    n = int(input('Introduza um número inteiro (negativo para sair): '))

print('O maior de todos foi {}'.format(maiorDeTodos))
  • I thank you for your help.

0


You can do it this way:

#!/usr/bin/env python
numbers = []
while True:   
   try:
      n = int(input("Insira um numero negativo para terminar: "))
   except ValueError:
      print("Entrada inválida!")
      continue #continua o loop

   if (n > 0):
      numbers.append(n)
   else:
      if numbers: #verifica se lista está não vazia
         print("O maior numero é: " + str(max(numbers)))
      else:
         print("Não há numero para mostrar!")
      break

There are some minor errors in your code like: do not convert int to string in concatenation, do not treat exception and repeat variable "n" without precision. This last little mistake is irrelevant. I hope this can help :)

Browser other questions tagged

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