I am in a Python class and a few weeks ago we were given these sets of instructions for an assignment:
Write a program that utilizes a loop to read a set of five floating-point
values from user input. Ask the user to enter the values, then print the
following data:
Total,
Average,
Maximum,
Minimum,
Interest at 20% for each original value entered by the user.
Use the formula: Interest_Value = Original_value + Original_value*0.2
I uploaded a different assignment for the class, but this problem is driving me crazy because I cannot figure out why minimum number, and interest does not work correctly. Any suggestions would be appreciated. Thank you.
This is the code I wrote. My problem is the minimum number does not output and the printed interest is wrong.
entered_number = 0
sum = 0
average = 0
max_number = 0
min_number = 0
interest = 0.2
for entered_number in range(5):
entered_number = float(input('Enter a number: '))
if entered_number > max_number:
max_number = entered_number
if entered_number < min_number:
min_number = entered_number
sum = sum + entered_number
average = sum / 5
interest = entered_number + (entered_number * interest) # removing the () didn't solve
print('Total:', sum)
print('Average:', average)
print('Maximum number:', max_number)
print('Minimum number:', min_number)
print('Interest at 20% for each entered number is: ', interest)
My output example:
Enter a number: 20
Enter a number: 30
Enter a number: 40
Enter a number: 50
Enter a number: 60
Total: 200.0
Average: 40.0
Maximum number: 60.0
Minimum number: 0
Interest at 20% for each entered number is: 90123060.0
Try setting your min_number and max_number values to positive and negative infinity respectively, upon intialization.
Then for the interest it sounds like you need to collect multiple values and output all of them if I understand correctly. And you don't want to overwrite the interest variable because that is constant between all numbers so use current_interest and move it inside the loop.
For the total you shouldn't use sum as a variable name since it overwrites the function. instead use total, and move it inside the loop so that the value updates for each input received.
import math
entered_number = 0
total = 0
average = 0
max_number = -math.inf
min_number = math.inf
interest = 0.2
interest_list = []
for entered_number in range(5):
entered_number = float(input('Enter a number: '))
if entered_number > max_number:
max_number = entered_number
if entered_number < min_number:
min_number = entered_number
current_interest = entered_number + (entered_number * interest)
interest_list.append(current_interest) # collect all interest values
total += entered_number # dont use sum as a variable name
average = total / 5
print('Total:', total)
print('Average:', average)
print('Maximum number:', max_number)
print('Minimum number:', min_number)
print('Interest at 20% for each entered number is: ', interest_list)
OUTPUT
Enter a number: 20
Enter a number: 30
Enter a number: 40
Enter a number: 50
Enter a number: 60
Total: 200.0
Average: 40.0
Maximum number: 60.0
Minimum number: 20.0
Interest at 20% for each entered number is: [24.0, 36.0, 48.0, 60.0, 72.0]
Related
Write a program in Python that reads a sequence of integer inputs (data) from the user and then prints the following results:
the total of all the inputs
the smallest of the inputs
the largest of the inputs
the number of even inputs
the number of odd inputs
the average of all of the inputs
You do not know how many numbers the user will want to type in, so you must ask her each time if she has another number to add to the sequence.
So far this is my code but I want to know if there's a way without using the sys module
import sys
# declare a variable largest which has smallest integer value
# -sys.maxsize gives the smallest integer value,you can also use any smallest value
largest = -sys.maxsize
# declare a variable smallest, that is assigned with maximum integer value
smallest = sys.maxsize
# declare variables total to store the sum of all numbers
total = 0
# option variable is to store the user option Y or N
option = 'y'
# declare variables to count odd, even and totalCount
evenCount = 0
oddCount = 0
totalCount = 0
print("This program will calculate statistics for your integer data.")
# run the loop when the user enters y or Y
while option == 'y' or option == 'Y':
# take input of number
number = int(input("Please type a number: "))
# add the number to total
total = total + number
# increase totalCount
totalCount = totalCount + 1
# calculate smallest
if number < smallest:
smallest = number
# calculate largest
if number > largest:
largest = number
# calculate count of even and odd numbers
if number % 2 == 0:
evenCount = evenCount + 1
else:
oddCount = oddCount + 1
option = input("Do you have another number to enter? ")
# calculate average
average = total / totalCount
# print the output
print("\nThe total of your numbers is:", total)
print("The smallest of your numbers is:", smallest)
print("The largest nof yout numbers is:", largest)
print("The number of even numbers is:", evenCount)
print("The number of odd numbers is:", oddCount)
print("The average of your numbers is:", average)
The answer to "can it be done?" when it comes to programming is almost always "yes."
In this case, you can test if you're on the first loop iteration and set smallest and largest accordingly.
E.g.
option = 'y'
first_loop = True
while option.lower() == 'y':
x = int(input("Please type a number: "))
if first_loop:
smallest = x
first_loop = False
elif x < smallest:
smallest = x
option = input("Do you have another number to enter? ")
print(f"Smallest number entered is {smallest}")
You might also collect the input numbers into a list.
option = 'y'
inputs = []
while option.lower() == 'y':
x = int(input("Please type a number: "))
inputs.append(x)
option = input("Do you have another number to enter? ")
Now if you have all of the input numbers in inputs, then calculating a minimum and maximum is just min(inputs) and max(inputs).
Interesting approach, when I have problems like this I use float('inf') or float('-inf'). Can easily be worked into your approach.
The question is to write a program that asks the user to enter a series of numbers and output, the maximum number in the series, the minimum number in the series, and the average of all the POSITIVE numbers.
The current code I have calculates for the minimum and maximum, but I don't know how to write a code to make it calculate the average.
maximum = None
minimum = None
num = None
while True:
inp = input("PLease enter a number: ")
if inp == "#" :
break
try:
num=float(inp)
except:
print ("Error with this input")
continue
if maximum is None:
maximum = num
minimum = num
if num>maximum:
maximum=num
if num<minimum:
minimum=num
print ("The Maximum is ", maximum)
print ("The Minimum is ", minimum)
You store all inputted numbers in a list and calculate from there:
def avg_pos(d):
if len(d) == 0: # avoid div by 0
return 0
return sum(d)/len(d)
data = []
while True:
try:
n = input("Number: ")
if n == "#":
break
n = int(n)
data.append(n)
except ValueError:
print("Not a number")
print( f"Min: {min(data)} Max: {max(data)} AvgP: {avg_pos([d for d in data if d>0])}" )
Output:
Number: 4
Number: 5
Number: 6
Number: -2
Number: -99
Number: 73
Number: #
Min: -99 Max: 73 AvgP: 22.0
Find the sum each time a positive number is accepted and count each number. At the end you can determine the average
maximum = None
minimum = None
sum_of_positive = 0
count_of_positive = 0
num = None
while True:
inp = input("PLease enter a number: ")
if inp == "#" :
break
try:
num=float(inp)
except:
print ("Error with this input")
continue
if maximum is None:
maximum = num
minimum = num
if num>maximum:
maximum=num
if num<minimum:
minimum=num
if num > 0:
sum_of_positive = sum_of_positive + num
count_of_positive = count_of_positive + 1
if count_of_positive > 0:
average_of_positive = sum_of_positive / count_of_positive
else:
average_of_positive = 0
print ("The Maximum is ", maximum)
print ("The Minimum is ", minimum)
print ("The Average of Positive Numbers is ", average_of_positive)
You need to add a counter variable to know how many rounds you got in the loop.
And also you need a total variable to sum all the num
Then you just need to print total/counter
Use library functions like max, min and sum.
For example max([1,2,3,5,11,8]) gives you 11, min([1,2,3,5,11,8]) gives you 1 and sum([1,2,3,5,11,8]) gives you 30.
So lets say you read the numbers in to a list named numbers, then getting the maximal number is max(numbers), the minimal is min(numbers) and the average is sum(numbers)/len(numbers).
Please notice that if you use python 2 then you need to convert to float before dividing, like this float(sum(numbers))/len(numbers).
I have to make a program where I have to ask the user for a number which I would add to a randomly generated value. If the total sum is over 50 then the loop should break however if it's not then it should generate a new value and add it to the user input until it goes over 50
My code:
import random
i = random.randint(1, 50)
num = input("Please enter a number: ")
while i <= 50:
total = i + int(num)
print("The total is " + str(total))
if total > 50:
break
The code works fine when the total is over 50 but if it's not then it would keep repeating the same line infinitely
Desired result:
Please enter a number: 23
Your total is 41
Your total is 35
Your total is 63 <------ The code would break here since it's over 50
My actual result:
Please enter a number: 36
Your total is 44
Your total is 44
Your total is 44
Your total is 44
Your total is 44
Your total is 44
Your total is 44
Your total is 44
Your total is 44
This will keep repeating
The problem is that you're not actually updating total. Your while test is also not actually performing anything useful here. You can replace it with while True or with while total <= 50.
import random
i = random.randint(1, 50)
num = input("Please enter a number:\n>>> ")
total = int(num)
while True:
total += i
print("The total is", total)
if total > 50:
break
print('done')
Now, are you actually intending to add the same number every time? I suspect not, but maybe. If you intend to add a new random number every time, this is what you might have meant to do:
import random
num = input("Please enter a number:\n>>> ")
total = int(num)
while total <= 50:
total += random.randint(1, 50)
print("The total is", total)
print('done')
You should initialize total outside the loop, and generate a random number inside while each time the number is less than 50:
import random
total = 0
i = random.randint(1, 50)
print('Generated random number:', i)
total += i
while i <= 50:
print("The total is " + str(total))
if total > 50:
print('Total Exceeded 50!!!')
break
else:
j = random.randint(1, 50)
total +=j
print('Generated random number:', i)
I've been struggling with this problem for a while now since loops are a bit confusing to me. Essentially, I think I got some of the more difficult stuff (for me at least) out of the way. The issue is that I need the average of 3 students per exam not 6 students per exam, which is what my current code gives.
If what I am asking isn't clear let me know and I will clear it up.
My inputs are n = 3 and m = 2.
def readGrade():
grade = int(input("Enter the grade: "))
while grade > 100 or grade < 0:
print("Invalid Grade")
grade = int(input("Enter the grade: "))
return grade
def examAverage(m):
average = 0
for i in range(n):
readGrade()
average = average + readGrade()
return (average / n)
n = int(input("Enter the number of students: "))
m = int(input("Enter the number of exams: "))
for i in range(m):
print("The average of exam", i + 1, "is:", examAverage(m))
You are calling readGrade() two times within examAverage()
I think this is what examAverage() should be:
def examAverage(m):
average = 0
for i in range(n):
this_grade = readGrade()
average = average + this_grade
return (average / n)
I am trying to write as the question is stated, Write a program that accepts a positive integer from the user and print the first four multiples of that integer; Use while loop (Python)
total = 0
number = int(input("Enter integer: "))
while number <= 15:
total = total + number
print(number)
SAMPLE
Enter integer: 5
0
5
10
15
this is the example my professor wanted
This is what i have so far, but i'm a bit lost...
You should loop over a counter variable instead of a hard coded limit
counter = 1
while counter <= 4:
counter += 1
total = total + number
print(number)
The loop condition should be set on total, not number, and total should be incremented by 1, not number (assuming total is used as a loop counter):
total = 0
number = int(input("Enter integer: "))
while total <= 3:
print(total * number)
total = total + 1
Sample:
Enter integer: 5
0
5
10
15
A normal while loop that counts upto 4:
count, total = 0, 0
number = int(input("Enter integer: "))
while count < 4:
print(total)
total = total + number
count += 1
Python for loop is more pythonic than while:
number = int(input("Enter integer: "))
for i in range(4):
print(number * i)
Although you have the right idea from the example there's still a couple of things the sample is missing.
1. You don't check whether the input is positive or not
2. The while loop is dependent on knowing the input
Try the following:
# Get Input and check if it's positive
number = int(input('Enter positive integer: '))
if number <= 0:
number = int(input('Not positive integer, enter positive integer: '))
# This increments i by one each time it goes through it, until it reaches 5
i=1
while i < 5:
new_number = number*i
i = i + 1
print(new_number)
Note: This does not take into account if the input is a letter or string. If so, it'll throw an error.