Creating a List from User input {with Unlimited User Input} - python

I'm trying to create a function definition that asks the user to enter a int or float value to be added to an empty list, but continues to ask the user for input until the user types in -1 or so (<0).
This is what I have so far, but all it does is take the user's input and replicates it 5 times [range(5)] in the new list, and doesn't allow the user to enter anymore values....
I'm very stuck even though I feel it should be pretty easy:
def main():
salesList = []
salesValue = float(input('Please enter total sales in your department: '))
while salesValue < 0:
salesValue = float(input('Please enter a value greater than or equal to zero: '))
if salesValue == -1:
break
else:
for values in range(5):
salesList.append(salesValue)
print(salesList)
main()
Any guidance will be greatly appreciated, as I am new to programming.
:::The easy solution:::
def makeList():
salesList = []
while True:
salesValue = float(input('Please enter total sales in your department: '))
if salesValue == -1:
break
salesList.append(salesValue)
return salesList

You want
while salesValue > 0:
instead of
while salesValue < 0:
As you have it written now, the user inputs a value greater than 0, which automatically kicks it into the else block. You will be able to remove the
if salesValue == -1:
break
as well.

# here you are saying, for 5 iterations do the following
for values in range(5):
# append the single float value salesValue to salesList
# naturally this will happen 5 times
salesList.append(salesValue)
So it makes total sense that you end up with a list containing
the salesValue five times over.
Think about this:
while True: # will loop until a break
salesValue = float(input('Please enter a value greater than or equal to zero (-1 to end): '))
if salesValue < 0:
break
else:
salesList.append(salesValue)

Your current code has a mistake. Basically, when the flow finally reaches the for statement, the value of salesValue does not change, so the program appends the same value 5 times. Try this instead:
def main():
salesList = []
salesValue = float(input())
while salesValue < 0:
salesvalue = float(input())
if salesValue == -1:
break
for values in range (5):
salesList.append(salesValue)
salesValue = float(input("yourmessage"))
print salesList
main()

Related

Why does my program to calculate the average of numbers entered into a while loop not work as expected?

I am new to coding. I would like to attend a course but there are assessments first in order to be chosen.
The question I am stuck on is:
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.
num = 0
inputs = []
while True:
num = int(input("Please enter a number between -1 and 5: "))
if num > -1:
break
else:
inputs.append(int(num))
print (sum(inputs) / len(inputs))
so lets break this down together.
This is fine.
num = 0
inputs = []
You will want to modify this while true statement to be while True (if using python) like below
while True:
Next, it doesn't explicitly say integers, and technically there are different number types, but for simplicity sake we check to see if the number entered is an integer to avoid trying convert a letter to an integer. (This will cause a ValueError). We make a decision to ignore this type of bad input and continue.
input_value = input("Please enter a number between -1 and 5: ")
try:
num = int(input_value)
except ValueError:
continue
The condition for stopping the loop is entering -1 (if I understood the question properly). So, first check to see if the number entered matches the condition to stop: if num == -1: break.
if num == -1:
break
otherwise, you will want to check to be sure the number is in range before it is added to your inputs array, otherwise ignore it and wait for the next input. The question asks for any number, but since you're prompting for specific input, we're making a decision here not to accept numbers out of bounds of what was prompted for.
elif num < -1 or num > 5:
continue
Finally, if input is not -1, and the input is a number between 0-5 inclusive, add it to the array and await the next input.
else:
inputs.append(num)
Finally at the end of the return after -1 was received, it is possible the first number entered was -1, or all values entered were invalid. Both of these scenarios would result in division by 0, and an error being thrown. So you would want to set the minimum number that can be set as the divisor to 1 to ensure you don't crash trying to calculate your answer:
print(sum(inputs) / max(len(inputs), 1))
And now putting it all together:
num = 0
inputs = []
while True:
input_value = input("Please enter a number between -1 and 5: ")
try:
num = int(input_value)
except ValueError:
continue
if num == -1:
break
elif num < -1 or num > 5:
continue
else:
inputs.append(num)
return sum(inputs) / max(len(inputs), 1)
Maybe this is the code you are looking for just changing if num > -1 to if num == -1 to agree with the question you posted:
num = 0
inputs = []
while True:
num = int(input("Please enter a number between -1 and 5: "))
if num == -1:
break
else:
inputs.append(num)
print(sum(inputs) / len(inputs))
and it works just fine having as a result:
Please enter a number between -1 and 5: 5
Please enter a number between -1 and 5: 4
Please enter a number between -1 and 5: 3
Please enter a number between -1 and 5: 2
Please enter a number between -1 and 5: 1
Please enter a number between -1 and 5: -1
3.0

including a loop for the function so it can ask the user to re enter a number if the number is incorrect

I need to modify my program so it includes a prime read with a loop. the document is saying for my getNumber function it should ask the user only to input a number between 2 and 30, the getScores function should ask the user to input a number between 0 and 100. it they don't get a number between that it should tell them re enter a number. I don't get any errors when running the program but not sure what I am missing in order to make sure its running properly to include the re enter a number part. here is the code:
# main
def main():
endProgram = 'no'
print
while endProgram == 'no':
totalScores = 0
averageScores = 0
number = 0
number = getNumber(number)
totalScores = getScores(totalScores, number)
averageScores = getAverage(totalScores, averageScores, number)
printAverage(averageScores)
endProgram = input('Do you want to end the program? yes or no ')
while not (endProgram != 'yes' or endProgram != 'no'):
print('Enter yes or no ')
endProgram = input('Do you want to end the program? (yes or no )')
# this function will determine how many students took the test
def getNumber(number):
number = int(input('How many students took the test: '))
return number
while number < 2 or number > 30:
print('Please enter a number between 2 and 30')
number = int(input('How many students took the test: '))
# this function will get the total scores
def getScores(totalScores, number):
for counter in range(0, number):
score = int(input('Enter their score: '))
return totalScores
while score < 0 or score > 100:
print('Please enter a number between 0 and 100')
score = int(input('Enter their score: '))
return score
# this function will calculate the average
def getAverage(totalScores, averageScores, number):
averageScores = totalScores / number
return averageScores
# this function will display the average
def printAverage(averageScores):
print ('The average test score is: ', averageScores)
# calls main
main()
First suggestion is to change this:
number = int(input('How many students took the test: '))
reason is that, as it is written, this takes the user input and implicitly assumes that it can be cast to an int. What happens if the user enters "hello, world!" as input? It is necessary to take the user input first as a string, and check if it would be valid to convert it:
number = input("enter a number:")
if number.isdecimal():
number = int(number)
Next, the function as a whole has some structural problems:
def getNumber(number):
number = int(input('How many students took the test: '))
return number
while number < 2 or number > 30:
print('Please enter a number between 2 and 30')
number = int(input('How many students took the test: '))
number is passed in as an argument to getNumber. Then the name number is reassigned to the result of reading the user input, and returned... Make sure you understand what the return statement does: once the control flow reaches a return statement, that function terminates, and it sends that value back to the caller. So your while loop never runs.
Maybe this would work better:
def getNumber():
while number := input("enter a number"):
if number.isdecimal() and int(number) in range(0, 31):
return int(number)
print('Please enter a number between 2 and 30')

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")

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)

Categories

Resources