Loops and float numbers - python

I’m taking an online basic programming class and I’m completely lost on this assignment. Our book went over basic loops, but not how to find max, min, or average in a loop with values input by a user. Here is my assignment:
Write a loop control program that will provide important statistics for the grades in a class. The program will utilize a loop to read five floating-point grades from user input. Ask the user to enter the values, then print the following data: Average Maximum Minimum
My textbook and instructor have really given me no guidance on how to use floating numbers in a loop. Here is what I have come up with so far:
for grade in range(5):
int(input("Enter Grade (percentage): "))
if max:
print('Max:')
if min:
print('Min:')
else:
print('Average:')
This allows me to get the loop to run 5 times but how do I actually calculate the min, max, and average for unknown variables?

I don't do python, but I'd know how to approach this problem.
For the average, declare a variable called sum or something and set it to 0. Then, every time you get an input, add that value to the sum. After 5 inputs, print that sum divided by 5. That'll be the average.
To get the max, initiate a variable to 0. On input, check if that input is greater than the currently stored maximum. If so, set the variable to that input. After 5 inputs that variable will contain the max.
Similarly for the min. But make sure to set that variable to something big at the start (like 100000), and then check if the new input is smaller than that variable.
Also, if you're supposed to use floats, don't cast your user input to an int. Use float instead.

You use floating numbers in a loop the same way you use them outside the loop.
The loop does not change anything.
But, it seems you are misunderstanding the task wording:
You are not suppose to print the min, max, and average calculation inside the loop.
That would be impossible, since you can not know them, until the user inputs all 5 grades.
What you are suppose to do inside the loop, are 4 steps:
Read a float from the user. Currently, you are trying to read an int for some reason. Do you know how to read a float in Python?
Add it to the sum you will use after the loop to calculate average.
See if it is the max of all numbers the user inputted so far.
See if it is the min of all the numbers the user inputted so far.
Once you exit the loop, all you have to do is print 3 numbers:
The max and min you found and the average calculation.

You'll want to make a list first,
Then create a for loop that will run 5 times, range(5) should work.
Then exit the loop and run an average, min and max

You can create a simple function for this task. You can do the following:
def take_what(statistic = None):
f = []
for grade in range(5):
f.append(int(input("Enter Grade (percentage): ")))
if statistic == "max":
print('Max: {}'.format(max(f)))
elif statistic == "min":
print('Min: {}'.format(min(f)))
else:
print('Average: {}'.format(sum(f)/len(f)))
print(take_what('max'))
print(take_what('min'))
print(take_what())

Related

Python program to calculate maximum, minimum and average using built in function such as import

Write a program that reads 6 temperatures (in the same format as before), and
displays the maximum, minimum, and mean of the values.
Hint: You should know there are built-in functions for max and min. If you hunt, you
might also find one for the mean.
I managed to do this program.
############################################################################
Modify the previous program so that it can process any number of values. The input
terminates when the user just pressed "Enter" at the prompt rather than entering a
value.
I want my program to calculate the maximum, minimum and average of any numbers entered by the user using the built in functions such as import. The user will have to be able to enter as many numbers he can in the input
import statistics
def my_function():
temp=input("Enter temperature:")
temp=int(temp)
mean_value=statistics.mean(temp)
print(mean_value)
my_function()
You don't need to import anything to compute minimum, maximum and average. You can use min(x) , max(x) and sum(x)/len(x) to compute these values from a list of numeric values.
To do so in your program, however, you have to store multiple inputs in a list of numeric values. You can do so by initiating an empty list at the beginning and prompting new numbers until no more number is entered:
def my_function():
temps = [] ## Empty list to be filled
asking = True ## Switch to keep asking
while asking:
temp=input("Enter temperature:")
try:
temp=int(temp)
temps.append(temp) ## If a number was entered, add it to the list
except: ## Stop asking if no number was entered
asking = False
if len(temps)>0:
mean_value=sum(temps)/len(temps)
min_value = min(temps)
max_value = max(temps)
print(mean_value,min_value,max_value)
else:
print("no numbers were entered")

average value of inputs in python

I am in intro programming class and I just started learning the loops. My question asks about the average value of the inputs and it supposed to be done with while-loops. When the user inputs end instead of a number, that signifies the end of the loop and calculates the average value. The program should print the average value and return it. Also, if the user does not input any number and directly inputs end, the program should print "No numbers were entered". I tried creating the loop, but I do not know what I am missing for my loop to be running.
Also, I am not allowed to use any inbuilt functions like sum, ave, etc.
Here is the code I've written so far
def avgOfTheSum():
total = 0
avg = 0
count = 0
while True:
number = input("Enter next number:")
if number != 'end':
num = float(number)
total = total + num
count = count + 1
average = total/count
else:
print("The Average is:",average)
break
return average
a few tips from my not-so-experienced point of view :
when you increment a variable, eg. 'total = total + num', you can do so with a more compact way : use 'total += num' which does exactly the same thing and lightens your code. Some people find it ugly though, so use it if you will.
You first declared a variable named 'avg' but you then later use 'average', which leads to an error when trying to print 'average' which was not defined because the first 'if' statement was bypassed.
You should use one naming for the average. Either 'avg' or 'average' is okay but remember your code must be easy to understand so try not to squeeze things too much, especially if someone is reviewing it when you are finished.
Use one name and stick to it. That way you don't have an error when the user inputs something that isnt handled by your code.
You could add safe nets to ensure the user passes a number but the most simple ways need to use python built-ins.
You could add something like (not python do not write it like so)
if count = 0
then print 'no numbers entered'
then either :
break if you want to quit the application
or pass if you want to force the user to enter a number (enforcing a new loop)
Hope it helped you a little bit !

I have to write a program that calculates and displays the total score using a for loop?

I'm quite new to the for loops in Python. So, I want to write a program that asks the user to enter to enter 20 different scores and then I want the program to calculate the total and display it on the screen. How could I use a for loop to do this?
edit: I can ask the user to for the different numbers but I don't know how to then add them.
Without giving you the full code here is the pseudocode for what your code should look like
x = ask user for input
loop up till x //Or you could hard code 20 instead of x
add user input to a list
end
total = sum values in list
print total
Here are all the things you need to implement the logic
User input/output:
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html
Loops:
https://wiki.python.org/moin/ForLoop
Summing a list:
https://docs.python.org/2/library/functions.html
Try something like this:
total = 0; # create the variable
for i in range(1,20): # iterate over values 1 to 20 as a list
total += int(input('Please enter number {0}: '.format(i)));
print("Sum of the numbers is '{0}'".format(total))
I'd suggest you go through the tutorials on the python site:
Python 3 is here https://docs.python.org/3/tutorial/index.html
Python 2 is here https://docs.python.org/2/tutorial/index.html
I could go into a lot of detail here and explain everything, however I'd only be duplicating the resources already available. Written far better than I could write them. It would be far more beneficial for you (and anyone else reading this who has a similar issue) to go through these tutorials and get familiar with the python documentation. These will give you a good foundation in the basics, and show you what the language is capable of.
Input
To read a value from the commandline you can use the input function, e.g. valueString = input("prompt text"). Notice the value stored is of type string, which is effectively an array of ASCI/Unicode characters.
So in order to perform math on the input, you first need to convert it to its numerical value - number = int(valueString) does this. So you can now add numbers together.
Adding numbers
Say you had two numbers, num1 and num2, you can just use the addition operator. For example num3 = num1 + num2. Now suppose you have a for loop and want to add a new number each time the loop executes, you can use the total += newNum operator.
total = 0
for _ in range(1,20):
num = input('> ')
total += int(num)
print(total)
I hope this helps.

Random Choice is out of list range in Python?

I am trying to create a program that will guess the number you entered. I was trying to get the computer to get the number in as few guesses as possible so I am doing something like a binary search. I keep getting a Index out of range when I run the code and it gets to total = total[the_low_one:computer2_guess]. I am confused why it is out of range. Should I be adding or subtracting one to the_low_one each time it hits a new low so it stays in range? I would appreciate any help as I am lost. Thanks a bunch in advance!
Code:
def second_computer():
global computer2_score
computer2_score=0
computer2_guess= -1
the_low_one=1
the_high_one=1000000
total= range(1,1000000)
while computer2_guess != pick_number:
computer2_guess=random.choice(total)
if computer2_guess>pick_number:
total=total[the_low_one:computer2_guess]
the_high_one=computer2_guess-1
else:
total=total[computer2_guess:the_high_one]
the_low_one=computer2_guess+1
computer2_score+=1
As total shrinks, the numerical values in the list no longer line up with their indices. You could make it work by doing
total=total[total.index(the_low_one):total.index(the_high_one)]
A simpler approach would be to do away with total altogether and set
computer2_guess=random.randint(the_low_one,the_high_one)

writing an improved version of the Chaos Help

Here is the question proposed by the text.
Write an improved version of the Chaos program from Chapter 1 that allows a user to input two initial values and the number of iterations and then prints a nicely formatted table showing how the values change over time. for example, if the starting values were .25 and .26 with 10 iterations, the table would look like so:
following this is a table with a index 0.25 0.26 as headers and then the 10 iterations in two columns.
here is my initial Chaos program.
# File: chaos.py
def main ():
print ("This program illustrates a chaotic function")
x=eval (input("enter a number between 0 and 1: "))
for i in range (10):
x = 3.9 * x * (1-x)
print (x)
main()
my question is how do i change it to fulfil the above question..
Please if answering take in mind this is my first programming class ever.
You really just have to duplicate the functionality you already have. Instead of just asking the user for an x value, also ask for a y value.
x= float(input("enter a number between 0 and 1: "))
y= float(input("enter another number between 0 and 1: "))
Then in your loop you need to do the same thing you did with the x value to the y value. When you print, remember that you can print two values (x and y) at once by separating them with a comma.
Also, as PiotrLegnica said, you should use float(input(...)) instead of eval(input(...)). Since you know that the user should enter a floating point number (between 0 and 1) you don't have to call eval. Calling eval could be dangerous as it will execute any instruction given to it. That might not matter right now, but it's better to not get in the habit of using it.

Categories