I'm new in Python and doing an online tutorial. I have an assignment that I can not accomplish. My problem is that when I run this code, the minimum variable stays the same to None and does not record the new value input.
maximum = None
minimum = None
while True:
try:
num2 = raw_input('Type here ')
if num2 == 'done':break
else:
num = int(num2)
if num <= minimum:
minimum = num
print minimum
elif num >= maximum:
maximum = num
print maximum
except:
print 'Invalid Entry'
print 'Maximum is %d' % maximum
print 'Minimum is %d' % minimum
import sys
maximum = None
minimum = sys.maxsize
while True:
try:
num2 = raw_input('Type here ')
if num2 == 'done':break
else:
num = int(num2)
minimum = min(minimum, num)
maximum = max(maximum, num)
except:
print 'Invalid Entry'
if maximum is None:
minimum = None
print 'Maximum is %d' % maximum
print 'Minimum is %d' % minimum
You are comparing None and int, Python does not know how to do that.
Instead, you should do:
maximum = float('-inf')
minimum = float('inf')
Any int would be greater than -infinity and lower than infinity, so things will work fine. Same thing can not be said about zeroes, so don't use those.
Also, look up min and max builtins.
Your problem is that your are checking if (some number) <= None You cannot compare numbers with None. Instead, minimum=float("inf") and maximum=float("-inf") would set minimum to infinity, and maximum to negative infinity. That way, the first number entered would be less than infinity, setting it to minimum, and greater than negative infinity (setting it to maximum). Note that elif maximum >= num would need to be changed to if maximum >= num (to handle the first entered number).
Related
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).
This program prompts the user for numbers and when the user inputs 'done', it should give the largest value which was input and the smallest.
The function seems to work just fine for the largest variable. Which successfully takes the value of the first input. Later, the program keeps running, and it updates its value for the biggest value typed until done is pressed, so it will print it.
The Problem that I'm having is with the variable 'smallest'. Once the program runs, we type some numbers. When we insert ' done ', when the function is running, the Minimum (which relates to the variable smallest) will still have the value 'None'. So I'm having problems, through the function, to assign the smallest with the inputted values, so that it loses its None value.
If I run the function 'manually', i.e., I don't use this logic in a function, it'll work just fine and provide the results as expected.
inum = None
largest = None
smallest = None
def primeval(sizest) :
if sizest is None :
sizest = inum
while True:
num = input ('Enter an integer number: ')
if num == 'done' :
break
try:
inum = int(num)
except:
print ('Invalid input')
continue
primeval (largest)
primeval (smallest)
#if largest is None : #if done manually it'll work
# largest = inum
#if smallest is None :
# smallest = inum
#resume of the code, after the 'manual primeval'
if inum > largest :
largest = inum
if inum < smallest :
smallest = inum
print ('Maximum is', largest)
print ('Minimum is', smallest)
I would approach your problem differently:
numbers = []
while True:
user_input = input ('Enter an integer number (e for end!): ')
if user_input == 'e':
break
try:
number = int(user_input)
except:
print('Invalid input!')
continue
numbers.append(number)
if len(numbers):
print('Maximum is', max(numbers))
print('Minimum is', min(numbers))
You define a function that has no return value (return statement). In the function you want to work with the value inum, which you do not pass as parameter and which you do not define in the function. You shouldn't do that.
If you prefer a solution without a list:
smallest = None
largest = None
while True:
user_input = input ('Enter an integer number (e for end!): ')
if user_input == 'e':
break
try:
number = int(user_input)
except:
print('Invalid input!')
continue
if smallest is None or largest is None:
smallest = number
largest = number
else:
if number < smallest:
smallest = number
if number > largest:
largest = number
print('Maximum is', largest)
print('Minimum is', smallest)
In this case it makes sense to initialize the two values for the first time with None.
you have to return a value:
def primeval(sizest,inum) :
if sizest is None:
sizest = inum
return sizest
and use it like this:
largest = primeval(largest,inum)
I'm trying to assign a value to the two starting variables in the following code, and change them if necessary (first if and elif), but the smallest gets changed to the string "done" while the largest stays untouched. what am I missing ?
Thank you very much
largest = 0
smallest = 999
while True:
num = raw_input("Enter a number: ")
if largest > num:
largest = num
elif smallest < num:
smallest = num
try:
num = int(num)
except ValueError:
print "Invalid input"
if num == "done" : break
print "Maximum is", largest
print "Minimum is", smallest
Edited the code as per suggestions as follow:
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
try:
num = int(num)
if num > largest:
largest = num
elif smallest < num:
smallest = num
except ValueError:
print "Invalid input"
if num == "done" : break
print "Maximum is", largest
print "Minimum is", smallest
Now it runs correctly
I'm asked to write a program which takes in a bunch of numbers and print out the maximum and minimum number of them, below is my code:
maximum = None
minimum = None
while True:
num = raw_input("Enter a number: ")
if num == 'done':
break;
try:
num = int(num)
if num >= maximum:
maximum = num
if num <= minimum:
minimum = num
except:
print "Please Enter A Number!"
continue
print "Max = ",maximum, "Min = ",minimum
The thing is when I run this program the Min always equals to its initial value None, but it will work if I change the second if statement into else. What's wrong with the current one?
If the indentation is correct in the question (and not some copy paste mistake, that is the issue, the minimum = num line needs to be indented towards the right. Also, you need to take care of maximum and minimum being None that would throw error when used in comparison to int in Python 3.x , and would not work correctly for minimum in Python 2.x since no int would be smaller than None.
maximum = None
minimum = None
while True:
num = raw_input("Enter a number: ")
if num == 'done':
break;
try:
num = int(num)
if maximum is None:
maximum = num
minimum = num
if num >= maximum:
maximum = num
if num <= minimum:
minimum = num
except:
print "Please Enter A Number!"
continue
print "Max = ",maximum, "Min = ",minimum
Here is how I would do it:
track = []
while True:
num = raw_input("Enter a number: ")
if num == 'done':
break
try:
num = int(num)
except ValueError:
print "Please Enter A Number!"
continue
track.append(num)
print "Max = ", max(track), "Min = ", min(track)
Well the problem here is with your use of None here as the default value. It happens to work for the maximum because all numbers are greater than None. However, that way the minimum condition will never come true.
There are a few ways to fix this. The obvious and non-pythonic way is to set the minimum to float('inf'). This is kinda obviously infinity. The "better" way would be to change the condition to:
if num <= minimum or minimum==None:
which will automatically set the min on the first pass.
P.S.: I'm guessing you're doing this for algo-practice, because min() and max() functions are built-in.
I'm trying to write this program which asks for numbers and stores the smallest and largest in two variables which are both None at the beginning.
Somehow the largest number is stored as I want it but the smallest number never makes it.
Here's my code:
largest = None
smallest = None
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try :
num = int(inp)
except :
print "Invalid input"
continue
if num == None or num < smallest :
num = smallest
if num == None or num > largest :
num = largest
print "Maximum is", largest
print "Minimum is", smallest
As soon as I typed in some numbers and end the program with "done" the output looks like this:
Maximum is 56
Minimum is None
I checked the indentation a couple of times.
Don't you mean :
if smallest is None or num < smallest :
smallest = num
if largest is None or num > largest :
largest = num
instead of :
if num == None or num < smallest :
num = smallest
if num == None or num > largest :
num = largest
Because nothing is ever stored in smallest nor largest in the code you posted and as pointed by #MartijnPieters None is always smaller than numbers in python 2.
You can check this link : Is everything greater than None? for further information on that subject.
Also I'd prefer using explicit except such as except ValueError: in you case rather than something that catches everything.
Largest and smallest are never assigned to.
And in the spirit of writing pythonically, you can use min and max :)
largest = None
smallest = None
a=[]
while True:
inp = raw_input("Enter a number: ")
if inp == "done" : break
try :
num = int(inp)
a.append(num)
except :
print "Invalid input"
continue
smallest=a[0]
for x in a:
if x<smallest:
smallest=x
largest=max(a)
print "Maximum is", largest
print "Minimum is", smallest
You can replace the for loop with smallest=min(a)
#d6bels Answer is correct, but you need to add:
if smallest == None:
smallest = num
if largest == None:
largest = num
all code applied:
largest = None
smallest = None
a=[]
while True:
inp = raw_input("Enter a number: ")
if inp == "done": break
try:
num = int(inp)
a.append(num)
except:
print("Invalid input")#For the sake of 2.x-3.x compatability, format your
if smallest == None: #prints as a function
smallest = num
if largest == None:
largest = num
smallest=a[0]
for x in a:
if x<smallest:
smallest=x
largest=max(a)
print("Maximum is " + str(largest))
print("Minimum is " + str(smallest))