How do i order the numbers a user inputs? - python

I am basically wondering how i can store the users inputs and put them in order from least to greatest to help them find median mode or range.
from __future__ import division
amtnum = 0
sumofnums = 0
print "Hello, This program will help find the mean of as many numbers as you want."
useramtnum = input("How many numbers will you need to enter: ")#asks user to say how many numbers there are
while amtnum < useramtnum: #Tells program that while the amount of numbers is less than the users input amt of numbers to run.
amtnum = amtnum + 1 #Tells that each time program asks for number add one to amt of numbers
entnum = (int(raw_input("Enter a number:"))) #Asks user for number
sumofnums = entnum + sumofnums #Adds users number to all values
print "The amount of your numbers added up were:", sumofnums
print "The average/mean of your numbers were:", (sumofnums/useramtnum)

put 'em in a list and sort it
mylist = []
while ...
mylist.append(entnum)
mylist.sort()
print mylist

Utilize the basic data structure called a list!
Before your while loop, create a list (aka array)
user_input_list = []
After you get the individual number from the user in the while loop, add the input to the list (in the while loop)
user_input_list.append(entnum)
After the while loop, sort the list (it will sort in place)
user_input_list.sort()
Then the list has every input from the user in sorted order, least to greatest.
To access the last item in the list, use array accessors.
user_input_list[-1]
To access median, utilize the fact you can use the length of the list. Access the length(list)/2 item
user_input_list[int( len(user_input_list) / 2)] #int cast used to remove decimal points

I am by no means a Python expert (as in, this is like my third python program), but I think it's generally easier to call functions, be it in Python or in any other language. It makes code more readable.
These are all basic math functions, so I don't feel I deprived you of knowledge by just writing them. I did, however, leave the range function for you to write. (Since mylist is sorted, I'm sure you can figure it out.)
This allows the user to continually enter numbers and have the mean, median, and mode spit back at them. It doesn't handle non-integer input.
from collections import Counter
from decimal import *
def getMode(l):
data = Counter(l)
mode = data.most_common(1)
print "mode:", mode
def getMean(l):
length = len(l)
total = 0
for x in l:
total = total + x
mean = Decimal(total) / Decimal(length)
print "mean:", mean
def getMedian(l):
median = 0
length = len(l)
if (length % 2 == 0):
median = (l[length/2] + l[length/2 - 1])/2.0
else:
median = l[length/2]
print "median:", median
mylist = []
print "Enter numbers to continually find the mean, median, and mode"
while True:
number = int(raw_input("Enter a number:"))
mylist.append(number)
mylist.sort()
getMean(mylist)
getMedian(mylist)
getMode(mylist)

Solution to solve your problem :
Use a list : More on Lists
Example :
numbers = []
while amount < counter:
...
numbers.append(num)
print sorted(numbers)
You can take a look at modification of your code below.
numbers = []
print "Hello, This program will help find the \
mean of as many numbers as you want."
while True:
try:
counter = input("How many numbers will you need to enter: ")
except:
print "You haven't entered a number."
else:
break
amount = 0
while amount < counter:
try:
num = input("Enter a number: ")
except:
print "You haven't entered a number."
else:
amount += 1
numbers.append(num)
print "The amount of your numbers added up were:", (sum(numbers))
print "The average/mean of your numbers were:", ( (sum(numbers)) / counter)
print "My list not in order:", numbers
print "My list in order:", sorted(numbers)

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.

Stuck with this

I am trying to write a program that will add together a series of numbers that the user inputs until the user types 0 which will then display the total of all the inputted numbers. this is what i have got and im struggling to fix it
print ("Keep inputting numbers above 0 and each one will be added together consecutively. enter a and the total will be displayed on the screen. have fun")
number = input("Input a number")
sum1 = 0
while number >= 1:
sum1 = sum1 + number
if number <= 0:
print (sum1)
Here is a more robust way to input the number. It check if it can be added. Moreover I added the positive and negative number.
# -*-coding:Utf-8 -*
print ("Keep inputting numbers different than 0 and each one will be added together consecutively.")
print ("Enter a and the total will be displayed on the screen. Have fun.")
sum = 0
x = ""
while type(x) == str:
try:
x = int(input("Value : "))
if x == 0:
break
sum += x
x = ""
except:
x = ""
print ("Please enter a number !")
print ("Result : ", sum)
If you're using Python 3, you will need to say number = int(input("Input a number")) since input returns a string. If you're using Python 2, input will work for numbers but has other problems, and the best practice is to say int(raw_input(...)). See How can I read inputs as integers? for details.
Since you want the user to repeatedly enter a number, you also need an input inside the while loop. Right now it only runs once.

Simple python code error

error: Can't convert int to str implicitely
Code:
user_name = input("What is your name? ")
print("Hello {}!, this program is going to ask you to type in a series of numbers (all positive integers)" .format(user_name))
total_numbers = input("How many numbers would you like to add")
for i in range(1, total_numbers):
number = float(input("State a numbers {}: " .format(i)))
total_numbers += number
print("Total number: {}" .format(total_numbers))
MY TASK IS TO: Ask for the user’s name to be entered. It should be stored in a suitable variable (like user_name)
Ask for how many numbers are going to be entered. Store this in a suitable variable too. (like “num_values”)
Then get each of the numbers entered.
You will need to have some way of keeping a total of all of the numbers and at the end, once all numbers have been entered, you need to print out something like..
The issue is in lines -
total_numbers = input("How many numbers would you like to add")
for i in range(1, total_numbers):
number = float(input("State a numbers {}: " .format(i)))
total_numbers += number
You have to convert total_numbers to int to use in range function. Like -
total_numbers = int(input("How many numbers would you like to add"))
for i in range(1, total_numbers):
number = float(input("State a numbers {}: " .format(i)))
total_numbers += number
Also, I see that you are adding numbers to total_numbers inside the loop itself, maybe you instead want to create a new variable , initilize with 0 and add to it instead, Increasing total_numbers itself would give you unexpected results.
Code would be -
total_numbers = int(input("How many numbers would you like to add"))
total = 0.0
for i in range(1, total_numbers):
number = float(input("State a numbers {}: " .format(i)))
total += number
print("Total number: {}" .format(total))

How to compare inputted numbers without storing them in list

Note: This is not my homework. Python is not taught in my college so i am doing it my myself from MITOCW.
So far i have covered while loop, input & print
Q) Write a program that asks the to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered it should print a message to the effect
How can i compare those 10 number without storing them in some list or something else? Coz i haven't covered that as if yet.
print "Enter 10 numbers: "
countingnumber=10
while countingnumber<=10:
number=raw_input():
if number % 2 == 0:
print "This is odd"
countingnumber=countingnumber+1
else:
print "This is even. Enter the odd number again"
i think the program will look something like this. But this has some unknown error & How can i compare all the numbers to get the largest odd number without storing those 10 numbers in the list.
print "Enter 10 numbers: "
countingNumber = 1
maxNumber = 0
while countingNumber<=10:
number=int(raw_input())
if (number % 2 == 0):
countingNumber = countingNumber+1
if (maxNumber < number):
maxNumber = number
else:
print "This is even. Enter the odd number again"
print "The max odd number is:", maxNumber
you can just define a maxnum variable and save the max in it! also you must use int(raw_input()) instead raw_input()
print "Enter 10 numbers: "
maxnum=0
for i in range(10):
number=int(raw_input())
if number%2 == 0:
print "This is odd"
if number>maxnum:
maxnum=number
else:
print "This is even. Enter the odd number again"
print "max odd is :{0}".format(maxnum)
DEMO:
Enter 10 numbers:
2
This is odd
4
This is odd
6
This is odd
8
This is odd
12
This is odd
14
This is odd
16
This is odd
100
This is odd
2
This is odd
4
This is odd
max odd is :100
Whenever I do input, I like to make sure I don't leave room for human error giving me bugs.
Because I put in extra checks I break code into a lot of separate function. This also gives code the quality of being non-coupled. ie) You can reuse it in other programs!!
def input_number():
while true:
input = raw_input("Enter Value: ")
if not input.isdigit():
print("Please enter numbers only!")
else:
return int(input)
Designing the input function in this fashion gives the code no opportunity to crash. We can now use it in a function to get odd numbers!
def input_odd_number():
while true:
input = input_number()
if input % 2 == 0:
print("Please enter odd numbers only!")
else:
return input
Now we can finally move onto the main code. We know we need ten numbers so lets make a for loop. We also now we need to hold onto the largest odd number, so lets make a variable to hold that value
def largest_odd(count = 10): // its always nice to make variables dynamic. The default is 10, but you can change it when calling!
max_odd = input_odd_number() // get the first odd number
for i in range(count - 1): // we already found the first one, so we need 1 less
new_odd = input_odd_number()
if new_odd > max_odd:
max_odd = new_odd
print("The largest odd value in '{}' inputs was: {}".format(count, max_odd)
In your solution are multiple flaws.
A syntax error: The colon in number=raw_input():.
raw_input returns a string and you have to cast it to an int.
Your while loop just runs one time, because you start with 10 and compare 10 <= 10. On the next iteration it will be 11 <= 10 and finishes.
Also you have mixed odd an even. even_number % 2 gives 0 and odd_number % 2 gives 1.
To get the biggest value you only need a additional variable to store it (See biggest_number in my solution). Just test if this variable is smaller then the entered.
You ask again if the number is odd, but you should take every number and test only against odd numbers.
A working solution is:
print "Enter 10 numbers"
count = 0
max_numbers = 10
biggest_number = None
while count < max_numbers:
number=int(raw_input("Enter number {0}/{1}: ".format(count + 1, max_numbers)))
if number % 2 == 1:
if biggest_number is None or number > biggest_number:
biggest_number = number
count += 1
if biggest_number is None:
print "You don't entered a odd number"
else:
print "The biggest odd number is {0}".format(biggest_number)
If you wonder what the format is doing after the string take a look in the docs. In short: It replaces {0} with the first statement in format, {1} with the second and so on.
here is the correct code for that:
print "Enter 10 numbers: "
countingnumber=1
MAX=-1
while countingnumber<=10:
number=int(raw_input())
if number%2==1:
if number>MAX:
MAX=number
if MAX==-1:
print "There Weren't Any Odd Numbers"
else:
print MAX
here are some notes about your errors:
1- you should cast the raw input into integer using int() function and the column after calling a function is not needed and therefor a syntax error
2- your while loop only iterates once because you initial counting number is 10 and after one iteration it would be bigger than 10 and the while body will be skipped.
3-an even number is a number that has no reminder when divided by 2 but you wrote it exactly opposite.
4- you don't need to print anything in the while loop, you should either print the biggest odd number or print "There Weren't Any Odd Numbers".
5- an additional variable is needed for saving the maximum odd number which is MAX.
Last note: in the code provided above you can combine the two ifs in the while loop in to one loop using 'and' but since you said you are a beginner I wrote it that way.

Finding largest and smallest number where user inputs numbers using a loop

I am creating a program where I am asking the user to input numbers using a loop (not function).
I need to assume the numbers are floating.
User will continue to input numbers until they hit the enter key a second time.
Then the program will generate the largest number, smallest number, sum of the list and average number.
I've figured everything out but when I type in a number 10 or larger, the program doesn't identity it as the largest. In fact, I noticed that 10 is considered the smallest number.
Also I'm not able to convert the numbers in floating numbers.
myList = []
done = False
while not done:
enterNumber = raw_input("Enter a number (press Enter key a second time to stop): ")
nNumbers = len(myList)
if enterNumber == "":
done = True
break
else:
myList.append(enterNumber)
print "You've typed in the following numbers: " + str(myList)
smallest = 0
largest = 0
for nextNumber in myList:
if smallest == 0 or nextNumber < smallest:
smallest = nextNumber
for nextNumber in myList:
if largest == 0 or largest < nextNumber:
largest = nextNumber
print "Largest number from this list is: " + largest
print "Smallest number from this list is: " + smallest
sum = 0
for nextValue in myList:
sum = sum + float(nextValue)
print "The sum of all the numbers from this list is: " + str(sum)
average = float(sum/nNumbers)
print "The average of all the numbers from this list is: " + str(average)
This tells me that you are probably not comparing what you think :)
Your code is mostly correct, except for the fact that you never told python what the "type" of the user input was. I am guessing python assumed the user entered a bunch of strings, and in the string world - "10" < "9"
So in your code, force the type of "enterNumber" to be a float before adding it to your list of floats like so:
while not done:
enterNumber = raw_input("Enter a number (press Enter key a second time to stop): ")
nNumbers = len(myList)
if enterNumber == "":
done = True
break
else:
myList.append(float(enterNumber))
you need to convert it before you add it to your list
enterNumber = raw_input("Enter a number (press Enter key a second time to stop): ")
nNumbers = len(myList)
if enterNumber == "":
done = True
break
else:
myList.append(float(enterNumber)) # convert it here...
#you may want to check for valid input before calling float on it ...
but my favorite way to get a list of numbers is
my_numbers = map(float,
iter(lambda:raw_input("Enter a number or leave blank to quit").strip(),""))

Categories