Python: Loop Sentinel Value [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm supposed to write a program with a loop that lets the user enter a series of integers, followed by -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.
This is what I have so far:
def main():
user_input = 1
while user_input != -99:
user_input = int(input("Enter your number or -99 to end."))
bigger = largest(user_input)
tinier = smallest(user_input)
print('The largest number is ', bigger, "and the smallest is ", tinier, ".")
def largest(number):
largest = 0
if number > largest:
largest = number
return largest
def smallest(number):
smallest = 10000
if number < smallest:
smallest = number
return smallest
main()
For some reason the sentinel value (-99) is entering the loop, I have no clue how, and becoming the smallest value. On top of that, the biggest value isn't ever the right one. Help much appreciated!

The quickest change to make to your code to fix this would be
def main():
user_input = 1
while user_input != -99:
user_input = int(input("Enter your number or -99 to end."))
if use_input == -99:
break
bigger = largest(user_input)
tinier = smallest(user_input)
print('The largest number is ', bigger, "and the smallest is ", tinier, ".")
The problem is, if the user enters -99, you complete the rest of the lines for that iteration of the loop. It will not terminate the while loop until the next time around, but it has already performed largest and smallest at that point so it is already overwritten.

Your Indentation is important in python so your smallest value and largest value functions return statement is improperly indent
def largest(number):
largest = 0
if number > largest:
largest = number
return largest
def smallest(number):
smallest = 10000
if number < smallest:
smallest = number
return smallest

Pretty simple if you use a list to store the numbers and rely on max/min functions from the standard library:
def main():
numbers = []
while True:
user_input = int(raw_input("Enter a number"))
if user_input == -99:
break
else:
numbers.append(user_input)
print('Largest is {}, smallest is {}'.format(max(numbers), min(numbers)))

You have two problems as far as I can see: your input is being processed before being checked, and there are issues in your largest() and smallest() functions. When you scan for user input, you immediately go into your functions before verifying. Restructure your loop like this:
input()
while(){
...
...
input()
}
For the second part, your functions aren't working because you initialize the values every time they run. Initialize your functions in the header at the top of your file, then just compare them. So for example, move the line largest=0 to the top of your file right below your import statements. Other than that, I think it should work.

Related

Why the While loop continues and how to calculate the average based on numbers input? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
Hi I'm trying to solve this coding homework:
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.
I define the while loop to make sure it keeps asking, as:
while n != -1
str(input("enter your number:"))
But whenever I try to input -1, it just keeps on asking to enter the number regardless.
Also, I'm not sure what is the best way to define the average excluding -1, none of the lessons prior to this assignment talked about this. I have Googled about it but none of the examples match this particular assignment, even fumbling around did not help.
Thank you for your help :)
Presumably n is meant to be the user input, but you're never assigning a value to n. Did you mean to do this?
n = str(input("enter your number:"))
Also, you're comparing n to -1, but your input isn't a number; it's a string. You can either convert the input to a number via n = int(input(...)), or compare the input to a string: while n != '-1'.
You could ask for a number the if it is not equal to -1 enter the while loop. So the code would be:
n = float(input("What number?"))
if n != -1:
sum += n
nums_len = 1
while n != -1:
sum += 1
nums_len += 1
n = float(input("What number?"))
print("The average is", str(sum/nums_len))
Thanks everyone, this is the final code with the correct values that gives the average of user inputs
n = float(input("What number?"))
if n != -1:
sum = 0
nums_len = 0
while n != -1:
sum += n
nums_len += 1
n = float(input("What number?"))
print("The average is", float(sum/nums_len))

the correct use of max(), min() function in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
im strugguling to get a solution for my problem. I keep getting errors with my max(), and min() function.
Im trying to write a code that takes user inputs until a negative value is inputted.Then i need to take the sum, highest, lowest and avarges of the numbers.
the code:
print("Please enter values(negative value to stop)")
g=1
flag=0
list = []
while not flag:
val=float(input("Enter value number "+str(g)+ ": "))
g+=1
if val<0:
flag=1
else:
sum+=val
print("Sum of "+str(g-2)+ " values: "+str(sum))
print("The highest number is: ",min(low_number))
print("The lowest number is: ",min(low_number))
print("The average number is: ",sum/(g-1))
I am no expert but I think it is because you are not entering any of the values inputted into the lists. There is no where that you are appending the given values so there are no numbers in the lists to be checked.
I have not tested this but perhaps try
print("Please enter values(negative value to stop)")
flag=0
number = []
while not flag:
val=float(input("Enter value number :"))
if val<0:
flag=1
else:
number.append(val)
print("Sum of "+str(len(number))+ " values: "sum(number))
print("The highest number is: ",max(number))
print("The lowest number is: ",min(number))
print("The average number is: ",sum(number)/len(number))
EDIT: I made some changes to ensure it all works :)
EDIT 2: I have tested this and this code works entirely
low_number is empty, so min() on an empty list will fail.
Maybe you want to do something like this:
print("Please enter values(negative value to stop)")
flag=0
values=[]
while not flag:
val=float(input("Enter value number : "))
if val < 0:
break
values.append(val)
print("Sum of values: ",sum(values))
print("The highest number is: ",max(values))
print("The lowest number is: ",min(values))
print("The average number is: ",sum(values)/len(values))

Bisection search code doesnt work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Could you explain where i'm going wrong with this code? I want to do a bisection search which takes input number and repeats bisection search until it finds the same number as input and prints out various statements.
num =int( input("Please think of a number between 0 and 100!"))
maximum = num
minimum = 0
average = (minimum+maximum)/2.0
while(average<num):
print ("Is your secret number ", +average, "?")
cond = input("Enter 'h' to indicate the guess is too high.Enter 'l' to indicate the guess is too low.Enter 'c' to indicate I guessed correctly.")
if( cond == "h"):
maximum = minimum
minimum = 0
elif(cond == "l"):
minimum = maximum
maximum = 100
elif(cond == "c"):
print("Game over. Your secret number was: ", +average)
break
Firstly, you don't need to input a guess. You are always going to start at the mid-point of your range.
So, instead, wait for the user to think of a number, then guess.
import time
minimum = 0
maximum = 100
print("Please think of a number between {} and {}!".format(minimum, maximum))
time.sleep(3)
average = (minimum + maximum)/2.0
while(True):
print ("Is your secret number ", +average, "?")
cond = input("Enter 'h' to indicate the guess is too high.Enter 'l' to indicate the guess is too low.Enter 'c' to indicate I guessed correctly.")
Second problem, you need to "divide" your search space. If the guess is too high, set that guess as the maximum, if too low, set that as the minimum. No need to set the other value in either case; it stays the same.
if( cond == "h"):
maximum = average
elif(cond == "l"):
minimum = average
elif(cond == "c"):
print("Game over. Your secret number was: ", +average)
break
And lastly, you need to update average each time through the loop to generate a new guess.
average = (minimum + maximum) / 2.0

How do I write a function that repeatedly prompts the user for a number and then average the numbers? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm pretty new to programming, and I have no idea how to go about this.
Basically I need a function that repeatedly prompts a user to input an integer until they enter a non-numerical characters, then it takes the numbers and averages them.
This what I have so far, the ave function is to average the numbers, that's not the problem
def ioAve():
L = input("Enter your number: ")
if L == int:
print(L)
if L != int:
ave(L)
The program doesn't return anything at all.
This is probably the most pythonic way I can think of to solve this. Your approach of checking if an entered number is of a certain type is less desirable than catching the exceptions that might be raised when trying to convert (e.g. in this case a ValueError is raised when an invalid value is passed to int() ). You can learn more about exceptions in Python at the Python wiki.
The solution below also uses a list, which is an object that can contain multiple values. You can learn more about lists at effbot.org.
numbers = list()
while True:
try:
number = int(input("Enter a number: "))
numbers.append(number)
except ValueError:
break
print ("The average is", sum(numbers) / len(numbers))
cont = True
nums = []
while cont:
entered = input("Enter a number: ")
cont = all(char.isdigit() for char in entered)
if cont:
nums.append(int(entered))
print("The average is:", sum(nums)/len(nums))
Something like this:
print('Average: ',(lambda x:sum(x)/len(x))
([x for x in iter(lambda:(lambda x:int(x)
if x and all(x.isdigit() for x in x)else
...)(input('Enter a number: ')),...)]))
Sorry, I couldn't resist.
Something like this maybe. I'm sure there is a more pythonic way thou.
#import sys instead of using sys for program termination
def main():
sum = 0
iterations = 0
while True:
try:
num = int(raw_input("Input an integer: "))
iterations += 1
sum += num
except:
print "Average: "+str(sum//iterations)
#sys.exit() use break to "jump" out of an infinite loop
break
if __name__ == "__main__":
main()

Python while loop/range

I need to ask a number from the user and have then if it is in the range of the low/high number then it returns the number and if it isnt in the range, it loops until the number entered is in the range. I don't really know how exactly to do this but I think I have part of it right. My main concern is the line "while question != low <= question <= high:" I feel as if there is a problem with that line.
def ask_number(question, low, high):
question = int(raw_input("Enter a number within the range: "))
question = ""
while question != low <= question <= high:
question = int(raw_input("Enter a number within the range: "))
In this case, the easiest solution is to use True as the condition in the while loop, and an if inside the loop to break out if the number is fine:
def ask_number(low, high):
while True:
try:
number = int(raw_input("Enter a number within the range: "))
except ValueError:
continue
if low <= number <= high:
return number
I also added a try/except statement to prevent the program from crashing if the user enters a string that can't be converted to a number.
Your while loop syntax would be more clear if you thought of it this way: "I want to keep asking the user for the answer while their answer is less than low or greater than high." Translated directly to Python, this would be
while question < low or question > high:
You should also not assign "" to question as this overwrites the user's first answer. If they get the number in the range the first time, they will still be asked again. Basically, you should remove this line:
question = ""
Your final code should look something like this:
def ask_number(low, high):
assert low < high
question = int(raw_input("Enter a number within the range: "))
while question < low or question > high:
question = int(raw_input("Enter a number within the range: "))
return question
print(ask_number(5,20))
def ask_number(low, high):
while True:
number = int(raw_input('Enter a number within the range: '))
if number in xrange(low, high + 1):
return number
def ask_number(low, high):
"""question cannot be less than the minimum value so we set it below the
minimum value so that the loop will execute at least once."""
question = low - 1
"""You want question to be within the range [high, low] (note the
inclusivity), which would mathematically look like 'low <= question <= high'.
Break that up into what appears to be one comparison at a time:
'low <= question and question <= high'. We want the while loop to loop when
this is false. While loops loop if the given condition is true. So we need to
negate that expression. Using the DeMorgan's Theorem, we now have
'low < question or question > high'."""
while question < low or question > high:
"""And this will obviously update the value for question. I spruced up
the only argument to raw_input() to make things a bit 'smoother'."""
question = int(raw_input("Enter a number within the range [%d, %d]: " % _
(low, high)))
# Return question.
return question

Categories

Resources