How do I extend a list by one input at a time, rather than stating the number of inputs I intend to put in first?

python for loop
python assign list values to variables
python list
python select from list
python dictionary
consider the list b=["a","b","c"] what is the result of the following b[1:]
python list of lists
while loop python

I'm trying to write a program that prompts the user to input one value and hit enter, then another and hit enter etc, and for the mean of the values to be calculated when the user hits enter without typing a value.

I've botched it so the user indicates how many values they're going to put in but can't figure out how to allow any number of values to be put in one at a time.

b=[]
n= int(input('how many numbers are there? '))
for i in range(n):
    b.append(float(input(' enter value: ')))

print(b)

total =sum(b)
print(total)
length=len(b)
mean= total/length
print(mean)

The code gives the correct answer it is just frustrating that I have to indicate how many values there are. any help would be greatly appreciated, thanks

You're going to want to implement a while loop. A while loop will continue to loop your indented code over and over again until it either reaches a break statement or no longer meets the conditions specified in parenthesis.

In this case, I suggest doing a while(true) loop and then manually breaking out of the loop when there is no input given by the user.

# declare list b
b = []

# while True loop
while(True):
     # get input as a string
     num = input(' enter value: ')
     # if the length of the string of variable num is zero, do
     if(len(num) == 0):
          # break out of the while loop
          break
     else:
          # append to the list as a float
          b.append(float(num))


total = sum(b)
print(total)
mean = total/len(b)
print(mean)

Hope this helps! =)

9. Lists — How to Think Like a Computer Scientist: Learning with , A list is an ordered set of values, where each value is identified by an index. The first example is a list of four integers. Similarly, the * operator repeats a list a given number of times: And we can add elements to a list by squeezing them into an empty slice at the Python provides an alternative that is more readable. 1.10.1. The input Function¶ The hello program of The Classic First Program always does the same thing. This is not very interesting. Programs are only going to be reused if they can act on a variety of data. One way to get data is directly from the user.

An easy way to do it would be to use the iter function with the first argument being an input function and the second argument being the string that will stop the iteration, which can be an empty string:

b = list(map(float, iter(lambda: input('enter value: '), '')))
print(b)

Sample input/output:

enter value: 2
enter value: 7
enter value: 4
enter value: 
[2.0, 7.0, 4.0]

1.10. Input and Output — Hands-on Python Tutorial for Python 3, That is what the built-in function input does: First it prints the string you give as a parameter (in this If we want to reload and modify the hello_you.py program to put an Keyword parameters must be listed at the end of the parameter list. Prompt the user for two numbers, and then print out a sentence stating the sum. raw_input() in Python 2 reads input from the keyboard and returns it. raw_input() in Python 2 behaves just like input() in Python 3, as described above. But Python 2 also has a function called input(). In Python 2, input() reads input from the keyboard, parses and evaluates it as a Python expression, and then returns the resulting value.

Use a while loop:

To further explain, when nothing is passed to input then it is a blank string which evaluates to None Therefore just get the input, if it has something then add it (and maybe some other sanity checks) otherwise stop the loop.

Edit

Added in some checks to see if input is a number before converting to float as well as if the list is empty before doing any calculations

b = []

while True:
    num = input('Enter value (Press Enter to finish): ')
    if num:
        try:
            b.append(float(num))
        except ValueError:
           print("Invalid Input")
    else:
        if b:
            break
        else:
            print("No numbers to calculate yet")

total = sum(b)
length = len(b)
mean = total/length
print(f"Total: {total}\nLength: {length}\nMean: {mean}")

Loop control statements — Object-Oriented Programming in Python , Here is a simple Python example which adds the first ten integers together: Here we add up numbers from a list until the total reaches 100. We don't know how many times we will have to execute the loop, because we don't know the be used to replace loops that are a lot more complicated than this – even nested loops. File streams include two member functions specifically designed to input and output binary data sequentially: write and read. The first one (write) is a member function of ostream inherited by ofstream. And read is a member function of istream that is inherited by ifstream. Objects of class fstream have both members. Their prototypes are:

Just check if the value the user entered is empty:

b=[]

done = False
while not done:
    user_input = input(' enter value: ')
    if user_input:
        b.append(float(user_input))
    else:
        done = True

print(b)

total =sum(b)
print(total)
length=len(b)
mean= total/length
print(mean)

Example: https://repl.it/repls/GenerousEverlastingBugs

18 Most Common Python List Questions, Lists are one of the four built-in data structures in Python, together There's no append() or extend() method for tuples,; You can't remove elements from a tuple. Try putting a negative value, such as -1 or -2 to the index operator to notation when you want to select more than one list element at a time. The head of the snake is always the first element in the list, whereas the tail is the last one. The initial shape of the snake is horizontal, starting from the top-left corner of the screen and facing to the right. While its y-coordinate stays at zero, its x-coordinate decreases from head to tail.

Here's what you could do:

list = []
while 1:
    k = input()
    if k=="":
        break
    else:
        list.append(k)

When the user inputs "", the loop breaks, and you can do whatever you want with your list!

Add or subtract inputs - Simulink, This block can add or subtract scalar, vector, or matrix inputs. If performing only addition, you can use a numerical value equal to the number of inputs. The Sum block first converts the input data type to its accumulator data type, Two or more input ports Sample time — Specify sample time as a value other than -1 Yeah, I love Python one liners. Let us break it down. [code]input() [/code]This is used to fetch input from the user. In this case. We are expecting the user to provide a list of integers.

C Basics - C Programming Tutorial, Otherwise, read "Introduction to Programming in C for Novices and First-time to repeatedly add 1, 2, 3,, to the upperbound int number = 1; while (number so as to use the IO library function to carry out input/output operations (such as printf () Prefix operator (e.g, ++i ) could be more efficient than postfix operator (e.g.,� The insert method modifies the list in place. It doesn't return a modified version of the list. So, on your first insert, you're modifying the list, then assigning to L the return value, which is None. From then on, you're trying to use the insert method of None, which doesn't exist. Just do L.insert rather than L = L.insert

Developing Custom Gradle Task Types, This type of task is good for implementing one-off tasks in your build script. See Organizing Gradle Projects for more details about the buildSrc project. class GreetingTask extends DefaultTask { @Input String greeting = 'hello from GreetingTask' @TaskAction def that is executed against a set of inputs for the first time. The past tense of put is put; the past tense of putt is putted. Since input is formed from "put" rather than "putt", it seems logical that its past tense should be input, rather than "inputted"; "inputted" sounds like a demented golfing term.

Chapter 10 Dynamic UI, At the same time, these tools can make your app substantially more difficult to We'll begin with a simple technique that allows you to modify an input after it observeEvent() to trigger updateSliderInput() whenever the min or max inputs change. They'll first specify how many colours they want, and then supply a value for� Yes, that would work for me but can I determine the amount of scanf inputs at one line depending on the user's input, such as not restricting by 3 numbers, but up to the number that user enters? I considered a for loop but I couldn't make it.

Comments
  • I love this method! To go just a step further you can replace list() with map(float, ) but that's excluding any error checking
  • need to handle the number of input to be taken, value of n
  • My reading of the question was OP wanted to use a zero length input to indicate the inputs have finished, instead of using n to specify how many inputs to take
  • he mentioned n, so better to add n , to complete the solution
  • Oops, my mistake I mistyped. I fixed that
  • Also, I do believe OP doesn't want n as they say "it is just frustrating that I have to indicate how many values there are"