Finding the Min and Max of User Inputs - python

I'm learning Python, and in trying to find out the min and max values of user number inputs, I can't seem to figure it out.
count = 0
x = []
while(True):
x = input('Enter a Number: ')
high = max(x)
low = min(x)
if(x.isdigit()):
count += 1
else:
print("Your Highest Number is: " + high)
print("Your Lowest Number is: " + low)
break

inp=input("enter values seperated by space")
x=[int(x) for x in inp.split(" ")]
print (min(x))
print (max(x))
output:
Python 3.5.2 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
enter values seperated by space 20 1 55 90 44
1
90

break your program into small manageable chunks start with just a simple function to get the number
def input_number(prompt="Enter A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
if not input: return None #user is done
else: print("That's not an integer!")
then write a function to continue getting numbers from the user until they are done entering numbers
def get_minmax_numbers(prompt="Enter A Number: "):
maxN = None
minN = None
tmp = input_number(prompt)
while tmp is not None: #keep asking until the user enters nothing
maxN = tmp if maxN is None else max(tmp,maxN)
minN = tmp if minN is None else min(tmp,minN)
tmp = input_number(prompt) # get next number
return minN, maxN
then just put them together
print("Enter Nothing when you are finished!")
min_and_max = get_numbers()
print("You entered Min of {0} and Max of {1}".format(*min_and_max)

x is a list, and to append an item to a list, you must call the append method on the list, rather than directly assigning an item to the list, which would override the list with that item.
Code:
count = 0
x = []
while(True):
num = input('Enter a Number: ')
if(num.isdigit()):
x.append(int(num))
count += 1
elif(x):
high = max(x)
low = min(x)
print("Your Highest Number is: " + str(high))
print("Your Lowest Number is: " + str(low))
break
else:
print("Please enter some numbers")
break

Related

Loop and check if integer

I have an exercise:
Write code that asks the user for integers, stops loop when 0 is given.
Lastly, adds all the numbers given and prints them.
So far I manage this:
a = None
b = 0
while a != 0:
a = int(input("Enter a number: "))
b = b + a
print("The total sum of the numbers are {}".format(b))
However, the code needs to check the input and give a message incase it is not an integer.
Found that out while searching online but for the life of me I cannot combine the two tasks.
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
else:
total_sum = total_sum + num
print(total_sum)
break
I suspect you need an if somewhere but cannot work it out.
Based on your attempt, you can merge these two tasks like:
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
try:
a = int(a)
except ValueError:
print('was not an integer')
continue
else:
b = b + a
print("The total sum of the numbers are {}".format(b))
If you want to use an If-Statement, you don't need the else: If the number is not 0 it will just start again until it's 0 sometime.
total_sum = 0
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
total_sum = total_sum + num
if num == 0:
print(total_sum)
break
Since input's return is a string one can use isnumeric no see if the given value is a number or not.
If so, one can convert the string to float and check if the given float is integer using, is_integer.
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
if a.isnumeric():
a = float(a)
if a.is_integer():
b += a
else:
print("Number is not an integer")
else:
print("Given value is not a number")
print("The total sum of the numbers are {}".format(b))

AttributeError: 'str' object has no attribute 'list'

We have to find out the average of a list of numbers entered through keyboard
n=0
a=''
while n>=0:
a=input("Enter number: ")
n+=1
if int(a)==0:
break
print(sum(int(a.list()))/int(n))
You are not saving the numbers entered. Try :
n = []
while True:
a=input("Enter number: ")
try: #Checks if entered data is an int
a = int(a)
except:
print('Entered data not an int')
continue
if a == 0:
break
n.append(a)
print(sum(n)/len(n))
Where the list n saves the entered digits as a number
You need to have an actual list where you append the entered values:
lst = []
while True:
a = int(input("Enter number: "))
if a == 0:
break
else:
lst.append(a)
print(sum(lst) / len(lst))
This approach still has not (yet) any error management (a user enters float numbers or any nonsense or zero at the first run, etc.). You'd need to implement this as well.
a needs to be list of objects to use sum, in your case its not. That is why a.list doens't work. In your case you need to take inputs as int (Can be done like: a = int(input("Enter a number")); ) and then take the integer user inputs and append to a list (lets say its name is "ListName")(listName.append(a)), Then you can do this to calculate the average:
average = sum(listName) / len(listName);
def calc_avg():
count = 0
sum = 0
while True:
try:
new = int(input("Enter a number: "))
if new < 0:
print(f'average: {sum/count}')
return
sum += new
count += 1
print(f'sum: {sum}, numbers given: {count}')
except ValueError:
print("That was not a number")
calc_avg()
You can loop, listen to input and update both s (sum) and c (count) variables:
s, c = 0, 0
while c >= 0:
a = int(input("Enter number: "))
if a == 0:
break
else:
s += a
c += 1
avg = s/c
print(avg)

can a condition be in range in python?

can a range have a condition in python? for example, I wanna start at position 0 but I want it to run until my while statement is fulfilled.
total = 0
num = int(input ( "Enter a number: " ))
range[0,while num != 0:]
total += num
I want to be able to save different variables being in a while loop.
The purpose of my program is to print the sum of the numbers you enter unil you put in 0
my code
num = int(input ( "Enter a number: " )) #user input
number_enterd = str() #holds numbers enterd
total = 0 #sum of number
while num != 0:
total += num
num = int(input ( "Enter a number: " ))
number_enterd = num
print( "Total is =", total )
print(number_enterd) #check to see the numbers ive collected
expected output:
enter an integer number (0 to end): 10
1+2+3+4+5+6+7+8+9+10 = 55
as of right now I'm trying to figure out how to store different variables so i can print them before the total is displayed. but since it is in a loop, the variable just keeps getting overwritten until the end.
If you want to store all the numbers you get as input, the simplest way to do that in Python is to just use a list. Here's that concept given your code, with slight modification:
num = int(input ( "Enter a number: " )) #user input
numbers_entered = [] #holds numbers entered
total = 0 #sum of number
while num != 0:
total += num
numbers_entered.append(num)
num = int(input ( "Enter a number: " ))
print("Total is = " + str(total))
print(numbers_entered) #check to see the numbers ive collected
To get any desired formatting of those numbers, just modify that last print statement with a string concatenation similar to the one on the line above it.
I used a boolean to exit out of the loop
def add_now():
a = 0
exit_now = False
while exit_now is False:
user_input = int(input('Enter a number: '))
print("{} + {} = {} ".format(user_input, a, user_input + a))
a += user_input
if user_input == 0:
exit_now = True
print(a)
add_now()
If you want to store all of the values entered and then print them, you may use a list. You code would end like this:
#number_enterd = str() # This is totally unnecessary. This does nothing
num = int(input ( "Enter a number: " ))
total = 0 #sum of number
numsEntered = [] # An empty list to hold the values we will enter
numsEntered.append(num) # Add the first number entered to the list
while num != 0:
total += num
num = int(input ( "Enter a number: " ))
#number_enterd = num # Unnecesary as well, this overwrites what you wrote in line 2
# It doesn't even make the num a string
numsEntered.append(num) #This adds the new num the user just entered into the list
print("Total is =", total )
print("Numbers entered:", numsEntered) #check to see the numbers you've collected
For example, user enters 5,2,1,4,5,7,8,0 as inputs from the num input request.
Your output will be:
>>>Total is = 32
>>>Numbers entered: [5, 2, 1, 4, 5, 7, 8, 0]
Just as a guide, this is how I would do it. Hope it helps:
num = int(raw_input("Enter a number: "))
numsEntered = [] # An empty list to hold the values we will enter
total = 0 #sum of numbers
while True:
numsEntered.append(num) #This adds the num the user just entered into the list
total += num
num = int(raw_input("Enter a number: "))
print("Total is =", total)
print("Numbers entered:", numsEntered) #check to see the numbers you've collected
In this case, the last 0 entered to get out of the loop doesn't show up. At least, I wouldn't want it to show up since it doesn't add anything to the sum.
Hope you like my answer! Have a good day :)

String, Int Differentiation and Looping in Python

How to complete my program which repeatedly reads numbers until the user enters
“done”. Once “done” is entered, print out the total, count, and average of
the numbers. If the user enters anything other than a number, detect their mistake
using try and except and print an error message and skip to the next number.
count = 0
total = 0
while True:
x = raw_input('Enter number')
x=int(x)
total = total + x
count = count + 1
average = total / count
print total, count, average
The following code should be what you want.
count = 0
total = 0
while True:
x = raw_input('Enter number: ')
if(x.lower() == "done"):
break
else:
try:
x=int(x)
total = total + x
count = count + 1
average = total / count
except:
print("That is not an integer. Please try again.")
print total, count, average
or in Python 3
count = 0
total = 0
while True:
x = input('Enter number: ')
if(x.lower() == "done"):
break
else:
try:
x=int(x)
total = total + x
count = count + 1
average = total / count
except:
print("That is not an integer. Please try again.")
print(total, count, average)

get raw input that is between a set of numbers with some checks

I am trying to get the user input 2 numbers which are split into a list of 2 integers, but unfortunately I can't seem to get them to turn into integers, but I am also unsure of my checks and if it is going to terminate properly and return what I need.
def getlohiint():
lohilist = []
lohi = raw_input("Enter min and max number of points to use(e.g., 2 1000): ")
lohilist = lohi.split()
for x in lohilist:
int(x)
if lohilist[0]<=2 and lohilist[1]<=1000 and lohilist[0]<lohilist[1]:
break
else:
prompt = "%d is not in the range of 2 to 1000; "
prompt1 = "must be at least 2"
prompt2 = "must be no higher than 1000"
if lohilist[0]<2:
print prompt + prompt1
elif lohilist[1]>1000:
print prompt + prompt2
else:
print prompt + prompt1 + prompt2
lohi
high = lohilist[1]
low = lohilist[0]
return(low, high)
You never assign the result of int(x) to anything. It's easiest achieved with a list comprehension:
lohilist = [int(x) for x in lohi.split()]
Note that you can assign to multiple targets at once:
low, high = [int(x) for x in lohi.split()]
would convert everything in lohi to integers and assign to the two variables in one go.
You may want to test for exceptions too here:
def getlohiint():
while True:
lohi = raw_input("Enter min and max number of points to use(e.g., 2 1000): ")
try:
low, high = [int(x) for x in lohi.split()]
except ValueError:
# either not integers or not exactly 2 numbers entered.
print "You must enter exactly 2 numbers here"
continue
if low <= 2 and high <= 1000 and low < high:
# valid input, return
return low, high
if low > 2:
print 'The minimum must be 2 or lower'
if high > 1000:
print 'The maximum must be 1000 or lower'
if low >= high:
print 'The maximum must be greater than the minimum'
int(x) returns an integer value, it does not modify the value of x.
You probably want something like:
def getlohiint():
lohilist = []
lohi = raw_input("Enter min and max number of points to use(e.g., 2 1000): ")
lohilist = lohi.split()
lohilist = [int(x) for x in lohilist]
I would abstract this out a bit: make a function that parses a list of integers from input, then another function which takes a list of integers and tests that they fit your criteria:
import sys
# version compatibility shim
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
else:
# Python 3.x
inp = input
def get_ints(prompt, delimiter=None):
while True:
try:
return [int(i) for i in inp(prompt).split(delimiter)]
except ValueError:
pass
def get_lo_hi_ints(prompt, min_=None, max_=None):
while True:
try:
lo, hi = get_ints(prompt)
if lo >= hi:
print("First value must be < second value")
elif (min_ is not None and lo < min_):
print("Low value must be >= {}".format(min_))
elif (max_ is not None and hi > max_):
print("High value must be <= {}".format(max_))
else:
return lo, hi
except ValueError:
print("Please enter 2 values!")
then you can use it like
min_points, max_points = get_lo_hi_ints("Enter min and max number of points to use(e.g., 2 1000): ", 2, 1000)

Categories