-6

Hi i've recently started learning Python and i want to code something that prompts a user for integer numbers as long as the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number face an error.could some one please tell me what is the problem of my coding ?

largest = -1
smallest = None
while True:
    sval = input('Enter a number: ')
    if sval == 'done' :
       break
try:
    fval = float(sval)
except:
        print('Invalid input')
        continue
        largest=fval
    if fval>largest:
        largest=fval
        print('Maximum is ', largest)
    if smallest is None:
        smallest=fval
        return smallest
    if smallest>fval:
        smallest=fval
        print('Minimum is ',smallest)
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
Sahand Ak
  • 1
  • 1
  • Please show expected behavior, your code vs your explanation is hard to decipher – Jab Feb 04 '19 at 23:13
  • Python is picky about spacing. for right now I would suggest 4 spaces underneath a block. The section under your "except:" line is indented over too far for example or those try except statements are not far enough. I can't tell. – Back2Basics Feb 04 '19 at 23:14
  • s/picky/sane :p – Fynn Becker Feb 04 '19 at 23:15
  • Your code is badly written. First of all, if you input a number the loop will start again. If you input 'done' the loop will break, but it will always perform an exception. Second, your continue operator can't work without a loop. Also, you made two tabulations after except, but one is needed. – Igor Dragushhak Feb 04 '19 at 23:19
  • it showed the mentioned error in this line : – Sahand Ak Feb 04 '19 at 23:19
  • if fval>largest: – Sahand Ak Feb 04 '19 at 23:20

1 Answers1

-2

You need to modify your code so it saves all the inputs that can be converted to floats and not overwrite it. This code accepts the input and checks if it is "done", if not then it tries to convert it to a float and append it to a num list. After the input, it prints out the maximum and minimum of the list.

nums=[]
while True:
    sval = input('Enter a number: ')
    if sval == 'done' :
       break
    else:
       try: nums.append(float(sval))
       except: None
print('Maximum is ', max(nums))
print('Minimum is ', min(nums))
Igor Dragushhak
  • 567
  • 1
  • 3
  • 14
  • 6
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/206345) by showing _why_ this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Blue Feb 05 '19 at 00:14