This is just an introductory class code, and i'm wondering how to find the max of all the next_value variable and compare it to the first_value to print the maximum. My if statement is close but I'm not sure how to fix it
maximum = 0.0
value = int(input("Enter the number of values to process: "))
first_value = float(input("First value: "))
next_value_total = 0
for i in range(1, value):
next_value = float(input("Next value: "))
next_value_total += next_value
if first_value <= next_value:
maximum = next_value
elif first_value > next_value:
maximum = first_value
total = next_value_total + first_value
print("The total is {:.1f}".format(total))
print("The maximum is {:.1f}".format(maximum))
I will try to keep my answer as clean and simple as possible:
value = int(input("Enter the number of values to process: "))
first_value = float(input("First value: "))
total = first_value
maximum = first_value
for i in range(1, value):
next_value = float(input("Next value: "))
total += next_value
if maximum <= next_value:
maximum = next_value
print("The total is {:.1f}".format(total))
print("The maximum is {:.1f}".format(maximum))
I would just put the values in a list and get the sum and max later, like so:
value = int(input("Enter the number of values to process: "))
values = []
for i in range(value):
next_value = float(input("Next value: "))
values.append(next_value)
print("The total is {:.1f}".format(sum(values)))
print("The maximum is {:.1f}".format(max(values)))
However, if you want to keep the same structure:
maximum = 0.0
value = int(input("Enter the number of values to process: "))
first_value = float(input("First value: "))
next_value_total = 0
maximum = first_value # Note: initialize the maximum here
for i in range(1, value):
next_value = float(input("Next value: "))
next_value_total += next_value
if next_value > maximum:
maximum = next_value
total = next_value_total + first_value
print("The total is {:.1f}".format(total))
print("The maximum is {:.1f}".format(maximum))
You can also replace if next_value > maximum: maximum = next_value with just maximum = max(maximum, next_value).
If you used a list instead you could use sum() and max() respectively:
num_values = int(input("Enter the number of values to process: "))
values = []
for i in range(1, num_values + 1):
value = float(input("Please enter value %d: " % i))
values.append(value)
print("The total is {:.1f}".format(sum(values)))
print("The maximum is {:.1f}".format(max(values)))
Example Usage:
Enter the number of values to process: 3
Please enter value 1: 4.0
Please enter value 2: 5.6
Please enter value 3: 7.2324234
The total is 16.8
The maximum is 7.2
Try it here!
Related
This question already has answers here:
Min and Max of a List (without using min/max function)
(11 answers)
Closed 3 months ago.
I am trying to find the maximum and minimum without using the min and max functions. But the maximum is only displaying the first number. Any help?
My code:
count = 0
total = 0.0
num = float(input("Enter the number: "))
maximum = num
minimum = num
while num = 0:
count = count + 1
total = total + num
num = float(input("Enter the number: "))
if num < minimum:
minimum = num
else:
num > maximum
maximum = num
if count == 0:
print("Invalid Entry.")
else:
print("Average Number:", round(total/count, 1))
print("Minimum Number:", minimum)
print("Maximum Number:", maximum)
You did not intended the if condition that is why it is not working
I have modified the code for getting 6 numbers one after one try this
count = 0
total = 0.0
num = float(input("Enter the number: "))
maximum = num
minimum = num
while count < 5:
count = count + 1
total = total + num
num = float(input("Enter the number: "))
if num < minimum:
minimum = num
else:
num > maximum
maximum = num
if count == 0:
print("Invalid Entry.")
else:
print("Average Number:", round(total/count, 1))
print("Minimum Number:", minimum)
print("Maximum Number:", maximum)
count = 0
total = 0.0
num = None
maximum = -float("inf")
minimum = float("inf")
# No need to do the 1st round outside the loop
while num != 0:
num = float(input("Enter the number: "))
count += 1
total += num # += is more concise
# This block needs to be in the while loop
if num < minimum:
minimum = num
if num > maximum: # elif is fine if you initialize minimum and maximumwith the 1st value of num
maximum = num
if count == 0:
print("Invalid Entry.")
else:
print("Average Number:", round(total/count, 1))
print("Minimum Number:", minimum)
print("Maximum Number:", maximum)
I'm not quite sure what you are trying to accomplish here. If your first input is anything other than 0, you will set the variables maximum and minimum to that non-zero number. You will skip the while loop and if statement. If you don't get an error, it will probably just spit out the maximum and minimum being the same number. Can you provide more detail as to what you are trying to do?
you need to check the minimum and maximum for every number. so this part must be in while loop:
if num < minimum:
minimum = num
if num > maximum
maximum = num
also while condition doesn't seem right. you are assigning 0 to num every time. you probably meant num!=0. in this case when user inputs 0 the program terminates.
I am trying to make a code in Python that shows the number of steps needed to reach one from any number using a simple algorithm. This is my code:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(max - min):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num / 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(int(n)+min)+' Steps needed: '+count)
It freezes up without showing an error message, and I have no clue why this happens.
1) You are invoking range() incorrectly.
Your code: for n in range(max - min): produces the range of numbers starting at 0 and ending at the value max-min. Rather, you want the range of numbers starting at min and ending at max.
Try this:
for n in range(min, max):
2) You are performing floating-point division, but this program should use only integer division. Try this:
num = num // 2
3) You are updating the count variable in the wrong loop context. Try indenting it one stop.
4) Your final line could be:
print('Number: '+str(n)+' Steps needed: '+str(count))
Program:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(min, max):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num // 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(n)+' Steps needed: '+str(count))
Result:
Enter the lowest and highest numbers to test.
Minimum number: 3
Maximum number: 5
Number: 3 Steps needed: 7
Number: 4 Steps needed: 2
Number: 5 Steps needed: 5
It looks like it's getting stuck in the while not num == 1 loop. Remember that range() starts at 0, so num is first set to 0, which is divisible by 2, and so will be reset to 0/2... which is 0 again! It will never reach 1 to break the loop.
EDIT: I earlier said that count = 0 needed to be moved. Actually, looking more carefully it seems like the line count = count + 1 line just needs to be moved under the while loop.
a = int(input("Enter mark of BIOLOGY: "))
b = int(input("Enter mark of CHEMISTRY: "))
c = int(input("Enter mark of PHYSICS: "))
sum = a + b + c
x = sum
y = 3
avg = x / y
print("Total marks = ", sum)
print("Average marks = ", avg)
I want to limit the user's input so it only accepts integers from 0 to 90.
To limit the user's input to 0 to 90, you will need to repeatedly ask the user to re-input the data until it meets the 0 to 90 criteria. You can do that by implementing a while loop and then break if the criteria is met. Here's the code:
# Data validation for the variable "a"
while True:
a = int(input("Enter mark of BIOLOGY: "))
if 0 <= a <= 90:
break
else:
print("The mark is not between 0 and 90. Please enter a new mark.")
Hope this helped.
If you are wanting to limit the sum variable, at the end of your code you could simply put an if statement checking that the variable is within the boundary..
if sum > 90:
sum = 90
elif sum < 0:
sum = 0
The following code will ensure that the user inputs the number in the specified range:
while True:
a = int(input("enter mark of BIOLOGY = "))
if 0 <= a <= 90:
break
else:
print("Invalid mark. Please try again.")
while True:
b = int(input("enter mark of CHEMISTRY = "))
if 0 <= b <= 90:
break
else:
print("Invalid mark. Please try again.")
while True:
c = int(input("enter mark of PHYSICS = "))
if 0 <= c <= 90:
break
else:
print("Invalid mark. Please try again.")
sum = a + b + c
x = sum
y = 3
avg = x / y
print("total marks = ", sum)
print("average marks = ", avg)
This will ensure the variables a, b, and c are between 0-90.
Basically, I need to take input unless a negative number is entered and then print the sum of scores along with some other statistics and all. Question has now been resolved.
nums=[]
total= 0
count= 0
while x >= 0:
x = int(input("Enter a number (enter -1 to terminate): "))
if x <= 100:
total = total + x
count+=1
nums.append(x)
if x>100:
print("Invalid entry.")
x = int(input("Enter a number (enter -1 to terminate): "))
print(nums)
print("Number of scores: ", len(nums))
It looks like the 2nd input should be at the end of the while loop
while x >= 0:
if x <= 100:
total = total + x
count+=1
nums.append(x)
if x>100:
print("Invalid entry.")
x = int(input("Enter a number (enter -1 to terminate): "))
That gives the first value a chance to get processed, and means that the final -1 won't be appended
I need to create a function that will print the smallest, largest,and average of n amount of numbers inputed by user.
My function, so far, can print the average and largest value of n amount of numbers entered by user but I'm stuck on finding the smallest value.
This is what I have so far:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=0
l_v=0
while counter<n:
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x>l_v:
l_v=x
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
As #Padraic mentioned, the answer that your posted to your question doesn't work for positive values, since your if-statement only checks if the min value is less that 0.
To fix this, you could just assign the first inputted value to all the variables. This way you wouldn't have to use positive and negative inf variables:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=0
f_v = l_v = s_v = total =int (input("enter first value")) #first value
while counter<(n-1):
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x<s_v: #find minimum
s_v=x
elif x>l_v: #find maximum
l_v=x
print ("the smallest value is {0}".format(s_v))
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
Now your code will run without any issues:
how many?5
enter first value-1
enter next number7
enter next number0
enter next number3
enter next number2
the smallest value is -1
the largest value is 7
('the average is ', 2.2)
You could add the items to a list while the user inputs data.
When the user is done, just use min(), max(), and sum() (and maybe len()) on the list.
Keep track of the lowest number also, set the start value to float(inf) for the min and float(-inf) for the max:
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm, counter = 0, 0
while counter < n:
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
counter += 1
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
You can also use a for loop with range:
n = int(input("how many?"))
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm = 0
for i in range(n):
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
Or using a list comp:
n = int(input("how many?"))
if n > 0:
nums = [int(input("enter next number")) for _ in range(n)]
print ("the largest value is {0}".format(min(nums)))
print("the average is ", sum(nums)/ n)
print("the min value is {}".format(min(nums)))
else:
print("What? it is not possible to find the average, sorry ")
sm += x is augmented assignment which the same as doing sm = sm + x.
When verifying user input and casting you should really use a try/except to catch any exceptions:
def get_num():
while True:
try:
n = int(input("enter next number"))
# user entered valid input, return n
return n
except ValueError:
# could not be cast to int, ask again
print("Not an interger")
while True:
try:
n = int(input("how many?"))
break
except ValueError:
print("Not an interger")
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm, counter = 0, 0
while counter < n:
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
counter += 1
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
This is what I ended up doing... Just kind of worked it out myself through trial and error.
I really appreciate the answers! Gives me a different way of looking at the problem!
Answer:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=1
l_v=0
s_v= 0
f_v = int (input("enter first value"))
while counter<n:
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x<f_v:
s_v=x
elif x>l_v:
l_v=x
print ("the smallest value is {0}".format(s_v))
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()