I don't get this simple for-loop exercise - python

I have to write a program that calculates and displays the highest and second highest value entered by te user. The program must also work with zero or one values entered.
Here are some sample runs:
enter a value or 'stop' -3.2
enter a value or 'stop' -5.6
enter a value or 'stop' 0.5
enter a value or 'stop' 0.3
enter a value or 'stop' stop
the highest value = 0.5
the second highest value = 0.3
and
enter a value or 'stop' stop
the highest value could not be calculated
the second highest value could not be calculated
So i got a code, but it only gives me the minimum and the maximum.
all i got so far is this:
minimum = None
maximum = None
a = int(input("Enter a value or 'stop': "))
while True:
a = input("Enter a value or stop: ")
if a == 'stop':
break
try:
number = int(a)
except:
print("Invalid input")
continue
if minimum is None or number < minimum:
minimum = number
if maximum is None or number > maximum:
maximum = number
print('Maximum= ', maximum)
print('Minimum= ', minimum)
Would be awesome if someone could help me out!

value_list = list()
while True:
a = input("Enter a value or stop: ")
if a == 'stop':
break
else:
try:
value_list.append(float(a))
except:
print("Invalid input")
continue
sorted_list = sorted(value_list)
if len(sorted_list) > 0:
print('the highest value = ', sorted_list[-1])
else:
print('the highest value could not be calculated')
if len(sorted_list) > 1:
print('the second highest value = ', sorted_list[-2])
else:
print('the second highest value could not be calculated')
This should work. You might want to handle float/int scenarios
So, the code actually uses Python list to store the input values in the form of float. Once the user enters stop, we are sorting the values in the list in the ascending order and finally displaying only the top two values i.e at index -1 and -2. Enjoy!

As #rkta said, you don't need line 3 (as the program will ask the same question twice when you start it up).
You only need to alter your code slightly to get your desired program. Instead of using this block:
if minimum is None or number < minimum:
minimum = number
if maximum is None or number > maximum:
maximum = number
Use this block:
if highest is None or number > highest:
highest = number
elif second_highest is None or number > second_highest:
second_highest = number
Obviously you will need to set highest and second_highest to None at the beginning of your program, and change your print statements at the end.

I add my two cents:
# declare a list
inputs = []
while True:
a = input("Enter a value or stop: ")
if a == 'stop':
break
try:
# check if input is float or integer
if isinstance(a, int) or isinstance(a, float):
# append number to the list
inputs.append(a)
except:
print("Invalid input")
continue
# sort list
inputs = sorted(inputs)
# print result if list has at least two values
if len(inputs) >= 2:
# cut the list to the last two items
maxs = inputs[-2:]
print 'Max 1 = ', maxs[1]
print 'Max 2 =', maxs[0]
else:
print 'not enough numbers'

Related

How to use max() and min() for two or three digit numbers from user input

I am trying to find the maximum and minimum values of a series of numbers inputted by the user. I get only a semantic error, where both the max and min values are the last number inputted by the user.
This is what I have tried:
largest = None
smallest = None
while True:
snum = input("Enter a number: ")
if snum != "done" :
try:
largest = max(snum)
smallest = min(snum)
except:
print("Invalid Input")
continue
else:
break
print("Maximum is",largest)
print("Minimum is",smallest)
I used the try and except block to error check the user input.
I checked other similar questions such as: How to show max the max and min from user input, but I did not really understand the answer given.
Your first problem is here:
inum = int(snum)
largest = max(snum)
smallest = min(snum)
You're converting the user value (which always comes in as a string) into an integer and storing it in inum. But then you're calling max and min on the original string value, not the number.
Your second problem is that you are only ever checking one number at a time - snum is always filled with the latest number, with other numbers being forgotten.
You need to store each inputted number in a list, and then call max and min on the list as a whole.
Here's a potential solution:
num_list = []
while True:
user = input("Enter a number: ")
if user == "done":
break
try:
inum = int(user)
num_list.append(inum)
except:
print("Invalid input!")
print("The largest number was", max(num_list))
print("The smallest number was", min(num_list))

Python: I am trying to call a function but the expected results won't come

This program prompts the user for numbers and when the user inputs 'done', it should give the largest value which was input and the smallest.
The function seems to work just fine for the largest variable. Which successfully takes the value of the first input. Later, the program keeps running, and it updates its value for the biggest value typed until done is pressed, so it will print it.
The Problem that I'm having is with the variable 'smallest'. Once the program runs, we type some numbers. When we insert ' done ', when the function is running, the Minimum (which relates to the variable smallest) will still have the value 'None'. So I'm having problems, through the function, to assign the smallest with the inputted values, so that it loses its None value.
If I run the function 'manually', i.e., I don't use this logic in a function, it'll work just fine and provide the results as expected.
inum = None
largest = None
smallest = None
def primeval(sizest) :
if sizest is None :
sizest = inum
while True:
num = input ('Enter an integer number: ')
if num == 'done' :
break
try:
inum = int(num)
except:
print ('Invalid input')
continue
primeval (largest)
primeval (smallest)
#if largest is None : #if done manually it'll work
# largest = inum
#if smallest is None :
# smallest = inum
#resume of the code, after the 'manual primeval'
if inum > largest :
largest = inum
if inum < smallest :
smallest = inum
print ('Maximum is', largest)
print ('Minimum is', smallest)
I would approach your problem differently:
numbers = []
while True:
user_input = input ('Enter an integer number (e for end!): ')
if user_input == 'e':
break
try:
number = int(user_input)
except:
print('Invalid input!')
continue
numbers.append(number)
if len(numbers):
print('Maximum is', max(numbers))
print('Minimum is', min(numbers))
You define a function that has no return value (return statement). In the function you want to work with the value inum, which you do not pass as parameter and which you do not define in the function. You shouldn't do that.
If you prefer a solution without a list:
smallest = None
largest = None
while True:
user_input = input ('Enter an integer number (e for end!): ')
if user_input == 'e':
break
try:
number = int(user_input)
except:
print('Invalid input!')
continue
if smallest is None or largest is None:
smallest = number
largest = number
else:
if number < smallest:
smallest = number
if number > largest:
largest = number
print('Maximum is', largest)
print('Minimum is', smallest)
In this case it makes sense to initialize the two values ​​for the first time with None.
you have to return a value:
def primeval(sizest,inum) :
if sizest is None:
sizest = inum
return sizest
and use it like this:
largest = primeval(largest,inum)

Using += in a while loop but need to exclude highest number

I was tasked with creating a program that takes all the inputted numbers and adds them together except the highest integer out of that list. I am suppose to use while and if then logic but I cannot figure out how to exclude the highest number. I also had to make the program break when the string "end" was put into the console. So far I have,
total = 0
while 1 >= 1 :
value = input("Enter the next number: ")
if value != "end":
num = float(value)
total += num
if value == 'end':
print("The sum of all values except for the maximum value is: ",total)
return total
break
I just have no idea how to make it disregard the highest inputted number. Thanks in advance! I am using python 3 fyi.
Is this what you're trying to do?
total = 0
maxValue = None
while True:
value = input("Enter the next number: ")
if value != "end":
num = float(value)
maxValue = num if maxValue and num > maxValue else num
total += num
else:
print("The sum of all values except for the maximum value is: ",total-maxValue )
# return outside a function is SyntaxError
break
Here you go in regards to keeping it close to your original. Using lists is great in python for this sort of thing.
list = []
while True:
num = input("Please enter value")
if num == "end":
list.remove(max(list))
return sum(list)
else:
list.append(int(num))
if you input 1,2 and 3 this would output 3 - it adds the 1 and 2 and discards the original 3.
You've said it's an assignment so if lists aren't allowed then you could use
max = 0
total = 0
while True:
num = input("Please enter value")
if str(num) == "end":
return total - max
if max < int(num):
max = int(num)
total += int(num)
the easiest way to achieve the result you want is to use python's builtin max function (that is if you don't care about performance, because this way you are actually iterating over the list 2 times instead of one).
a = [1, 2, 3, 4]
sum(a) - max(a)
This not exactly the same as you want it to do, but the result is going to be the same (Since instead of not adding the largest item you can just subtract it in the end).
This should work for you.
total = 0
highest = None
while True:
value = input("Enter the next number: ")
if value != 'end':
num = float(value)
if highest is None or num > highest:
highest = num
total += num
else:
break
print("The sum of all values except for the maximum value is: ",total-highest )
print(total-highest)

Try except bug check

I'm doing a certain online course and I've completed the assignment with this code, but I can still induce a bug with certain inputs, and I can't understand why. I've asked the course mentors (using pseudo code) and they say there's a problem with my try/except statement.
The program should prompt a user for a number, over and over again, returning an error if something non-numeric is entered, with the exception of the string 'done,' in which case it will return the maximum and minimum of all the numbers entered.
Here's the program:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done': break
try:
float(num)
except:
print("Invalid input")
continue
if largest is None:
largest = num
elif largest < num:
largest = num
if smallest is None:
smallest = num
elif smallest > num:
smallest = num
print("Maximum is", largest)
print("Minimum is", smallest)
If you enter the following values as input 1 2 3 pk 27 -37 done, the output is Max: 3, Min -37.
It's driving me crazy. I have do idea why this is happening.
You are casting the input to a float, but not retaining that for later checks.
So later on after the except block, Python is doing string comparisons and is comparing the string "3" to the string "27" and since '3' is 'larger' than '2' it considers "3" larger than "27", much like "b" is larger than "aaabbbbzzz".
To fix it change this:
float(num)
to this:
num = float(num)

print out max and min numbers of the input

I'm asked to write a program which takes in a bunch of numbers and print out the maximum and minimum number of them, below is my code:
maximum = None
minimum = None
while True:
num = raw_input("Enter a number: ")
if num == 'done':
break;
try:
num = int(num)
if num >= maximum:
maximum = num
if num <= minimum:
minimum = num
except:
print "Please Enter A Number!"
continue
print "Max = ",maximum, "Min = ",minimum
The thing is when I run this program the Min always equals to its initial value None, but it will work if I change the second if statement into else. What's wrong with the current one?
If the indentation is correct in the question (and not some copy paste mistake, that is the issue, the minimum = num line needs to be indented towards the right. Also, you need to take care of maximum and minimum being None that would throw error when used in comparison to int in Python 3.x , and would not work correctly for minimum in Python 2.x since no int would be smaller than None.
maximum = None
minimum = None
while True:
num = raw_input("Enter a number: ")
if num == 'done':
break;
try:
num = int(num)
if maximum is None:
maximum = num
minimum = num
if num >= maximum:
maximum = num
if num <= minimum:
minimum = num
except:
print "Please Enter A Number!"
continue
print "Max = ",maximum, "Min = ",minimum
Here is how I would do it:
track = []
while True:
num = raw_input("Enter a number: ")
if num == 'done':
break
try:
num = int(num)
except ValueError:
print "Please Enter A Number!"
continue
track.append(num)
print "Max = ", max(track), "Min = ", min(track)
Well the problem here is with your use of None here as the default value. It happens to work for the maximum because all numbers are greater than None. However, that way the minimum condition will never come true.
There are a few ways to fix this. The obvious and non-pythonic way is to set the minimum to float('inf'). This is kinda obviously infinity. The "better" way would be to change the condition to:
if num <= minimum or minimum==None:
which will automatically set the min on the first pass.
P.S.: I'm guessing you're doing this for algo-practice, because min() and max() functions are built-in.

Categories

Resources