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

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)

Related

How to loop a function def in python until I write the number 0

I'm trying to do a def function and have it add the digits of any number entered and stop when I type the number "0", for example:
Enter the number: 25
Sum of digits: 7
Enter the number: 38
Sum of digits: 11
Enter the number: 0
loop finished
I have created the code for the sum of digits of the entered number, but when the program finishes adding, the cycle is over, but what I am looking for is to ask again for another number until finally when I enter the number "0" the cycle ends :(
This is my code:
def sum_dig():
s=0
num = int(input("Enter a number: "))
while num != 0 and num>0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
if num>0:
return num
sum_dig()
Use list() to break the input number (as a string) into a list of digits, and sum them using a list comprehension. Use while True to make an infinite loop, and exit it using return. Print the sum of digits using f-strings or formatted string literals:
def sum_dig():
while True:
num = input("Enter a number: ")
if int(num) <= 0:
return
s = sum([int(d) for d in list(num)])
print(f'The sum of the digits is: {s}')
sum_dig()
In order to get continuous input, you can use while True and add your condition of break which is if num == 0 in this case.
def sum_dig():
while True:
s = 0
num = int(input("Enter a number: "))
# Break condition
if num == 0:
print('loop finished')
break
while num > 0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
sum_dig()
A better approach would be to have sum_dig take in the number for which you want to sum the digits as a parameter, and then have a while loop that takes care of getting the user input, converting it to a number, and calling the sum_digit function.
def sum_dig(num): # takes in the number as a parameter (assumed to be non-zero)
s=0
while num > 0: # equivalent to num != 0 and num > 0
r = num % 10
s = s + r
num = num // 10
return s
while True:
num = int(input("Enter a number: "))
if num == 0:
break
print("The sum of the digits is: " + sum_dig(num))
This enables your code to adhere to the Single-Responsibility Principle, wherein each unit of code has a single responsibility. Here, the function is responsible for taking an input number and returning the sum of its digits (as indicated by its name), and the loop is responsible for continuously reading in user input, casting it, checking that it is not the exit value (0), and then calling the processing function on the input and printing its output.
Rustam Garayev's answer surely solves the problem but as an alternative (since I thought that you were also trying to create it in a recursive way), consider this very similar (recursive) version:
def sum_dig():
s=0
num = int(input("Enter a number: "))
if not num: # == 0
return num
while num>0:
r= num %10
s= s+r
num= num//10
print("The sum of the digits is:",s)
sum_dig()

Calculate Maximun, Minimun, Average of n numbers

The question is to write a program that asks the user to enter a series of numbers and output, the maximum number in the series, the minimum number in the series, and the average of all the POSITIVE numbers.
The current code I have calculates for the minimum and maximum, but I don't know how to write a code to make it calculate the average.
maximum = None
minimum = None
num = None
while True:
inp = input("PLease enter a number: ")
if inp == "#" :
break
try:
num=float(inp)
except:
print ("Error with this input")
continue
if maximum is None:
maximum = num
minimum = num
if num>maximum:
maximum=num
if num<minimum:
minimum=num
print ("The Maximum is ", maximum)
print ("The Minimum is ", minimum)
You store all inputted numbers in a list and calculate from there:
def avg_pos(d):
if len(d) == 0: # avoid div by 0
return 0
return sum(d)/len(d)
data = []
while True:
try:
n = input("Number: ")
if n == "#":
break
n = int(n)
data.append(n)
except ValueError:
print("Not a number")
print( f"Min: {min(data)} Max: {max(data)} AvgP: {avg_pos([d for d in data if d>0])}" )
Output:
Number: 4
Number: 5
Number: 6
Number: -2
Number: -99
Number: 73
Number: #
Min: -99 Max: 73 AvgP: 22.0
Find the sum each time a positive number is accepted and count each number. At the end you can determine the average
maximum = None
minimum = None
sum_of_positive = 0
count_of_positive = 0
num = None
while True:
inp = input("PLease enter a number: ")
if inp == "#" :
break
try:
num=float(inp)
except:
print ("Error with this input")
continue
if maximum is None:
maximum = num
minimum = num
if num>maximum:
maximum=num
if num<minimum:
minimum=num
if num > 0:
sum_of_positive = sum_of_positive + num
count_of_positive = count_of_positive + 1
if count_of_positive > 0:
average_of_positive = sum_of_positive / count_of_positive
else:
average_of_positive = 0
print ("The Maximum is ", maximum)
print ("The Minimum is ", minimum)
print ("The Average of Positive Numbers is ", average_of_positive)
You need to add a counter variable to know how many rounds you got in the loop.
And also you need a total variable to sum all the num
Then you just need to print total/counter
Use library functions like max, min and sum.
For example max([1,2,3,5,11,8]) gives you 11, min([1,2,3,5,11,8]) gives you 1 and sum([1,2,3,5,11,8]) gives you 30.
So lets say you read the numbers in to a list named numbers, then getting the maximal number is max(numbers), the minimal is min(numbers) and the average is sum(numbers)/len(numbers).
Please notice that if you use python 2 then you need to convert to float before dividing, like this float(sum(numbers))/len(numbers).

I don't get this simple for-loop exercise

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'

Calculating average from raw_input data in a while loop

Fellow python developers. I have a task which I can't seem to crack and my tutor is MIA. I need to write a program which only makes use of while loops, if, elif and else statements to:
Constantly ask the user to enter any random positive integer using int(raw_input())
Once the user enters -1 the program needs to end
the program must then calculate the average of the numbers the user has entered (excluding the -1) and print it out.
this what I have so far:
num = -1
counter = 1
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
counter += anyNumber
answer = counter + anyNumber
print answer
print "Good bye!"
Try the following and ask any question you might have
counter = 0
total = 0
number = int(raw_input("Enter any number: "))
while number != -1:
counter += 1
total += number
number = int(raw_input("Enter another number: "))
if counter == 0:
counter = 1 # Prevent division by zero
print total / counter
You need to add calculating average at the end of your code.
To do that, have a count for how many times the while loop runs, and divide the answer at the end by that value.
Also, your code is adding one to the answer each time because of the line - answer = counter + anyNumber, which will not result in the correct average. And you are missing storing the first input number, because the code continuously takes two inputs. Here is a fixed version:
num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
counter += 1
answer += anyNumber
anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1
else:
print answer/counter #print average
print "Good bye!"
There's another issue I think:
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
The value of the variable anyNumber is updated before the loop and at the beginning of the loop, which means that the first value you're going to enter is never going to be taken in consideration in the average.
A different solution, using a bit more functions, but more secure.
import numpy as np
numbers = []
while True:
# try and except to avoid errors when the input is not an integer.
# Replace int by float if you want to take into account float numbers
try:
user_input = int(input("Enter any number: "))
# Condition to get out of the while loop
if user_input == -1:
break
numbers.append(user_input)
print (np.mean(numbers))
except:
print ("Enter a number.")
You don't need to save total because if the number really big you can have an overflow. Working only with avg should be enough:
STOP_NUMBER = -1
new_number = int(raw_input("Enter any number: "))
count = 1
avg = 0
while new_number != STOP_NUMBER:
avg *= (count-1)/count
avg += new_number/count
new_number = int(raw_input("Enter any number: "))
count += 1
I would suggest following.
counter = input_sum = input_value = 0
while input_value != -1:
counter += 1
input_sum += input_value
input_value = int(raw_input("Enter any number: "))
try:
print(input_sum/counter)
except ZeroDivisionError:
print(0)
You can avoid using two raw_input and use everything inside the while loop.
There is another way of doing..
nums = []
while True:
num = int(raw_input("Enter a positive number or to quit enter -1: "))
if num == -1:
if len(nums) > 0:
print "Avg of {} is {}".format(nums,sum(nums)/len(nums))
break
elif num < -1:
continue
else:
nums.append(num)
Here's my own take on what you're trying to do, although the solution provided by #nj2237 is also perfectly fine.
# Initialization
sum = 0
counter = 0
stop = False
# Process loop
while (not stop):
inputValue = int(raw_input("Enter a number: "))
if (inputValue == -1):
stop = True
else:
sum += inputValue
counter += 1 # counter++ doesn't work in python
# Output calculation and display
if (counter != 0):
mean = sum / counter
print("Mean value is " + str(mean))
print("kthxbye")

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