Hi so my problem is that i must create a function that asks the user to enter a series of
numbers greater than or equal to zero, one at a time. The user types end to indicate that
there are no more numbers. The function computes the sum of all the values entered
except for the maximum value in the series. (Think of this as dropping the highest
homework score from a series of homework scores.) The function then both prints the
sum and returns the sum. You may assume the user inputs are valid: they will either be a
number greater than or equal to zero, or the string end. Here are some examples of how
the function should behave:
>>> allButMax()
Enter next number: 20
Enter next number: 30
Enter next number: 40
Enter next number: end
The sum of all values except for the maximum value is: 50.0
50.0
>>> allButMax()
Enter next number: 1.55
Enter next number: 90
Enter next number: 8.45
Enter next number: 2
Enter next number: end
The sum of all values except for the maximum value is: 12.0
12.0
>>> x = allButMax()
Enter next number: 3
Enter next number: 2
Enter next number: 1
Enter next number: end
The sum of all values except for the maximum value is: 3.0
>>> print(x)
3.0
>>> allButMax()
Enter next number: end
The sum of all values except for the maximum value is: 0
0
can anyone help me with this?? so far i have this (also this has to be a while loop)
def allButMax():
while True:
number=float(input("Enter next number: "))
if number="end":
break
"end"=0
what i dont know is that i dont know how to add every value other than the max value. how would the function know which value is the maximum value? Also would i have to use another while loop to add all numbers?
I wrote the answer out for this but then saw from a previous answer that I'm not meant to do that. It's true, you do need to do your homework and work this out yourself but here are a few pointers:
Your function operates within a while loop but you can track variables outside of the while loop, your "max_number" can be reassigned a differnt value each time you go through the loop:
def allButMax():
max_number = 0
while True:
print "running while loop"
break
You don't need to use a list, the output number is simply all of the numbers added up minus the largest number.
return total_numbers - max_numer
Your function needs to return a value so use the "return" keyword.
lastly, you might want to look up the "try" and "except" keywords to evaluate the user's input. Did the user give you a number or a string?
try:
int(user_input)
except ValueError:
#user input is a string
Hope this helps without giving away too much :)
All the best!
Related
I have a question: I don't understand why my last function isn't going through and printing anything. I tried fixing where I think I might've messed up, but I can't find it. My task is to create function 1 that checks if all the values in a list are unique or not and return true or false, and the second function is the one that generates the random integer list based on user input (function 1 helps with this). After this, I need to find the nth maximum in the list that is requested by the user, which is the part that doesn't seem to be working.
For Example:
If the list has the values 1 3 7 2 15 20 5 18 11 and the user wanted the:
1st Maximum (n = 1) -> It would return 20 (the highest number)
2nd Maximum (n = 2) -> It would return 18 (the second highest number)
3rd Maximum (n = 3) -> It would return 15 (the third highest number)
#generate list of random numbers
def list_of_nums(start,end,number_of_values):
nums= []
#how can I let integer also be a negative value with range??
for i in range(0,number_of_values):
nums.append(random.randint(start,end))
return nums
#main function of inputs and calls list
def main():
number_of_values= int(input("Please enter the number of values you wish to generate:"))
start= int(input("Please enter the starting # of the values you wish to generate:"))
end= int(input("Please enter the ending # of the values you wish to generate:"))
###
myList= list_of_nums(start,end, number_of_values)
allunique(myList)
print(myList)
#find nth max
def finding_nth_max(nums, nthmax):
sorted_list= nums.sorted()
nthmax= int(input("Please enter the nth maximum you would like to find: "))
print("The nth maximum is", sorted_list[-nthmax])
allunique(myList)
main()
finding_nth_max(myList)
you must add finding_nth_max(your_list_here) function within your main function, for the output of that function to be printed. This must be added after you have called list_of_nums in your main function
you need to call method and nums.sort() does not return anything, it updates the list automatically
def find_nth_max(nums: list):
nums.sort()
print(f'provided list: {nums}')
nthmax= int(input("Please enter the nth maximum you would like to find: "))
print("The nth maximum is", nums[-nthmax])
find_nth_max([2, 5, 1, 8])
I am trying to get into coding and this is kinda part of the assignments that i need to do to get into the classes.
"Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1."
The while loop i can do... The calculation is what im stuck on.
negative = "-1"
passable = "0"
while not passable <= negative:
passable = input("Write a number: ")
I just want to get this to work and a explanation if possible
As pointed out by some of the other answers here, you have to sum up all your answers and divide it by how many numbers you have entered.
However, remember that an input() will be a string. Meaning that our while loop has to break when it finds the string '-1' , and you have to add the float() of the number to be able to add the numbers together.
numbers=[]
while True:
ans=input("Number: ")
if ans=="-1":
break
else:
numbers.append(float(ans))
print(sum(numbers)/len(numbers))
I would initialize a list before asking the user for a number, using a do-while. Then, you add every number to that list unless the number == -1. If it does, then you sum every element in the list and output the average.
Here's pseudocode to help:
my_list = []
do
input_nb = input("Please enter a number: ")
if(input_nb != -1)
my_list.add(input_nb)
while (input_nb != -1)
average = sum(my_list) / len(my_list)
print('My average is ' + average)
You are assigning strings to your variables, which I don't think is your intention.
This will work:
next_input = 0
inputs = []
while True:
next_input = int(input('Please enter a number:'))
if next_input == -1:
break
else:
inputs.append(next_input)
return sum(inputs) / len(inputs)
First, you need to create a container to store all the entered values in. That's inputs, a list.
Next, you do need a while loop. This is another way of structuring it: a loop that will run indefinitely and a check within it that compares the current input to -1, and terminates the loop with break if it does. Otherwise, it appends that input to the list of already entered inputs.
After exiting the loop, the average is calculated by taking the sum of all the values in the entered inputs divided by the length of the list containing them (i.e. the number of elements in it).
I am working on a program that requires the user to enter a number and will continue to loop until a positive number is given. When a positive number is given, it will alert the user and present them with the sum of the digits of their number. However, I thought I had written my code correctly, but it is giving me an incorrect answer. What have I done wrong and how can I fix this?
user_input = float(int(input("Please Enter Your Number:")))
s = 0
while user_input < 0:
float(int(input("Please Enter Another Number: ")))
if user_input > 0:
s += user_input%10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
Four things:
Not sure why you storing the input as float, int should suffice.
If you give a negative input, it will enter the while loop. However, in the while loop, you are not actually assigning the new input to user_input. Fix this by adding user_input =
The while loop guarantees user_input is >= 0, so if user_input > 0: is unnecessary.
Probably the most important, to calculate the sum of digits, you need to repeatedly divide and sum, not just do it once. So, add a while loop.
Final code:
user_input = int(input("Please Enter Your Number: "))
s = 0
while user_input < 0:
user_input = int(input("Please Enter Another Number: "))
while user_input:
s += user_input % 10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
The if statement is generally used to decide if something should be done once.
If you want to keep going until user_input becomes zero, you'll need a while.
Also, I'm not entirely certain why you're storing the number as a float, especially when you make that from an int anyway. It may as well just be an int.
Additionally, you're loop to re-enter the value if it was negative doesn't actually assign the new value to the variable.
And you probably also want to outdent the print statement lest it be done on every iteration of the loop you're about to add.
Of course, some may suggest a more Pythonic way of summing the digits of a positive number is a simple:
sum([int(ch) for ch in str(x)])
That works just as well, without having to worry about explicit loops.
Another way to solve this is using assert and a function:
def sum_num():
# try get user input
try:
user_in = input('Enter Number: ')
assert int(user_in) > 0
except AssertionError:
# we got invalid input
sum_num()
else:
s_d = sum([int(i) for i in user_in])
print('You\'ve entered a positive number! The sum of the digits is: ', s_d)
#run the function
sum_num()
So this will asked user input, if it is not greater than zero it will throw assertion error, which we catch and return the user to inputting the number by calling the function again. If all is well, we split the input into character and add them up. as list('12') gives ['1','2']. We convert to int and add them. :)
The awesome thing about this is you can add more too the asset to capture other issue as floats, character as invalid inputs. E.g.
Assuming literal_eval is important( from ast import literal_eval)
assert isinstance(literal_eval(user_in),int) and int(user_in)>0
Check if user_in is integer and it is greater than 0. So you won’t get issues when user inputs floats or characters.
got a error while compiling the code.
I tried to find smallest and largest value from user's input by storing the input in lists. After 'int' object not iterate problem, couldn't proceed further
largest=0
smallest=0
num=[]
while True:
num = int(input("Please enter a number: "))
for i in num:
if i>largest:
largest=i
for j in num:
if j<smallest:
smallest=j
if num==12:
break
print(largest)
print(smallest)
The moment you issue below code line num is no longer a list, instead its an int type of data.
num = int(input("Please enter a number: "))
As you can understand, there is nothing to iterate over in case of a single integer value.
The right solution is to read your input to a separate variable and append to your list.
input_num = int(input("Please enter a number: "))
num.append(input_num)
Further you will have to change value of your exit clause
if num==12:
break
If you desire to stop the loop after 12 inputs, then use len(num) == 12 in the if condition. In case you want to break loop if input number is 12 then change if condition to if input_num == 12
Note: Your algorithm has logical errors as well. You are assigning smallest to 0 . In case user enters all positive integers as input, your result will incorrect.
You are trying to iterate through a number which is wrong, you have overwritten your num list to an integer. Instead of the following:
num = int(input("Please enter a number: "))
You should save the number in some other variable and add to num list like:
x = int(input("Please enter a number: "))
num.append(x)
I have a homework problem that I cant figure out, can someone help
--Create a function called sums that will prompt the user to enter integer values (either positive or negative). The function should keep separate running totals of the positive values and the negative values. The user should be allowed to continue entering values until he/she enters a zero to stop.
Here's what I got and it doesn't work
number = int(raw_input("Enter and a positive or negative integer: "))
def sums(number):
while (number > 0):
posnumber = int(raw_input("Enter another number or 0 to quit: " ))
number = number + posnumber
print "The positive total is", number
while (number < 0):
negnumber = int(raw_input("Enter another number or 0 to quit: " ))
number = number + negnumber
print "The negative total is", number
it just runs the loop under the first iteration, I'm confused as to what to do to correct it
Because they're separate while loops - the first one is executed, then the second one is executed. You don't want that at all. Here's a layout of what you should do:
take a number from input, store it as inputnum
while inputnum isn't 0
determine whether inputnum is positive or negative
add inputnum to the either posnumber or negnumber
print the total
get a new inputnum
That is, you should have an if inside a while, not two whiles.