Python max and min - python

I'm pretty new to Python, and what makes me mad about my problem is that I feel like it's really simple.I keep getting an error in line 8. I just want this program to take the numbers the user entered and print the largest and smallest, and I want it to cancel the loop if they enter negative 1.
'int' object is not iterable is the error.
print "Welcome to The Number Input Program."
number = int(raw_input("Please enter a number: "))
while (number != int(-1)):
number = int(raw_input("Please enter a number: "))
high = max(number)
low = min(number)
print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"
raw_input("\n\nPress the enter key to exit.")

The problem is that number is an int. max and min both require lists (or other iterable things) - so instead, you have to add number to a list like so:
number = int(raw_input("Please enter a number: "))
num_list = []
while (number != int(-1)):
num_list.append(number)
number = int(raw_input("Please enter a number: "))
high = max(num_list)
low = min(num_list)
Just as a note after reading dr jimbob's answer - my answer assumes that you don't want to account for -1 when finding high and low.

That's cause each time you pass one integer argument to max and min and python doesn't know what to do with it.
Ether pass at least two arguments:
least_number = min(number1, number2,...,numbern)
or an iterable:
least_number = min([number1, number2, ...,numbern])
Here's the doc

You need to change number to an list of numbers. E.g.,
print "Welcome to The Number Input Program."
numbers = []
number = int(raw_input("Please enter a number: "))
while (number != -1):
numbers.append(number)
number = int(raw_input("Please enter a number: "))
high = max(numbers)
low = min(numbers)
print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"
raw_input("\n\nPress the enter key to exit.")

As mentioned by another answer, min and max can also take multiple arguments. To omit the list, you can
print "Welcome to The Number Input Program."
number = int(raw_input("Please enter a number: "))
high = low = number
while (number != int(-1)):
number = int(raw_input("Please enter a number: "))
high = max(high, number)
low = min(low, number)
print "The highest number entered was ", high, ".\n"
print "The lowest number entered was ", low, ".\n"
raw_input("\n\nPress the enter key to exit.")

num = ''
active = True
largest = 0
smallest = 0
while active:
num = input("Please enter a number")
if num == 'done':
active = False
break
else:
try:
num = int(num)
if largest < num:
largest = num
if smallest == 0 or smallest > num:
smallest = num
except ValueError:
print("Please enter a valid number")
print("Largest no. is " + str(largest))
print("Smallest no. is " + str(smallest))

Related

How do I modulo an input by two to check if the number is even or odd?

How do I modulo an input by two to check if the number is even or odd?
here is my code
num = input("Enter a number: ")
mod = num % 2
if mod > 0:
print("You picked an odd number.")
else:
print("You picked an even number.")
You need to take the int value of the input. int(input("Enter a number: "))
You need to convert the input to an integer like below:
num = int(input("Enter a number: "))
mod = num % 2
if mod > 0:
print("You picked an odd number.")
else:
print("You picked an even number.")
% is for string formatting for strings, for integers it's for modulo.
There is no meaning to test num%2>0. num % 2 is the remainder of the integer division of num by 2. num is even if and only if this remainder equals 0. So the predicate is_even(n) corresponds to num % 2==0.
Your code becomes :
num = int(input("Enter a number: "))
if num % 2==0:
print("You picked an even number.")
else:
print("You picked an odd number.")
You should consider defining a function and then call it like this:
def is_even(n):
return n%2==0
n = int(input("Enter a number:"))
if is_even(n): print("You picked an even number")
else: print("You picked an odd number")

How to stop a while loop processing integers with a string

I'm processing integer inputs from a user and would like for the user to signal that they are done with inputs by typing in 'q' to show they are completed with their inputs.
Here's my code so far:
(Still very much a beginner so don't flame me too much)
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num = int(input("Enter a number: "))
while num != "q":
num = int(input("Enter a number: "))
count += 1
total += num
del record[-1]
print (num)
print("The average of the numbers is", total / count)
main()
Any feedback is helpful!
You probably get a ValueError when you run that code. That's python's way of telling you that you've fed a value into a function that can't handle that type of value.
Check the Exceptions docs for more details.
In this case, you're trying to feed the letter "q" into a function that is expecting int() on line 6. Think of int() as a machine that only handles integers. You just tried to stick a letter into a machine that's not equipped to handle letters and instead of bursting into flames, it's rejecting your input and putting on the breaks.
You'll probably want to wrap your conversion from str to int in a try: statement to handle the exception.
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
Test:
Enter number: 1
got a number
Enter number: 2
got a number
Enter number: alligator
that was not a number: invalid literal for int() with base 10: 'alligator'
Enter number: -10
got a number
Enter number: 45
got a number
Enter number: 6.0222
that was not a number: invalid literal for int() with base 10: '6.0222'
I'll leave it to you to figure out why 6.02222 "was not a number."
changing your code as little as possible, you should have...
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
You may attempt it the way:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()

how should i write this program on python?

can you please tell me why do i get error for this?
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
try:
num=input("Enter a number: ")
if num == 'done':
break
num=int(num)
if largest == None or largest<num:
largest = num
elif smallest == None or smallest > num:
smallest = num
except ValueError:
print ("Invalid input")
break
print ("Maximum number is", int(largest))
print ("Minimum number is", int(smallest))
You may be using Python 2 instead of Python 3 - please check this. If you are using Python 2, you should be using raw_input() instead of input().
Change elif to if:
if largest == None or largest<num:
largest = num
if smallest == None or smallest > num:
smallest = num
That will guarantee both largest and smallest are both integers (unless the first input is done or another invalid value).
You need to check if largest or smallest is None.
Append the user input to a list inside the while loop, and then slice it in the final print statements:
largest = None
smallest = None
nums = []
while True:
try:
num = input("Enter a number: ")
if num == 'done':
break
num = int(num)
nums.append(num)
except ValueError:
print("Invalid input")
break
print("Maximum number is", max(nums))
print("Minimum number is", min(nums))
Example run:
Enter a number: 22
Enter a number: 2
Enter a number: done
Maximum number is 22
Minimum number is 2
Posting the output and/or the error would be very helpful to help you.
You have to change elif into if and remove the break clause inside the except in order to keep asking for numbers even after an invalid input.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == 'done':
break
num=int(num)
if largest == None or largest < num:
largest = num
if smallest == None or smallest > num:
smallest = num
except ValueError:
print ("Invalid input")
print ("Maximum number is", int(largest))
print ("Minimum number is", int(smallest))

Using range function to display a message

I am writing a program for a course that takes user input exam scores and averages them. I have a functioning program, however I need to add a function that uses a range to identify scores entered outside of the 1-100 range and display a message "score out of range. please re enter".
Here is what I have so far:
SENTINEL = float(9999)
scores = []
while True:
number = float(input("Enter exam score (9999 to quit): "))
if number == SENTINEL:
break
scores.append(number)
if not scores:
print("No scores entered")
else:
avg = sum(scores)/len(scores)
print("average of ", len(scores), " test scores is :", avg)
Try this:
SENTINEL = float(9999)
scores = []
while True:
number = float(input("Enter exam score (9999 to quit): "))
while number != SENTINEL and (number < 1 or number > 100):
number = float(input("score out of range. please re enter: "))
if number == SENTINEL:
break
scores.append(number)
if not scores:
print("No scores entered")
else:
avg = sum(scores)/len(scores)
print("average of ", len(scores), " test scores is :", avg)

python loops and arrays

Question: Create a program that allows the user to enter 10 different integers. If the user tries to enter
an integer that has already been entered, the program will alert the user immediately and
prompt the user to enter another integer. When 10 different integers have been entered,
the average of these 10 integers is displayed.
This is my code:
mylist = []
number = int(input("Enter value: "))
mylist.append(number)
while len(mylist) != 10:
number = int(input("Enter value: "))
if number in mylist:
number = int(input("The number is already in the list, enter another number: "))
mylist.append(number)
else:
mylist.append(number)
print(sum(mylist)/float(len(mylist)))
This kind of works but I need to create a loop that will keep on asking the user for another number if the number is in the array. Can you help?
What about:
mylist = []
number = int(input("Enter value: ")) mylist.append(number)
while len(mylist) != 10:
number = int(input("Enter value: "))
while number in mylist:
number = int(input("The number is already in the list, enter another number: "))
mylist.append(number)
print(sum(mylist)/float(len(mylist)))

Categories