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).
Related
The purpose of this program is to find the smallest and largest values in a list. The moment the user inputs a negative number, the program should stop. Here is the code I have written so far:
user_inputs = []
number = int(input())
for i in range(number):
value = int(input())
if i >= 0:
user_inputs.append(value)
else:
break
print(min(user_inputs))
print(max(user_inputs))
As you can see, I am new to programming and still struggling to find the logic behind loops. Surely, this code is ridden with mistakes and any helpful improvements is much appreciated. Thanks in advance.
Brother one mistake that you have done is that you are using
for i in range(number):
basically by doing this you are telling compiler that repeat the code in for loop for "number" of times and obviously number would change every time user inputs a new number resulting in error
The right way to make the code do what you want is :
user_inputs = []
while True:
number = int(input('Enter a positive number : '))
if number >= 0 :
user_inputs.append(number)
else:
print(user_inputs)
print('Smallest number in list is : ',min(user_inputs))
print('Largest number in list is : ',max(user_inputs))
break
Here while loop will run continuously until a negative number has been input, so when a negative number is input the while loop woulb break .
You are checking
i
when you should be checking
value
you have to compare value
i.e. if value >= 0
you are using i which is the number of iteration
I have the following code in Python:
If I run the code as it is, if I input the number 9, it will run a list of numbers from 0 to 8. And each time I rerun the code, it will automatically start at 0. What additional code do I need to get this to run from the end result of the previous loop (i.e. I start with 9, and then when I go with 8 the second time, it runs the loop from 8 as that was the end result from the previous loop)?
while user_play == "y":
# Ask the user how many numbers to loop through
ask_user = input("How many numbers would you like to loop? ")
# Loop through the numbers. (Be sure to cast the string into an integer.)
for number in range(0,int(ask_user)):
# Print each number in the range
print(number)
# Once complete, ask the user if they would like to continue
user_play = input("Would you like to continue? ")```
Instead of hardcoding the start of range(0,int(ask_user)) with 0, use a variable start initialized at 0 and updated in each loop with the last value.
start = 0 # initialize at 0
while user_play == "y":
# Ask the user how many numbers to loop through
ask_user = input("How many numbers would you like to loop? ")
# Loop through the numbers. (Be sure to cast the string into an integer.)
for number in range(start, start + int(ask_user)):
# Print each number in the range
print(number)
start = number # update start
# Once complete, ask the user if they would like to continue
user_play = input("Would you like to continue? ")```
You were close. Just two changes are needed.
Changes
1) Outside of the while-loop, set an initial value of number to zero.
2) Change the range to range(number, number+int(ask_user))
Result
number = 0
while user_play == "y":
ask_user = input("How many numbers would you like to loop? ")
for number in range(number, number + int(ask_user)):
print(number)
user_play = input("Would you like to continue? ")
How it works
The idea is that number always means "where you are in the looping" and that ask_user represents how many more steps should be run. The number is starts at zero and is remembered as the steps increase.
Variations
Depending on whether you want a step repeated, consider adding one to the number.
This question already has answers here:
Storing multiple inputs in one variable
(5 answers)
Closed 2 months ago.
hi i am very new to programming and was doing my 6th assignment when i started to draw a blank i feel as thou its really simple but i cant figure out how to continue and would appreciate some advice
showing the correct code would be cool and all but i would really appreciate feed back along with it more so then what to do and if so where i went wrong
down below is what im supposed to do.
Write a program that keeps reading positive numbers from the user.
The program should only quit when the user enters a negative value. Once the
user enters a negative value the program should print the average of all the
numbers entered.
what im having trouble with is getting the number to remember okay user entered 55 (store 55) user entered 10 (store 10) user enter 5 (store 5) okay user put -2 end program and calculate. problem is its not remembering all previous entry's its only remembering the last input (which i guess is what my codes telling it to do) so how do i code it so that it remembers all previous entry's
and here is the code i have so far
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
print (number)
else:
print (number) # these are just place holders
If you really want to remember all previous entries, you can add them to a list, like so:
# before the loop
myList = []
# in the loop
myList = int(input("enter a number. put in a negative number to end"))
Then you can easily compute the mean of the numbers by iterating over the list and dividing by the length of the list (I'll let you try it yourself since its an assignment).
Or, if you want to save (a little) memory, you can add them each time to a variable and keep another variable for the count.
You can use a simple list in order to keep track of the numbers that have been inserted by the user. This list may then get processed in order to calculate the average when every number got read in ...
# This is a simple list. In this list we store every entry that
# was inserted by the user.
numbers = []
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end "))
if number > 0 :
print (number)
# save the number for later usage.
numbers.append(number)
# calculate average
if len(numbers) == 0:
print("You have not inputted anything. I need at least one value in order to calculate the average!")
else:
print("The average of your numbers is: %s" % (sum(numbers) / len(numbers)))
What you need is an list which can store multiple values. It is often use with loops to insert/get value from it.
For instance,
number = 1
numbers = []
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
numbers.append(number)
print (numbers)
What you get is a list of numbers like [4, 10, 17] in ascending order as append() will add number to the back of the list. To get individual numbers out of the list:
numbers[0]
Note that the index inside the bracket starts from 0, so for instance you have a list with [4, 10, 17]. You should use the below 3 to get each of them:
numbers[0]
numbers[1]
numbers[2]
Or even better, with a loop.
for x in numbers:
print (x)
I need to write a program that prompts the user to enter numbers, and stores/displays the largest & smallest integer entered.
However, I can only do this with simple data types (no arrays.)
This is what I have so far.
def main()
while number != -99:
number = input('Enter a number: ')
compare = input('Please enter another number: ')
if compare < number then
compare = smallest
I'm sorry it's just a mess. We're not actually taught python in this class, only psuedo-code then just kind of sent on our own to figure it out.
If you don't need to keep all the numbers, then simply keep two variables maximum and minimum in two variables and only assign the latest user data entry to one or the other depending on whether it is lesser / greater or not - plus a special case to get the first number started in both variables. Here is a little pseudo-code example...
Maximum = NULL
Minimum = NULL
Do
Get User Input string
If Input is Blank Then Exit Loop
Input = Convert Input to Number
If Maximum=NULL
Then Maximum=Input
Else If Input > Maximum Then Input = Maximum
If Minimum=NULL
Then Minimum=Input
Else If Input < Minimum Then Input = Minimum
Loop
Print "Min = " + Minimum
Print "Max = " + Maximum
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.