How to print a list of numbers and their average? - python

For my assignment, I have to create a program that lets the user enter several numbers. I also want to create a list with all the numbers and their average.
But how do I create a code for the list of numbers?
I should exit with a number such as 0 or -999.
One line has invalid syntax.
print (number_list[i], end = " ")
Here is my code.
number_list = []
sum = 0.0
user_number = eval(input("Please enter a number (-999 quits): "))
# Loop until the user is ready to quit
while (user_number != -999):
number_list.append(user_number)
sum = sum + user_number
user_number = eval(input("Please enter a number (-999 quits): "))
# Make sure the user entered something
if (len(number_list) != 0):
# Compute average
average = sum / len(number_list)
# Do output
print ("Using the numbers:")
for i in range(len(number_list)):
# Note the end = " " at the end will keep the output on
# the same line
print (number_list[i], end = " ")
# Note the \n at the start of this line is needed because
# the previous print statement ended with a comma. This
# \n will move the cursor to the next line
print ("\nThe average is:", average)
else:
print ("No values were entered")

Because of Python's indentation rules, any compound statement needs to have at least one statement indented after it.
Let's focus on this section of your code:
for i in range(len(number_list)):
print (number_list[i], end = " ")
print ("\nThe average is:", average)
else:
print ("No values were entered")
A for loop is a compound statement as it needs stuff indented after it. You need to indent them accordingly. Something like:
for i in range(len(eggs)):
print(eggs[i])
The pythonic way to loop over stuff is just to use the value instead of getting the index and then finding it. Python's for loop is more like a foreach loop than an actual for loop. A remake would look like:
for spam in eggs:
print(spam)
Also, you have a check for if there aren't any numbers. Use a normal if statement for that, not one in the loop. The else behind a loop will run when the main part (while or for) finishes without a break.
This:
for spam in eggs:
print(spam)
else:
print("Nothing")
Is not the same as this:
if eggs:
for spam in eggs:
print(spam)
else:
print("Nothing")
Here's the fixed section :D
# If statement to check if list is truthy (nonempty)
if number_list:
# Note the for loop's target 'number'
for number in number_list:
# Note indentation.
print(number, end=" ")
print("\nThe average is:", average)
else:
print("No values were entered")
EDIT: You also have indentation errors after the while loop above this section. I'll leave that to you to fix :)

Related

A program that uses while loop to find average of numbers inputted, and uses a break statement to exit the loop

I would like to write a program that uses a while loop to repeatedly prompt the user for numbers and adds the numbers to a running total. When a blank line is entered, the program should print the average of all the numbers entered. I also would like to use a break statement to exit the while loop.
My Incorrect Work:
y = "\n"
total = 0
k = 0
while True:
x = input("Enter your number here: ")
x = float(x)
total = total + float(x)
k = k + 1
if type(x) != int:
print(total/k)
break
Be aware that the function input() will always outputs a string, so type(input()) != int will always be true.
Try using try-except function, when there is ValueError (example unable to convert blank/letters to float), the exception will be raised and break the loop:
total = 0
k = 0
while True:
x = input("Enter your number here: ")
try:
total += float(x)
k += 1
except ValueError:
if k > 0: #to avoid division by zero
print("Average: ", total/k)
break
Output:
Enter your number here: 3
Enter your number here: 4
Enter your number here: 5
Enter your number here:
Average: 4.0
Bearing in mind the comments already made, here is one such way to perform your task and finishing up when a blank entry is encountered.
total = 0.0
k = 0.0
while True:
x = input("Enter your number here: ")
if (x == " "): # Check for a blank line entry here before attempting to convert to float
print("Average is:", (total/k))
break
x = float(x)
total = total + float(x)
k = k + 1
As noted in the comments, one should check for the blank line entry prior to attempting to convert the entry.
You are immediately casting the value of x that is inputted to a float. So,
if type(x) != int
always is true, meaning the loop breaks after one iteration every time.
Others have already solved your problem in different ways, but I think that explaining our thinking might also be useful.
Currently, your program is not checking correclty the exit condition (empty line is entered instead of a number). When a new line is entered, your program should do one of the two possible scenarios:
when an empty line is entered: print result & exit (break)
else (assume a number is entered): add number to total
No third option is specified, so for now, let's assume that every line will either be an empty line or a number. Will expand it later.
After you decided what to do, the actions should just be easily wrapped in a while True: block - so it should be:
initialize_variables_total_and_count
while True:
read_line
decide_what_to_do:
# in case line was a number
convert_line_to_float
add_float_to_total
increment_count
other_case:
# empty line was entered
calculate_and_print
break
With only two options, you only need to decide once what to do. You can swap around the cases by deciding which condition to check for (and that also results in the other being the "default" behavior for other cases).
It's simpler to check for the line being empty with if line_entered == "":. In this case, any non-empty line is treated like a number, and if it were not one, the float() function will error out and your program crashes.
Checking if a string (the entered line) can be converted to a float is a bit harder. There is just no built-in for that in python, but there is a trick: you can try to convert it to a float, and if that works, it was convertible, and if that errors, it was not. There are other ways too, but this is the simplest - see this question on the topic.
In this case, every number will be added to the total, and every non-number (including the empty line, but also random strings like "asdf") will cause the program to calculate the total and stop.
You can avoid putting both cases into an if-else block by using break or continue. (technicly, you never need to use break or continue, all programs can be written without them. In this case, you could have a boolean variable, named run for example, write while run: and instead of break, do run = False). You can use the fact that both break and continue end the loop early to avoid placing the second case inside an else-block and still have the same behavior (as break and continue already causes skipping the rest of the loop body).
So an example implementation: (testing for == "", not using unstructured control flow)
total = 0
count = 0
run = True
while run:
line = input("Enter your number here: ")
if line == "":
print(total / count)
run = False
else:
total += float(line)
count += 1
I also renamed k to count, x to line and used in-place addition operators.
Another implementation, with break, testing for float with try/except (and re-using that for the entire control flow):
total = 0
count = 0
while True:
line = input("Enter your number here: ")
try:
# order matters here. If the first line errors out, the second won't happen so the count will only be inremented if it was indeed a float
total += float(line)
count += 1
except:
print(f"Average is: {total / count}")
break
Here I removed the run variable, and used a format string to print a bit fancier.
And an example using both continue and break:
total = 0
count = 0
while True:
line = input("Enter your number here: ")
if line != "":
total += float(line)
count += 1
continue
print(f"Average is: {total / count}")
break
You can fancy it a bit with adding more error handling - use three cases:
user entered empty line: print & exit
user entered a number: add to total
user entered something else: ignore line, but tell user what to do
I only provide one example implementation for this, but as you can see, it can be implemented in many ways.
total = 0
count = 0
# good practice to tell the user what to do
print("Average calcuator. Enter numbers one per line to calulate average of, enter empty line to print result & exit!")
while True:
line = input("Enter your number here: ")
if line == "":
print(f"Average is: {total / count}")
break
else:
try:
total += float(line)
count += 1
except ValueError:
print("You should enter a number or an empty line to calculate & exit!")

Python code: explain please

first_num = raw input ("Please input first number. ")
sec_num = raw input (" Please input second number:")
answer = into( first_num) +into( sec_num)
print " Now I will add your two numbers : ", answer
print " Pretty cool. huh ?
print " Now I'll count backwards from ",answer
counter = answer
while (counter >=0):
print counter
counter = counter-1
print " All done !"
I think the first half in a command to add first and second numbers to get sum and the second half is a command to return to start or zero out. I don't know python language.
You should probably try to run the code first and play with it to understand it. The code is simple; the first half take two user inputs and add them to each other then it displays the result.
first_num = input("Please input first number:") # get first number input
sec_num = input("Please input second number:") # get second number input
answer = int(first_num) +int(sec_num) # add up int values of the numbers
print(" Now I will add your two numbers : ", answer) # display answer
As for the second half it takes a number from which it counters downward till zero
print("Now I'll count backwards from ", answer)
counter = answer # set counter start value
while(counter >=0):
print(counter) # display counter value on each iteration
counter = counter-1 # decrement counter value on each iteration
print(" All done !)
I changed your code cause your lines were a bit messy and some incorrect. This version by me works on python3 and NOT python2.7. If you want to learn python I advise you to start with code academy python tutorial

Can't get value to be assigned to variable

import random
print('-\n')
begin=int(raw_input('-\n')
end=int(raw_input('-\n')
rep=int(raw_input('-\n')
def dop():
print random.randinterga
ivfhoierh
while count < rep:
print do
count = count + 1
print('Thanks for using this program!\n')
raw_input('press enter to continue')
Okay, so I really have no idea what iv've done wrong but I keep getting a syntax error and IDLE highlights 'end'.
Edit: C
This is how I would do this:
import random
print 'I will print out random integers from a range you specify.'
begin = int(raw_input('Please enter the starting range: '))
end = int(raw_input('Please enter the end range: '))
rep = int(raw_input('Please enter the repeat value: '))
def get_random():
return random.randint(begin, end)
for _ in range(rep):
print get_random()
Attention to detail is so important.
Problems addressed:
Mismatched parentheses
Inconsistent assignments
Inconsistent use of print
Personal preference over returning, then printing
Renamed function do() for clarity
raw_input() doesn't need \n new lines
randint() gets upset generating ValueError: non-integer arg 1 for randrange() on float values; cast the raw_input() accordingly
(Minor) Corrected spelling in output
Replaced while loop with for loop, removing unneeded variable count and assignments
Hope this helps!
I guess you are using Python 2, judging by raw_input.
Correct your code to:
import random
print 'Hi, I will print out random intergers from a range you specify.\n'
#No need for parenthesis
begin=float(raw_input('Please enter the starting range. \n'))
end=float(raw_input('Please enter the end range. \n'))
rep=float(raw_input('Please enter how many times you cant to repeat the function. \n'))
# ERROR you forgot an extra parenthesis on the end of each of the last 3 lines.
def do():
print random.randint(begin, end)
count = 0
while count < rep:
do() # <- Parenthesis, and no need to print.
count = count + 1
print 'Thanks for using this program!\n' #No need for parenthesis
raw_input('press enter to continue')
Also this:
count = 0
while count < rep:
do() # <- Parenthesis, and no need to print.
count = count + 1
Can be replaced by this:
for count in range(rep):
do()

How to append a list with raw_input in Python and print min and max values

I am trying to build a list with raw inputs.
while True:
inp = raw_input("Enter a number: ")
#edge cases
if inp == "done" : break
if len(inp) < 1 : break
#building list
try:
num_list = []
num = int(inp)
num_list.append(num)
except:
print "Please enter a number."
continue
#max and min functions
high = max(num_list)
low = min(num_list)
#print results
print "The highest number: ", high
print "The lowest number: ", low
print "Done!"
At the moment it seems to only save one of the inputs at a time and therefore the the last raw input is printed as both the max and min.
Any ideas? I am new to Python and could use some direction. So far I have been unable to find the answer in StackOverflow or in the Python documentation.
Thanks in advance!
That's because you keep erasing the list with each iteration. Put num_list = [] outside the while loop:
num_list = []
while True:
...
You should also put these two lines:
high = max(num_list)
low = min(num_list)
outside the loop. There is no reason to keep executing them over and over again.

Flowchart in Python

I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)

Categories