I am trying to display the largest number in a user inputed array. I am not allowed to use a built in sort function. Here is the code I have crafted. As it runs it always returns the first integer in my list instead of the largest.
integers = []
print("Please enter a list of integers.")
print("To finish entering the integers, enter a 0 for the value.")
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
integerIn = input("Please enter an integer < 0 to finish >: ")
if integerIn == int("0"):
done = True
else:
integers.append(integerIn)
return integers
floatInput()
def largestNumber(array):
maxNum = -1
for i in array:
if i > maxNum:
maxNum = i
return maxNum
def displayArray():
print("The Maximum value is: " + str(largestNumber(integers)))
displayArray()
Right code for this task:
def float_input():
integers = list()
while True:
value = int(input('Enter value (or 0 to exit): '))
if value != 0:
integers.append(value)
elif value == 0:
break
return integers
print(max(float_input()))
Or, if you want to create your own largestNumber function use this:
def largest_number(lst):
max_elem = lst[0]
for j in lst[1:]:
if j > max_elem:
max_elem = j
return max_elem
print(largest_number([1, 2, 5, 3, 4])) # print 5
Related
I now this isn't right, but I am I on the right path? I am super new to this. Any help is appreciated. The assignment is to create a script that allows the user to input a number. Then If 1 is entered, a countdown from that number to zero is printed.
If 2 is entered, the factorial of the number is printed.
num = int(input("Enter a number greater than 1: "))
if num<0:
print("please enter number greater than zero");
elif(num==0):
print("Please enter number greater than 0");
else:
select = int(input("Enter 1 to countdown from or enter 2 to get the factorial"))
select = true
def factorial():
factorial=1;
if num<0:
print("Factorial does not defined for negative integer");
elif(num==0):
print("The factorial of 0 is 1");
else:
while(num>0):
factorial=factorial*num
num=num-1
print("factorial of the given number is: ")
print(factorial)
def countdown():
countDown = num
while (countDown >= 0):
print(countDown)
countDown = countDown - 1
if countDown == 0:
print("Done!")
break
Yes, you are on the right path. Don't use ; at the end of statements, its not required in python. You can add this condition so as to call the functions based on the user input.
else:
select = int(input("Enter 1 to countdown from or enter 2 to get the factorial"))
if select==1:
countdown()
elif select==2:
factorial()
Also, to avoid
UnboundLocalError: local variable 'num' referenced before assignment
use global num at the begining of your factorial function. Good luck!
UPDATE: Here is how your entire code should look like
def factorial():
global num
factorial=1
if num<0:
print("Factorial does not defined for negative integer")
elif(num==0):
print("The factorial of 0 is 1")
else:
while(num>0):
factorial=factorial*num
num=num-1
print("factorial of the given number is: ")
print(factorial)
def countdown():
countDown = num
while (countDown >= 0):
print(countDown)
countDown = countDown - 1
if countDown == 0:
print("Done!")
break
num = int(input("Enter a number greater than 1: "))
if num<0:
print("please enter number greater than zero")
elif(num==0):
print("Please enter number greater than 0")
else:
select = int(input("Enter 1 to countdown from or enter 2 to get the factorial"))
if select==1:
countdown()
elif select==2:
factorial()
Figured it out with a lot of help. Thanks!! I appreciate the help.
Here is the final code:
def countdown(num):
countdown_num = num
print (countdown_num)
while (countdown_num >= 0):
print(countdown_num)
countdown_num = countdown_num - 1
if countdown_num == 0:
print("Done!")
break
def factiorial(num):
factorial_num = 1
while num>0:
factorial_num = factorial_num * num
num = num - 1
print(factorial_num)
def main():
num = int(input("Enter a number greater than 1: "))
if num<0:
print("please enter number greater than zero")
elif num==0:
print("Please enter number greater than zero, not zero")
else:
select = int(input("Enter 1 to countdown from or enter 2 to get the factorial"))
if select==1:
countdown(num)
if select==2:
factiorial(num)
main()
Q) Write a function named collatz() that has one parameter named number. If a number is even, then collatz() should print number // 2 and return this value. If a number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling
collatz() on that number until the function returns the value 1.
This is the code I wrote for the above problem but I need a small help on how to use the while loop so when I get a ValueError rather than breaking out of the program I want the program to re-execute the program rather than just displaying the print statement in except.
try:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
x = int(input("Enter a number: "))
while x != 1:
x = collatz(x)
except ValueError:
print("Please enter a numerical value")
You could modify the code from the HandlingExceptions - Python Wiki:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
has_input_int_number = False
while has_input_int_number == False:
try: # try to convert user input into a int number
x = int(input("Enter a number: "))
has_input_int_number = True # will only reach this line if the user inputted a int
while x != 1:
x = collatz(x)
except ValueError: # if it gives a ValueError
print("Error: Please enter a numerical int value.")
Example Usage:
Enter a number: a
Error: Please enter a numerical int value.
Enter a number: 1.5
Error: Please enter a numerical int value.
Enter a number: 5
16
8
4
2
1
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
x = int(input("Enter a number: "))
while x != 1:
try:
x = collatz(x)
except ValueError:
print("Please enter a numerical value")
Use while True and break if not statified.
def collatz(x):
x= x//2 if x%2==0 else x*3+1
print(x)
return x
def func(x):
while True:
x = collatz(x)
if x==1:
break
def run():
while True:
try:
x = int(input("Input a positive number: "))
assert x>0
func(x)
break
except Exception as exc:
#print("Exception: {}".format(exc))
pass
if __name__ == "__main__":
run()
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)
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
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)