I'm writing a program in which the user enters numbers. The program, after the user insert the string 'done', print max and min:
numbers=[]
n=0
def maximum():
for n in numbers:
if n > maximum:
maximum = n
print("Maximum is: ", maximum)
def minimum():
for n in numbers:
if n <minimum:
minimum=n
print("Minimum is: ", minimum)
while n != 'done':
n = input('Enter a number: ')
try:
fval=float(n)
except:
print("Invalid input")
continue
numbers.append(n)
if n == 'done':
break
maximum()
minimum()
where I wrong?
CodePudding user response:
You have a couple of problems. For starters, you cannot have a variable with the same name as the function in the same scope. In addition, you should check for "done" before you try to cast n to a float. Next, you put a
continue` in your code which causes the number to never be added. I have addressed these issues and more, please let me know if you have any questions.
numbers=[]
n=0
def find_maximum():
maximum = float('-inf')
for n in numbers:
if n > maximum:
maximum = n
print("Maximum is: ", maximum)
def find_minimum():
minimum = float('inf')
for n in numbers:
if n < minimum:
minimum=n
print("Minimum is: ", minimum)
while n != 'done':
n = input('Enter a number: ')
if n == 'done':
break
try:
fval=float(n)
numbers.append(fval)
except:
print("Invalid input")
find_maximum()
find_minimum()
CodePudding user response:
Your code has multiple issues. You are overwriting numbers which is a package for numbers, according to PEP 3141.
You are using the functions name to store the maximum. Some helpers are max() and min() that you can use to calculate the max/min directly.
numbers_list = []
def print_max(nl):
print("Maximum is: ", max(nl))
def print_min(nl):
print("Minimum is: ", min(nl))
while (n := input('Enter a number: ')) != 'done':
try:
numbers_list.append(float(n))
except ValueError:
print("Invalid input")
continue
print_max(numbers_list)
print_min(numbers_list)
If you just use those functions for printing, it would be better to use print("Maximum is: ", max(numbers_list))
directly.
CodePudding user response:
import math
numbers=[]
n=0
def maximum(numbers):
maximum=-1*math.inf
for n in numbers:
if n > maximum:
maximum = n
print("Maximum is: ", maximum)
def minimum(numbers):
minimum=math.inf
for n in numbers:
if n <minimum:
minimum=n
print("Minimum is: ", minimum)
while n != 'done':
n = input('Enter a number: ')
try:
fval=float(n)
numbers.append(float(n))
except:
print("Invalid input")
finally:
if n == 'done':
break
maximum(numbers)
minimum(numbers)
Fixed the mistakes in your code now it working fine.