My program asks the user to enter the number of integers they want to enter. Then the user enters integer. Then the program outputs the max and min of those integers.
I cannot use lists, only loops and conditional statements are allowed.
I tried setting max and min to specific values:
max_num = 0
min_num = 0
print("Please enter the number of integers you want to enter:")
inte_num = int(input())
for val in range (1, inte_sum + 1):
user_num = int(input())
if user_num >= max_num:
max_num = user_num
elif use_num <= min_num:
min_num = user_num
print("max:", max_num)
print("min:", min_num)
The expected output of 1, 2, 3, 4 is max: 4 and min: 1, but the actual output is max: 4 and min: 0
It is because you have initialized max_num and min_num to 0 at first. In the specific example you gave, 1,2,3,4, none of the input is smaller than the initial min_num value which is 0, thus min_num does not change.
One way to solve this problem is to initialize max_num and min_num to None and put values into max_num and min_num if they are None, as the following:
max_num = None
min_num = None
print("Please enter the number of integers you want to enter:")
inte_num = int(input())
for val in range (1, inte_num + 1):
user_num = int(input())
if max_num is None or user_num > max_num:
max_num = user_num
if min_num is None or user_num < min_num:
min_num = user_num
print("max:", max_num)
print("min:", min_num)
Related
This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number
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.
My teacher wants me to find the median of 10 inputs from the user by using iterations.
This is how I used iterations to find the sum, number of odd numbers, the max, and the number of prime numbers. But I'm stuck on finding the median.
def Main(): #main function
sum=0
odd=0
temp=0
prime=0
median=0
for i in range(10):
x=float(input("Please enter a number")) #ask user for input 10 times
sum=sum+x #adds all inputs together
if x%2!=0: #all even numbers are divisible by 2
odd=odd+1
if x>=temp: #update temp with current largest input
temp=x
for p in range (2,int(math.sqrt(x))+1):#find prime numbers
if x>=2 and x%p==0: prime=prime+1
import math
def Main(): #main function
sum=0
odd=0
temp=0
prime=0
median=0
my_list =[]
for i in range(10):
x=float(input("Please enter a number: ")) #ask user for input 10 times
sum=sum+x #adds all inputs together
if x%2!=0: #all even numbers are divisible by 2
odd=odd+1
if x>=temp: #update temp with current largest input
temp=x
for p in range (2,int(math.sqrt(x))+1):#find prime numbers
if x>=2 and x%p==0: prime=prime+1
my_list.append(x)
my_list.sort()
size =len(my_list)
if size == 1:
median = my_list[0]
elif size % 2 == 0:
size = int(size/2)
median=(my_list[size-1]+my_list[size])/2
else:
median = my_list[int(size / 2)]
print("sum is ", sum, ",odd is ", odd, ",temp is ", temp, ",prime is ", prime, "median is ", median)
Main()
First of all, as a user pointed out in a comment to your question, your method to determine prime numbers is not correct. You only should increase that counter after all factors have been checked, not after each one.
There are a few questions on StackOverflow that show how to calculate primes in python; here is a slightly improved version of your code with that error fixed (and some style improvement suggestions):
def main():
sum = 0
counter_odd = 0
max_num = None
min_num = None
counter_prime = 0
median = 0
for i in range(10):
x = float(input("Please enter a number"))
sum += x
if x % 2 != 0:
counter_odd += 1
if max_num is None or max_num < x:
max_num = x
if min_num is None or min_num > x:
min_num = x
if x == 0 or x == 1:
counter_prime += 1
elif x > 1:
if not any(x % d == 0 for d in range(2, int(math.sqrt(x)) + 1)):
counter_prime += 1
As to your main question: there are several questions on SO about finding medians in unsorted lists (that would be very similar to searching for medians without having the whole list at the beginning). Maybe search for that without the Python tag, so you get to see some algorithms without tying to a specific language.
For example, in this question you can find the suggestion to use the median of medians approach (Wikipedia).
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()
I have a school work that requires finding the average and the min and max, but I have no clue how to find the min and max, the teacher said we cant use the built in min max in python and also no sorting.I already got the average, just need to do the min and max, here is my code.
import random
import math
n = 0
with open("numbers2.txt", 'w') as f:
for x in range(random.randrange(10,20)):
numbers = random.randint(1,50) #random value between 1 to 50
f.write(str(numbers) + "\n")
print(numbers)
f = open("numbers2.txt", 'r')
fr = f.read()
fs = fr.split()
length = len(fs)
sum = 0
for line in fs:
line = line.strip()
number = int(line)
sum += number
print("The average is :" , sum/length)
Add the below lines to your code.
fs = fr.split()
print(min(int(i) for i in fs))
print(max(int(i) for i in fs))
Update:
min_num = int(fs[0]) # Fetches the first item from the list and convert the type to `int` and then it assigns the int value to `min_num` variable.
max_num = int(fs[0]) # Fetches the first item from the list and convert the type to `int` and then it assigns the int value to `max_num` variable.
for number in fs[1:]: # iterate over all the items in the list from second element.
if int(number) > max_num: # it converts the datatype of each element to int and then it check with the `max_num` variable.
max_num = int(number) # If the number is greater than max_num then it assign the number back to the max_num
if int(number) < min_num:
min_num = int(number)
print(max_num)
print(min_num)
If there is a blank line exists inbetween then the above won't work. You need to put the code inside try except block.
try:
min_num = int(fs[0])
max_num = int(fs[0])
for number in fs[1:]:
if int(number) > max_num:
max_num = int(number)
if int(number) < min_num:
min_num = int(number)
except ValueError:
pass
print(max_num)
print(min_num)
Maybe you could find the max and the min by searching into a number list:
numbers=[1,2,6,5,3,6]
max_num=numbers[0]
min_num=numbers[0]
for number in numbers:
if number > max_num:
max_num = number
if number < min_num:
min_num = number
print max_num
print min_num
If you learn how to think about these types of problems, it should all fall into place.
If you have no numbers, what is the min/max?
If you have one number,
what is the min/max?
If you have n numbers, where n is greater than
1, what are the min and max?