Python figuring out the maximum number? - python

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.
I have this so far but im confused on how to create a way to compare the maximum value? Im new to programming and im just asking for help. Also do I include the try and except block before the while with the try? and then error for the except?
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
print num
print "Maximum", largest

nums = []
while True:
n = raw_input("Enter a number: ")
if n == "done":
break
try:
nums.append(int(n))
except ValueError:
print "Invalid input"
print "Min: %d" % min(nums)
print "Max: %d" % max(nums)

largest = None
smallest = None
first_number = True
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
try:
num = int(num)
if first_number:
largest = num
smallest = num
first_number = False
else:
largest = max(largest, num)
smallest = min(smallest, num)
except Exception, e:
print "Not Valid Input!!!"
continue
print "Maximum", largest
print "Minimum", smallest

numbers =[]
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
else:
numbers.append(num)
print max(numbers)
print min(numbers)
So, the logic is to add the numbers to a list and use functions max and min. You can write code to handle exceptions yourself.

largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done": break
if len(num) < 1 : break
try:
num=int(num)
except:
print "Invalid input"
continue
if num is smallest:
smallest = num
if num > largest:
largest = num
print "Maximum is ", largest
print "Minimum is ", smallest

You can do this with a very small modification of your original program: just keep tabs of the smallest and largest numbers as you consider them.
largest = None
smallest = None
while True:
string = raw_input("Enter a number: ")
if string == "done":
break
try:
num = int(string)
except ValueError:
print "Not a number"
continue
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num

largest = None
smallest = None
while True:
num = raw_input('Enter a number: ')
if num == 'done':
print 'Maximum is %s' % largest
print 'Minimum is %s' % smallest
break
try:
num = int(num)
if smallest is None or num <= smallest:
smallest = num
if largest is None or num >= largest:
largest = num
except:
print 'Invalid input'

I am also a python beginning learner, this question I have noticed in 'Python for Everyone' by Charles Russell Severance. My answer is below.
prompt = 'Enter the number: '
initial_value = 0.0
while True:
thing = input(prompt)
if thing == 'done':
break
try:
num = float(thing)
except:
print('Invalid input')
continue
num = float(thing)
if num > initial_value:
max = num
min = initial_value
else:
min = num
print('Max', max)
print('Min', min)

By assigning num to a single value, you are overwriting it through every iteration of the loop. Use a list instead.
num = []
finish = "n"
while finish.lower() == "n"
try:
num.append(int(raw_input("Enter a number: ")))
except ValueError:
print "Not a number"
finish = raw_input("Would you like to add another number? (y/n): ")
print max(num)

Related

Why does this while loop not execute properly

I'm trying to write a basic code that prompts the user for a list of numbers as separate inputs, that then identifies the largest and smallest number. If the user enters anything other than a number the code should return an "invalid input" message. The code seems to run through the two inputs once, but then the while input seems completely broken and I'm not sure where its going wrong.
largest = None
smallest = None
try:
num1 = input("Enter a number: ")
num1 = int(num1)
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if num == "done" :
break
if num > largest:
largest = num
if num < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)
If you check your exit condition of "done" and if the input is not "done" then convert the string to an integer.
Then all the if conditions would correctly and your while loop should run.
largest = None
smallest = None
try:
num1 = input("Enter a number: ")
num1 = int(num1)
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if num == "done" :
break
num = int(num)
if num > largest:
largest = num
if num < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)
heres a simple way to do it:
lst = []
while True:
try:
lst.append(int(input("enter a number: ")))
except:
break
print(f"max is {max(lst)}")
print(f"min is {min(lst)}")
enter a number: 10
enter a number: 22
enter a number: 11
enter a number: 22
enter a number: 4
enter a number: done
max is 22
min is 4
In addition to other corrections:
largest = None
smallest = None
try:
num1 = int(input("Enter a number: "))
largest = num1
smallest = num1
while True:
num = input("Enter a number: ")
if str(num) == "done" :
break
if int(num) > largest:
largest = num
if int(num) < smallest:
smallest = num
else: continue
except:
print('Invalid input')
print("Maximum is ", largest)
print("Minimum is ", smallest)

How can I break the while loop and go to the finally block if the user entered "done"

largest = None
smallest = None
l = []
while True:
try:
num = input("Enter a number: ")
except NameError as err:
if err == "done":
break
else:
print("Invalid input")
finally:
l.append(num)
l.sort()
largest = l[-1]
smallest = l[0]
print("Maximum", largest)
print("Minimim", smallest)
This code looks like it's for Python 2.x, where input() tried to evaluate the input, and signalled an error if you typed a string that's not a variable name. Python 3.x doesn't signal an error when you type done.
So just compare the input. You can later do error checking when you try to convert it to an int.
while True:
num = input("Enter a number")
if num == "done":
break
try:
num = int(num)
except ValueError:
print("Invalid input")
continue
l.append(num)
l.sort()
largest = l[-1]
smallest = l[0]
Refactored logic. NameError won't happen and finally not needed...just put it outside the while when "finally" done.
nums = []
while True:
num = input('Enter a number or "done": ') # num is a string at this point
if num == 'done':
break
try:
# try to convert num to integer...
num = int(num) # This can fail with ValueError, so is in try
nums.append(num) # This won't run if above raises exception
except ValueError:
print("Invalid input")
# No need to sort...
print("Maximum", max(nums))
print("Minimum", min(nums))

Collatz Sequence: Automate the Boring Stuff with Python Chapter 3 Practice Project

This is my working code:
number = int(input())
while number > 1:
if number % 2 == 0:
number = int(number) // 2
print (number)
elif number % 2 == 1:
number = 3 * int(number) + 1
print (number)
Now I'm trying to add the exception that if user input has non-integer value, it should print 'Enter a number'
while True:
try:
number = int(raw_input())
break
except ValueError:
print("Enter a number!")
while number > 1:
....
EDIT: As noted in a comment by Anton, use raw_input in Python 2, and input in Python 3.
I'm a complete beginner so I would appreciate all kinds of tips. Here is how I managed to solve the problem, and for now it seems to work fine:
def collatz(number):
if number%2 == 0:
return number // 2
else:
return 3*number+1
print ('Enter a number:')
try:
number = int(input())
while True:
if collatz(number) != 1:
number= collatz(number)
print(number)
else:
print('Success!')
break
except ValueError:
print('Type an integer, please.')
You could check for ValueError for the except. From docs:
exception ValueError
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
try:
number = int(input())
while number > 1:
if number % 2 == 0:
number = int(number) // 2
print (number)
elif number % 2 == 1:
number = 3 * int(number) + 1
print (number)
except ValueError:
print('Enter a number')
You could do this-
while number != 1:
try:
if number % 2 == 0:
number = int(number) // 2
print (number)
elif number % 2 == 1:
number = 3 * int(number) + 1
print (number)
except ValueError:
print('Enter a number')
break
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return 3 * number + 1
while True:
try:
value = int(input("Eneter a number: "))
break
except ValueError:
print("enter a valid integer!")
while value != 1:
print(collatz(value))
value = collatz(value)
def coll(number):
while number !=1:
if number%2==0:
number= number//2
print(number)
else:
number= 3*number+1
print(number)
while True:
try:
number = int(input("Enter the no:"))
break
except ValueError:
print("Enter a number")
print(coll(number))
I did it like this:
# My fuction (MINI-Program)
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return 3 * number + 1
# try & except clause for errors for non integers from the users input
try:
userInput = int(input("Enter a number: "))
# Main loops till we get to the number 1
while True:
number = collatz(userInput)
if number !=1:
userInput = number
print(userInput)
else:
print(1)
break
except ValueError:
print("Numbers only! Restart program")

Python: How to check if a number is in range and if not have the user enter a new number?

I first asked the user to enter a number and then ran a try/except block. I now want to check to see if the number is in a range between 1-9.
If not I want it to check if int and then check if it is in range.
Here is what I have so far:
def getInt(low, high):
start = 0
while start == 0:
try:
num = input("Enter a number for your calculation in range of 1- 9: ")
num = int(num)
start = 1
asdf = 0
while asdf == 0:
if num > 9 or num < 0:
print("Error: Please only enter numbers between 1-9")
else:
asdf = +1
return num
except:
print("Error: Please only enter numbers")
# main
TOTAL_NUMBERS = 2
LOW_NUMBER = 1
HIGH_NUMBER = 9
num1 = getInt(LOW_NUMBER, HIGH_NUMBER )
print(num1)
num2 = getInt(LOW_NUMBER, HIGH_NUMBER )
print(num2)
Maybe you need this:
def getInt(low, high):
while True:
try:
num = int(input("Enter a number for your calculation in range of 1- 9: "))
except ValueError:
print("Error: Please only enter numbers")
continue
if num not in range(1, 10):
print("Error: Please only enter numbers between 1-9")
else:
return num
You could replace
print("Error: Please only enter numbers between 1-9")
with
num = input("Error: Please only enter numbers between 1-9: ")
or move
num = input("Enter a number for your calculation in range of 1- 9: ")
num = int(num)
into the while loop so it gets called again if the user inputs a number outside the range
def getInt(low, high):
while True: # Keep asking until we get a valid number
try:
numStr = raw_input("Enter a number for your calculation in range of {0} - {1}: ".format(low, high) )
if numStr.isdigit():
num = int(numStr)
if num <= high and num >= low:
return num
except: # Field left empty
pass
getInt(1, 9)

How do I add numbers together using loops?

def adding():
total = 0
x = 0
while x != 'done':
x = int(raw_input('Number to be added: '))
total = x + total
if x == 'done':
break
print total
I cant figure out how to add numbers that a user is inputing, and then stop and print the total when they input 'done'
I'm assuming it's yelling at you with a ValueError when the user inputs "done"? That's because you're trying to cast it as an int before checking if it's a number or the sentinel. Try this instead:
def unknownAmount():
total = 0
while True:
try:
total += int(raw_input("Number to be added: "))
except ValueError:
return total
Alternatively, you can change your own code to work by doing:
def unknownAmount():
total = 0
x = 0
while x != "done":
x = raw_input("Number to be added: ")
if x == "done":
continue
else:
total += int(x)
return total
But beware that if the user enter "foobar", it will still throw a ValueError and not return your total.
EDIT: To address your additional requirement from the comments:
def unknownAmount():
total = 0
while True:
in_ = raw_input("Number to be added: ")
if in_ == "done":
return total
else:
try:
total += int(in_)
except ValueError:
print "{} is not a valid number".format(in_)
This way you check for the only valid entry that's NOT a number first ("done") then holler at the user if the cast to int fails.
There are many similar questions here, but what the hell. Simplest would be:
def adding():
total = 0
while True:
answer = raw_input("Enter an integer: ")
try:
total += int(answer)
except ValueError:
if answer.strip() == 'done':
break
print "This is not an integer, try again."
continue
return total
summed = adding()
print summed
More fancy take on problem would be:
def numbers_from_input():
while True:
answer = raw_input("Enter an integer (nothing to stop): ")
try:
yield int(answer)
except ValueError:
if not answer.strip(): # if empty string entered
break
print "This is not an integer, try again."
continue
print sum(numbers_from_input())
but here are some python features you may not know if you are begginer

Categories

Resources