I need to write a program that prompts the user to enter numbers, and stores/displays the largest & smallest integer entered.
However, I can only do this with simple data types (no arrays.)
This is what I have so far.
def main()
while number != -99:
number = input('Enter a number: ')
compare = input('Please enter another number: ')
if compare < number then
compare = smallest
I'm sorry it's just a mess. We're not actually taught python in this class, only psuedo-code then just kind of sent on our own to figure it out.
If you don't need to keep all the numbers, then simply keep two variables maximum and minimum in two variables and only assign the latest user data entry to one or the other depending on whether it is lesser / greater or not - plus a special case to get the first number started in both variables. Here is a little pseudo-code example...
Maximum = NULL
Minimum = NULL
Do
Get User Input string
If Input is Blank Then Exit Loop
Input = Convert Input to Number
If Maximum=NULL
Then Maximum=Input
Else If Input > Maximum Then Input = Maximum
If Minimum=NULL
Then Minimum=Input
Else If Input < Minimum Then Input = Minimum
Loop
Print "Min = " + Minimum
Print "Max = " + Maximum
Related
The purpose of this program is to find the smallest and largest values in a list. The moment the user inputs a negative number, the program should stop. Here is the code I have written so far:
user_inputs = []
number = int(input())
for i in range(number):
value = int(input())
if i >= 0:
user_inputs.append(value)
else:
break
print(min(user_inputs))
print(max(user_inputs))
As you can see, I am new to programming and still struggling to find the logic behind loops. Surely, this code is ridden with mistakes and any helpful improvements is much appreciated. Thanks in advance.
Brother one mistake that you have done is that you are using
for i in range(number):
basically by doing this you are telling compiler that repeat the code in for loop for "number" of times and obviously number would change every time user inputs a new number resulting in error
The right way to make the code do what you want is :
user_inputs = []
while True:
number = int(input('Enter a positive number : '))
if number >= 0 :
user_inputs.append(number)
else:
print(user_inputs)
print('Smallest number in list is : ',min(user_inputs))
print('Largest number in list is : ',max(user_inputs))
break
Here while loop will run continuously until a negative number has been input, so when a negative number is input the while loop woulb break .
You are checking
i
when you should be checking
value
you have to compare value
i.e. if value >= 0
you are using i which is the number of iteration
I am very, very, VERY new to programming. So far I am really enjoying this class. However lately the programming challenges have been a bit confusing and daunting. The most current challenge I'm on has me scratching my head as I can find no help in my book nor online. In a nutshell I need to create a program that takes the score of five judges in a range of 0-10, exclude the highest and lowest scores given and then calculate the average of the remaining three scores. While I understand how to validate user input for a single value and compute the average, I have no idea how to validate user input for all 5 inputs without doing anything too tedious, and exclude the highest score and lowest score that the user inputs. I have some idea of what I need to do. Take the user input as a float, then transfer it to a function that takes the highest and lowest scores then send it to another function that will compute the average. If anyone could help me with this I'll be really grateful. Below is what I've worked out so far. Thank you in advance.
def getJudgeData():
badEntry = True
while (badEntry) :
judge1 = float (input("Please enter the first judge's score : "))
if (judge1 < 0 or judge1 > 10) :
print ("The score must be greater than 0 and less than or equal to 10!")
else:
badEntry = False
while (badEntry) :
judge2 = float (input("Please enter the second judge's score : "))
if (judge2 < 0 or judge2 > 10) :
print ("The score must be greater than 0 and less than or equal to 10!")
else:
badEntry = False
Below code will ask to input a score 5 times, that is why the loop in a range of 5. It will throw a value error if the user's input is not an integer. If you want float, you can change that to a float. If the user input is more than 10, it will prompt the user to inout numbers in the correct range. Then the calculate_average function returns the average rounded to two decimal places, you can change that if needed more or less decimal places.
I was not sure what you meant by subtracting max and min values, so I removed then from the scores. But if I misunderstood, just leave them in there, and then calculate average as normal.
scores = []
def getJudgeData():
for i in range(5):
try:
judge_score = int(input("Please enter the first judge's score : "))
if (judge_score in range(11)):
scores.append(judge_score)
else:
print('Enter a score from 1 to 10')
except ValueError:
print("Enter a valid number")
def calculate_average():
max_value = max(scores)
min_value = min(scores)
scores.remove(max_value)
scores.remove(min_value)
average = sum(scores)/len(scores)
return round(average, 2)
getJudgeData()
print(calculate_average())
I am trying to get into coding and this is kinda part of the assignments that i need to do to get into the classes.
"Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1."
The while loop i can do... The calculation is what im stuck on.
negative = "-1"
passable = "0"
while not passable <= negative:
passable = input("Write a number: ")
I just want to get this to work and a explanation if possible
As pointed out by some of the other answers here, you have to sum up all your answers and divide it by how many numbers you have entered.
However, remember that an input() will be a string. Meaning that our while loop has to break when it finds the string '-1' , and you have to add the float() of the number to be able to add the numbers together.
numbers=[]
while True:
ans=input("Number: ")
if ans=="-1":
break
else:
numbers.append(float(ans))
print(sum(numbers)/len(numbers))
I would initialize a list before asking the user for a number, using a do-while. Then, you add every number to that list unless the number == -1. If it does, then you sum every element in the list and output the average.
Here's pseudocode to help:
my_list = []
do
input_nb = input("Please enter a number: ")
if(input_nb != -1)
my_list.add(input_nb)
while (input_nb != -1)
average = sum(my_list) / len(my_list)
print('My average is ' + average)
You are assigning strings to your variables, which I don't think is your intention.
This will work:
next_input = 0
inputs = []
while True:
next_input = int(input('Please enter a number:'))
if next_input == -1:
break
else:
inputs.append(next_input)
return sum(inputs) / len(inputs)
First, you need to create a container to store all the entered values in. That's inputs, a list.
Next, you do need a while loop. This is another way of structuring it: a loop that will run indefinitely and a check within it that compares the current input to -1, and terminates the loop with break if it does. Otherwise, it appends that input to the list of already entered inputs.
After exiting the loop, the average is calculated by taking the sum of all the values in the entered inputs divided by the length of the list containing them (i.e. the number of elements in it).
This question already has answers here:
Storing multiple inputs in one variable
(5 answers)
Closed 2 months ago.
hi i am very new to programming and was doing my 6th assignment when i started to draw a blank i feel as thou its really simple but i cant figure out how to continue and would appreciate some advice
showing the correct code would be cool and all but i would really appreciate feed back along with it more so then what to do and if so where i went wrong
down below is what im supposed to do.
Write a program that keeps reading positive numbers from the user.
The program should only quit when the user enters a negative value. Once the
user enters a negative value the program should print the average of all the
numbers entered.
what im having trouble with is getting the number to remember okay user entered 55 (store 55) user entered 10 (store 10) user enter 5 (store 5) okay user put -2 end program and calculate. problem is its not remembering all previous entry's its only remembering the last input (which i guess is what my codes telling it to do) so how do i code it so that it remembers all previous entry's
and here is the code i have so far
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
print (number)
else:
print (number) # these are just place holders
If you really want to remember all previous entries, you can add them to a list, like so:
# before the loop
myList = []
# in the loop
myList = int(input("enter a number. put in a negative number to end"))
Then you can easily compute the mean of the numbers by iterating over the list and dividing by the length of the list (I'll let you try it yourself since its an assignment).
Or, if you want to save (a little) memory, you can add them each time to a variable and keep another variable for the count.
You can use a simple list in order to keep track of the numbers that have been inserted by the user. This list may then get processed in order to calculate the average when every number got read in ...
# This is a simple list. In this list we store every entry that
# was inserted by the user.
numbers = []
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end "))
if number > 0 :
print (number)
# save the number for later usage.
numbers.append(number)
# calculate average
if len(numbers) == 0:
print("You have not inputted anything. I need at least one value in order to calculate the average!")
else:
print("The average of your numbers is: %s" % (sum(numbers) / len(numbers)))
What you need is an list which can store multiple values. It is often use with loops to insert/get value from it.
For instance,
number = 1
numbers = []
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
numbers.append(number)
print (numbers)
What you get is a list of numbers like [4, 10, 17] in ascending order as append() will add number to the back of the list. To get individual numbers out of the list:
numbers[0]
Note that the index inside the bracket starts from 0, so for instance you have a list with [4, 10, 17]. You should use the below 3 to get each of them:
numbers[0]
numbers[1]
numbers[2]
Or even better, with a loop.
for x in numbers:
print (x)
I have a homework problem that I cant figure out, can someone help
--Create a function called sums that will prompt the user to enter integer values (either positive or negative). The function should keep separate running totals of the positive values and the negative values. The user should be allowed to continue entering values until he/she enters a zero to stop.
Here's what I got and it doesn't work
number = int(raw_input("Enter and a positive or negative integer: "))
def sums(number):
while (number > 0):
posnumber = int(raw_input("Enter another number or 0 to quit: " ))
number = number + posnumber
print "The positive total is", number
while (number < 0):
negnumber = int(raw_input("Enter another number or 0 to quit: " ))
number = number + negnumber
print "The negative total is", number
it just runs the loop under the first iteration, I'm confused as to what to do to correct it
Because they're separate while loops - the first one is executed, then the second one is executed. You don't want that at all. Here's a layout of what you should do:
take a number from input, store it as inputnum
while inputnum isn't 0
determine whether inputnum is positive or negative
add inputnum to the either posnumber or negnumber
print the total
get a new inputnum
That is, you should have an if inside a while, not two whiles.