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(),""))
Related
I've been working on a small program to learn more about Python, but I'm stuck on something.
Basically, the user has to input a sequence of positive integers. When a negative number is entered, the program stops and tells the user the two largest integers the user previously inputted. Here is my code:
number = 1
print("Please enter your desired integers. Input a negative number to end. ")
numbers = []
while (number > 0):
number = int(input())
if number < 0:
break
largestInteger = max(numbers)
print(largestInteger)
integers.remove(largestInteger)
largestInteger2 = max(numbers)
print(largestInteger2)
There are two issues with your code:
You need to update the list with the user input for every iteration of the while loop using .append().
integers isn't defined, so you can't call .remove() on it. You should refer to numbers instead.
Here is a code snippet that resolves these issues:
number = 1
print("Please enter your desired integers. Input a negative number to end. ")
numbers = []
while number > 0:
number = int(input())
if number > 0:
numbers.append(number)
largestInteger = max(numbers)
print(largestInteger)
numbers.remove(largestInteger)
largestInteger2 = max(numbers)
print(largestInteger2)
I would build a function that would call itself again if the user enters a number larger or equal to 0, but will break itself and return a list once a user inputs a number smaller than 0. Additionally I would then sort in reverse (largest to smallest) and call only the first 2 items in the list
def user_input():
user_int = int(input('Please enter your desired integers'))
if user_int >= 0:
user_lst.append(user_int)
user_input()
else:
return user_lst
#Create an empty list
user_lst = []
user_input()
user_lst.sort(reverse=True)
user_lst[0:2]
You forgot to append the input number to the numbers list
numbers = []
while (True):
number = int(input())
if number < 0:
break
numbers.append(number)
print("First largest integer: ", end="")
largestInteger = max(numbers)
print(largestInteger)
numbers.remove(largestInteger)
print("Second largest integer: ", end="")
largestInteger2 = max(numbers)
print(largestInteger2)```
The above code will work, according to your **desire**
The assignment
So heres the problem, i have a to write a program thats takes input from user until he writes "done".
When that happens, i should take the biggest and smallest value and print them out.
The problem
When i write "done" it tells me that i cant compare an str to a int, and also, it doesnt store every value i wrote in my input() function.
The code
while True:
number = input("Enter number:")
if number == "done":
break
largest = None
for value in number:
if value > largest or largest is None:
largest = value
print("after:", largest)
smallest = None
for value in number:
if value < smallest or smallest is None:
smallest = value
print("after",smallest)
you overwrite number at each loop cycle. Use a container to hold the numbers:
numbers = []
while True:
number = input("Enter number:")
if number == "done":
break
else:
numbers.append(int(number))
print(numbers)
output:
Enter number:1
Enter number:2
Enter number:3
Enter number:done
[1, 2, 3]
NB. I also assume you want to use integers, so I provided the conversion (this will fail if you enter anything else than an integers). Also, as your task is simple (min/max) and doesn't need to know the further numbers in advance, I would recommend to compute those min/max in the while loop. This will be more efficient than reading again 2 times the list (see below).
numbers = [] # not needed if you don't want the list as output
smallest = float('inf')
largest = float('-inf')
while True:
number = input("Enter number:")
if number == "done":
break
else:
number = int(number)
numbers.append(number) # not needed if you don't want the list as output
if number > largest:
largest = number
if number < smallest:
smallest = number
print(numbers, smallest, largest)
output:
Enter number:1
Enter number:3
Enter number:2
Enter number:done
[1, 3, 2] 1 3
I would suggest using min/max, like this:
numbers = []
while True:
ans = input("give me a number: ")
if not ans or ans == "done":
break
try:
ans = int(ans) # we dont want to add this if it's not really a number
numbers.append(ans)
except:
print("please give me an integer!")
print(numbers,min(numbers),max(numbers))
I want to write a program which reads numbers continuously from the user (one at a time), until the user enters "0"
and then the program returns the smallest number in that inputs. I am having trouble sorting out.
This is my code so far:
while True:
number = []
number = input("Please enter a number ")
if number == "0":
break
number.sort()
x = number[0]
return x
You overwrite your number at each step, this cannot work. You should keep track of the min value instead:
min_value = None
while True:
number = int(input("Please enter a number ")) # no type check here
if number == 0:
break
if number is None or number < min_value:
min_value = number
print(min_value)
You can make a list of your entered numbers appending them and then finding the minimum value using the numpy module. For example:
import numpy as np
while True:
number_list = []
number = input("Please enter a number ")
number_list.append(number)
if number == "0":
break
number_array = np.array(number_list)
minval = np.min(number_array[np.nonzero(number_array)])
So that you can find the minimum value of the array, excluding the "0" you entered at the end.
I'm new to python and I'm trying to help out a friend with her code. The code receives input from a user until the input is 0, using a while loop. I'm not used to the python syntax, so I'm a little confused as to how to receive user input. I don't know what I'm doing wrong. Here's my code:
sum = 0
number = input()
while number != 0:
number = input()
sum += number
if number == 0:
break
In your example, both while number != 0: and if number == 0: break are controlling when to exit the loop. To avoid repeating yourself, you can just replace the first condition with while True and only keep the break.
Also, you're adding, so it is a good idea to turn the read input (which is a character string) into a number with something like int(input()).
Finally, using a variable name like sum is a bad idea, since this 'shadows' the built-in name sum.
Taking all that together, here's an alternative:
total = 0
while True:
number = int(input())
total += number
if number == 0:
break
print(total)
No need last if, and also make inputs int typed:
sum = 0
number = int(input())
while number != 0:
number = int(input())
sum += number
You can actually do:
number=1
while number!=0:
number = int(input())
# Declare list for all inputs
input_list = []
# start the loop
while True:
# prompt user input
user_input = int(input("Input an element: "))
# print user input
print("Your current input is: ", user_input)
# if user input not equal to 0
if user_input != 0:
# append user input into the list
input_list.append(user_input)
# else stop the loop
else:
break
# sum up all the inputs in the list and print the result out
input_sum = sum(input_list)
print ("The sum is: ", input_sum)
Or
If you don't want to use list.
input_list = 0
while True:
user_input = int(input("Input an element: "))
print("Your current input is: ", user_input)
if user_input != 0:
input_list += user_input
else:
break
print ("The sum is: ", input_list)
Note:
raw_input('Text here') # Python 2.x
input('Text here') # Python 3.x
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.