Get the Biggest (int) Input From a Loop and Print it - python

I want to know how to get the biggest 'int(input) from the user in a loop. For example:
def main():
times = int(input('How many times will you do this: ')
for i in range(times):
num = int(input('Enter a number: ')
main()
I want to know how I could get the biggest number from the user's input from something like this and print it.
If I said I wanted to enter a number 5 times and entered 6, 1, 21, 34, 3. I would want it to print 34 because that is the biggest value entered by the user.
This is just an example!

Keep track of the numbers the users enters, after the loop, pick the highest one using the max function.
def main():
numbers = []
times = int(input('How many times will you do this: '))
for i in range(times):
num = int(input('Enter a number: '))
numbers.append(num)
print(str(max(numbers)) + ' is the biggest number.')
main()

Related

How to add X amount number from user input then add all of number in python?

how_many_number = int(input("How many number do you want to print? "))
for take_number in how_many_number:
take_number = int(input("Enter number: "))
sum = 0
sum = sum + take_number
print(sum)
Here you go. To take user input we can use a for loop and for each iteration we can add it to our sum using += operator. You can read through the following code to understand it well enough.
number_of_inputs = int(input("How many number to sum: ")
sum = 0 # Initialize the sum variable
for x in range(number_of_inputs): # Repeat the number of inputs times
sum += int(input("Enter Value: ")) # Take a input and add it to the sum
print("Sum is", sum) # print out the sum after completing
You can also compress it into a List Comprehension, like this...
how_many_number = int(input("How many number do you want to print? "))
print(sum([int(input("Enter number: ")) for i in range(how_many_number)]))
i would use the following, note: error handle is not yet incorporated.
num_list = []
### create a function that adds all the numbers entered by a user
### and returns the total sum, max 3 numbers
### return functions returns the entered variables
def add_nums():
while len(num_list) < 3:
user_num = int(input('please enter a number to add:'))
num_list.append(user_num)
print('You have entered the following numbers: ',num_list)
total_num_sum = 0
for x in num_list:
total_num_sum += x
print('total sum of numbers = ',total_num_sum)
add_nums()
Also, please follow the StackOverFlow post guidelines; have your post title as a problem question, it has to be interesting for other devs, and add more emphasis on why you want to add numbers entered by user vs running calc on a existing or new data-frame, need more meat.

Mathmatical Average Calculation

Edit the program provided so that it receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing inputs. After the user presses the enter key, the program should print:
The Average and The Sum
I've been able to get it to print the sum of the numbers put in but I think it is messing up when trying to calculate the average. I really need some help with this. try inputting 100 59 37 21 and you will see what I mean
data = input("Enter a number: ")
number = float(data)
while data != "":
number = float(data)
theSum += number
data = input("Enter the next number: ")
print("The sum is", theSum)
average = theSum // number
print("The average is", average)```
As Mat and Nagyl have pointed out in the comments you need to keep track of how many numbers were given and divide the sum by that to get the average
data = input("Enter a number: ")
number = float(data)
numbersGiven = 0
theSum = 0
while data != "":
number = float(data)
theSum += number
numbersGiven += 1
data = input("Enter the next number: ")
print("The sum is", theSum)
average = theSum / numbersGiven
print("The average is", average)
Notice that the first input isn't counted (I start with numbersGiven = 0) but the empty input at the end is counted so it gives the correct count.
you can use these code too!
instead of writing the formula for average you can use statistics module
import statistics
the code below asks you the numbers how many times you wrote in the number of datas
number_of_datas=int(input("number of inputs asking: "))
datas=[]
The following code takes the number from the number of times you wrote in the number of inputs
also you can write a Specified number instead of getting an input
for i in range(number_of_datas):
data = float(input("Enter a number: "))
datas.append(data)
fmean is float average
average=statistics.fmean(datas)
print(average)

How to Separate a Range of Odd and Even Numbers Through Searching the Array While Skipping Numbers

I'd like to challenge myself and develop my programming skills. I would like to create a program that asks for the user to enter a range of numbers where odd and even numbers should be separated (preferably through search) and also separated by a specified jump factor.
Also the user should be allowed to choose whether or not they would like to continue. And if so they can repeat the process of entering a new range.
for example when the program is run a sample input would be:
"Please enter the first number in the range": 11
"Please enter the last number in the range": 20
"Please enter the amount you want to jump by": 3
and the program would output:
"Your odd Numbers are": 11,17
"Your even Numbers are": 14,20
"Would you like to enter more numbers(Y/N)":
So far what I have for code is this but am having trouble putting it together and would appreciate some help.
import sys
print("Hello. Please Proceed to Enter a Range of Numbers")
first = int(input("please enter the first number in the range: "))
last = int(input("please enter the last number in the range: "))
jump = int(input("please enter the amount you want to jump by: "))
def mylist(first,last):
print("your first number is: ",first,"your last number is: ",last,"your jump factor is: ",jump)
def binarySearch (target, mylist):
startIndex = 0
endIndex = len(mylist) – 1
found = False
targetIndex = -1
while (not found and startIndex <= endIndex):
midpoint = (startIndex + endIndex) // 2
if (mylist[midpoint] == target):
found = True
targetIndex = midpoint
else:
if(target<mylist[midpoint]):
endIndex=midpoint-1
else:
startIndex=midpoint+1
return targetIndex
print("your odd Numbers are: ")
print("your even Numbers are: ")
input("Would you like to enter more numbers (Y/N)?")
N = sys.exit()
Y = first = int(input("please enter the first number in the range"))
last = int(input("please enter the last number in the range"))
jump = int(input("please enter the amount you want to jump by: "))
question - "So far what I have for code is this but am having trouble putting it together and would appreciate some help."
answer -
As a start, it seems like a good idea to group your inputs and outputs into functions! Then putting it together is a snap!
def get_inputs():
bar = input('foo')
def process_inputs():
bar = bar + 1
def print_outputs():
print(bar)
if '__name__' == '__main__':
get_inputs()
process_inputs()
print_outputs()
You could even toss in something like if input('more? (Y/N):') == 'Y': in a while loop.
Maybe I'm missing something but couldn't you replace your binary search with the following?
>>> list(filter(lambda x: x%2 == 1, range(11, 20 + 1, 3)))
[11, 17]
>>> list(filter(lambda x: x%2 == 0, range(11, 20 + 1, 3)))
[14, 20]

Python Help, Max Number of Entries

Created a program for an assignment that requests we make a program that has the user input 20 numbers, and gives the highest, lowest etc. I have the main portion of the program working. I feel like an idiot asking this but I've tried everything setting the max number of entries and everything I've tried still lets the user submit more than 20. any help would be great! I tried max_numbers = 20 and then doing for _ in range(max_numbers) etc, but still no dice.
Code:
numbers = []
while True:
user_input = input("Enter a number: ")
if user_input == "":
break
try:
number = float(user_input)
except:
print('You have inputted a bad number')
else:
numbers.append(number)
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
Your question could be presented better, but from what you've said it looks like you need to modify the while condition.
while len(numbers) < 20:
user_input = input("Enter a number:" )
....
Now once you've appending 20 items to the numbers list, the script will break out of the while loop and you can print the max, min, mean etc.
Each time the user enters input, add 1 to a variable, as such:
numbers = []
entered = 0
while entered < 20:
user_input = input("Enter a number: ")
if user_input == "":
break
else:
numbers.append(number)
try:
number = float(user_input)
except:
print('You have inputted a bad number')
continue
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
entered+=1
Every time the while loop completes, 1 is added to the variable entered. Once entered = 20, the while loop breaks, and you can carry on with your program. Another way to do this is to check the length of the list numbers, since each time the loop completes you add a value to the list. You can call the length with the built-in function len(), which returns the length of a list or string:
>>> numbers = [1, 3, 5, 1, 23, 1, 532, 64, 84, 8]
>>> len(numbers)
10
NOTE: My observations were conducted from what I ascertained of your indenting, so there might be some misunderstandings. Next time, please try to indent appropriately.

Python 2.7.5, making loop with unlimited user input, accumulate totals, applying sentinel?

Just started working with an older python book, learning about loops and trying to make a loop that accumulates the user input and then displays the total. The problem is the book only shows how to do this with a range, I want to have the user input as many numbers as they want and then display the total, so for example if the user entered 1,2,3,4 I would need python to output 10, but I don't want to have python tied down to a range of numbers.
here is the code I have WITH a range, as I stated above, I need to do this user input without being tied down to a range. Also do I need to apply a sentinel for the kind of program I want to make?
def main():
total = 0.0
print ' this is the accumulator test run '
for counter in range(5): #I want the user to be able to enter as many numbers
number = input('enter a number: ') #as they want.
total = total + number
print ' the total is', total
main()
You'll want a while-loop here:
def main():
total = 0.0
print ' this is the accumulator test run '
# Loop continuously.
while True:
# Get the input using raw_input because you are on Python 2.7.
number = raw_input('enter a number: ')
# If the user typed in "done"...
if number == 'done':
# ...break the loop.
break
# Else, try to add the number to the total.
try:
# This is the same as total = total + float(number)
total += float(number)
# But if it can't (meaning input was not valid)...
except ValueError:
# ...continue the loop.
# You can actually do anything in here. I just chose to continue.
continue
print ' the total is', total
main()
Using your same logic, only replace it with a while loop. The loop exits when the user types 0
def main():
total = 0
print 'this is the accumulator test run '
while True:
number = input('enter a number: ')
if number == 0:
break
total += number
print 'the total is', total
main()
Just for fun, here is a one line solution:
total = sum(iter(lambda: input('Enter number (or 0 to finish): '), 0))
If you want it to display right away:
print sum(iter(lambda: input('Enter number (or 0 to finish): '), 0))
Use a while-loop to loop an indeterminate number of times:
total = 0.0
print 'this is the accumulator test run '
while True:
try:
# get a string, attempt to cast to float, and add to total
total += float(raw_input('enter a number: '))
except ValueError:
# raw_input() could not be converted to float, so break out of loop
break
print 'the total is', total
A test run:
this is the accumulator test run
enter a number: 12
enter a number: 18.5
enter a number: 3.3333333333333
enter a number:
the total is 33.8333333333

Categories