This is what I got:
H = int(input("Enter a number or enter -1 to end)"))
smallest = H
counter=0
while(True):
number = int(input("Enter a number: "))
if(number == -1):
break
if(number < H):
smallest = number
print(number, "is the smallest")
What am I doing wrong?
It appears your question suffered some format issues but I get what you're asking. Really, you're asking the user to "Enter a number (or -1 to end):" repeatedly and finding the smallest.
With that in mind, I put the first time you prompt the user into the loop also. Keep in mind:
'None' is Python's way of saying not yet set.
You have to test for 'None' first
It helps you identify when you enter -1 right off the bat.
So here's a solution similar to yours:
number = None
smallest = None
while(True):
number = int(input("Enter a whole number (or -1 to end): "))
if(number == -1):
break
if smallest == None or number < smallest:
smallest = number
if smallest == None:
print ("No number entered.")
else:
print(smallest, "is the smallest")
Design a program with a loop that lets the user enter a series of numbers. The user should enter -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.
The user can enter any number of input value: negative, 0, or positive. No arrays can be used. Also 2 modules have to be used to display a welcome message with a program description and display the largest and smallest numbers
My loop doesn't seem to be working properly since it only works twice regardless if I input -99 or not. It also takes whatever number is input first and displays it as the largest and smallest number.
def main():
#call the welcome module
displayWelcome()
#declare the local variables
smallest = int()
largest = int()
#prompt user for the first number
inputNum = int(input('Enter the first number (0 indicates end of input): '))
#initialize largest and smallest to user input
smallest = inputNum
largest = inputNum
#loop while sentinel has not been entered
while inputNum != -99:
#compare number input with largest and smallest
if inputNum < smallest:
smallest = inputNum
elif inputNum > largest:
largest = inputNum
#prompt user for another number
inputNum = int(input('Enter another number (0 indicates end of input): '))
#call module to display the numbers
displayLargestSmallest(largest, smallest)
def displayWelcome():
#display welcome message and program descr
print('Hello!')
print('This program displays the largest and')
print('smallest values of all input integers.')
print('-99 indicates end of input')
def displayLargestSmallest(largestInput, smallestInput):
#module to display numbers input
print('The largest number input is ',largestInput)
print('The smallest number input is ', smallestInput)
Small improvement suggestions:
you don't have max or min limits, so you should use None at the start.
use while True: and break so you don't have to write input() two times.
Code:
def main():
displayWelcome()
smallest = None
largest = None
while True:
#prompt user
inputNum = int(input('Enter number (-99 indicates end of input): '))
if inputNum == -99:
# exit loop
break
#compare number input with largest and smallest
if smallest is None or inputNum < smallest:
smallest = inputNum
if largest is None or inputNum > largest:
largest = inputNum
displayLargestSmallest(largest, smallest)
# display again at the end
displayLargestSmallest(largest, smallest)
Start
Declare Real n,N
String keep going
Display “Enter a number.”
Input n
While n!=-99,
Display “Will you keep going?(yes or no)”
Input keep going
if keep going =yes then
Display “You must add -99 if you’ll end.”
Display “Enter next number.”
Input N
if n<N then
Display “The smallest number is”,n
else
Display “The smallest number is”,N
else if n>N then
Display “The largest number is”,n
else
Display “The largest number is”’N
end if
end if
End while
Stop
Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example:
Smallest = 0
count = 0
while count < 10:
Number = int(input("Enter a number >> "))
if Number < Smallest:
Smallest = Number
count = count + 1
print("{0} is the biggest value you have entered".format(Smallest))
But how do I do it in a for loop format? Here's what I have so far:
for i in range(10):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
Initialize your Smallest variable and all will works!
Smallest = int(input("Enter a Number >> "))
for i in range(9):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
What you have there, other than the fact you should initialise Smallest, is equivalent to the solution using your while statement.
So, assuming the while variant is considered correct, the for variant you have will suffice.
The reason I qualify it is because initialising Smallest to zero is actually the wrong thing to do. If your ten numbers are all greater than twenty (for example), Smallest will remain at zero, giving you the wrong answer.
One way to fix this (in both variants) is to change your if statement to:
if i == 0 or Number < Smallest:
which will set Smallest first time through the loop regardless (though it should be count in the while variant since that's using a different loop control variable).
Of course, as you learn more and more about the language, you'll come across the concept of things that are more "Pythonic" than others. An example of this is the rather more succinct:
Smallest = min(int(input("Enter a Number >> ")) for i in range(10))
which removes the need totally for an explicit check-and-replace strategy (that's still done, but under the covers of the min function).
If you want to get the smallest of the input numbers, you need to start with a minimum a bit bigger than 0... and that is a problem you have with your while loop. It will only work if the user inputs at least one negative number, else it will return 0.
Here is what I suggest:
smallest = float("inf")
for i in range(10):
number = int(input("Enter a Number >> "))
if number < smallest:
smallest = number
print("{0} is the smallest value you have entered.".format(smallest))
Note that I did not capitalize the variables, because to me it makes them look like classes. ^^
Since you are finding the Smallest values out of the input values from the user it is good practice to initially initialize the Smallest variable as maximum possible integer as below.
import sys
Smallest = sys.maxint
Then the rest of your loop will work as properly as it is.
I am trying to learn Python through a course on Courser, and so far having a feeling I am not going to be able to.
I don't want an answer to the assignment, I want someone to push me in the right direction. Because Im stuck and the online tutors there are not being any help just repeating the obvious that is already stated in the assignment. The assignment is very simple, but I cant understand what I am missing.
Here is the assignment:
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.
Here is my code, i tried using the example codes we where show for getting the minimum and maximum, but the problem is in the examples we had they had lists, here I was told I dont need a list. But everytime the value of num changes with ever new input, how can i get the program to choose from certain numbers if they are not storing...or do you think i can enter lists in the raw_input?
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
largest = None
if largest is None:
largest = num
elif num > largest:
largest = num
smallest = None
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
The numbers from the book are 4, 5, 7 and a word
Thank you everyone for your support, I understand what I have to do, not sure if I understand how I will get there, but Im going to sit and keep trying. Meanwhile I am getting issues with indentation
let's say I rewrote the code like this and want to add an if statement into the while loop
largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
should the if statement start with the same indent as the continue and then the inside of the if indented again?? Because Im getting errors when I do that
largest = None
smallest = None
while True:
inp = input("Enter a number: ")
if inp == "done" : break
try:
num = float(inp)
except:
print ("Invalid input")
continue
if smallest is None:
smallest=num
if num > largest :
largest=num
elif num < smallest :
smallest=num
def done(largest,smallest):
print("Maximum is", int(largest))
print("Minimum is", int(smallest))
done(largest,smallest)
this will surly work.
You're on the right track with your current implementation, but there is some issues in the order of your operations, and where the operations are taking place. Trace through your program step by step, and try to see why your None assignment may be causing some issues, among other small things.
You are being asked to keep a running max and running min, the same way you could keep a running total. You just update the running <whatever> inside the loop, then discard the user's most recent input. In the case of running total, the code would look like tot = tot + newinput and you could then discard newinput (or, more likely, reuse it) without recording it in a list or any other data structure.
Not every problem permits a "running" solution. For instance, if you wanted to give the user an undo feature, letting them back out some of the numbers they entered earlier, you would have to keep an exact history of all the numbers. But here, you can get by without keeping that data.
You should check for the largest and smallest numbers inside the loop. First check if its a number - if yes, carry on and see if it is bigger than your current largest variable value (start with 0). If yes, replace it. See, if its smaller than your smallest value (start with the first number that comes in, if you start with 0 or just a random number, you might not get lower that that. If you start with the first number, then it'll definitely be the smallest (after all the loops)), etc, etc. All of that should be done inside the loop and after the loop should be just the printing. And yes, you don't need to use lists.
Let me give you a hint here, every time your while loop takes in a input, it sets the values of largest and smallest to None. Where should you initialize them?
I sense that your confusion partly stems from how the user is expected to give the input. One could interpret the instructions in two ways.
The user writes 4 5 7 randomword [ENTER]
The user writes 4 [ENTER] 5 [ENTER] 7 [ENTER] randomword [ENTER]
If it was the first variant, then you might be expected to process the whole thing as a list and determine its parts
However, the fact that they told you "you will not need lists for this exercise" implies that they expect the second scenario. Which means you should design your while loop such that at each iteration it expects to receive a single input from the user, and do something with it (i.e. check if it's bigger / smaller than the last). Whereas the loop you have now, will simply always keep the last input entered, until "done" is encountered.
Once you're out of the while loop, all you need to do is present the variables that you've so carefully collected and kept updating inside the loop, and that's it.
I figured it out I think, and the thing that was killing my code was the continue statement if I am not wrong
here is what i got, and please leave comments if I got it wrong
largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
if largest is None:
largest = num
elif num > largest:
largest = num
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
largest = None
smallest = None
while True:
inp = input("Enter a number: ")
if inp == "done" : break
try:
num = float(inp)
except:
print ("Invalid input")
continue
if smallest is None:
smallest=num
if num > largest :
largest=num
elif num < smallest :
smallest=num
def done(largest,smallest):
print("Maximum is", int(largest))
print("Minimum is", int(smallest))
done(largest,smallest)
maximum = -1
minimum = None
while True:
num = input('Enter the num: ')
if num == 'done':
break
try:
num1 = int(num)
except:
print('Invalid input')
continue
if minimum is None:
minimum = num1
if num1 > maximum:
maximum = num1
elif num1 < minimum:
minimum = num1
print('Maximum is', maximum)
print('Minimum is', minimum)
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
n=int(num)
except:
print("Invalid input")
continue
if largest is None:
largest=n
if n > largest:
largest=n
if smallest is None:
smallest=n
elif n < smallest:
smallest =n
print("Maximum is", largest)
print("Minimum is" , smallest)
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 7 years ago.
Improve this question
smallest = None
largest = None
while True :
number = raw_input('Enter a number from -10 to 9: ')
if largest < number :
largest = number
if smallest is None :
smallest = number
elif number < smallest :
smallest = number
if number == 'done': break
print 'Largest number is: ',largest
print 'Smallest number is ',smallest
I have no idea why my "smallest" is alright while "largest" outcome is always done. I think that "break" is somehow affecting it. Could You point out my mistake?
The problem is that you are first updating smallest and largest even if the user entered done. So first of all, you should check whether the input is 'done' and abort immediately before updating any of your numbers.
That being said, there are multiple other issues with your code:
if largest < number – You are updating largest if the number is smaller than the previously stored one, making it have the same logic as smallest. Of course, you will not end up with the largest number that way.
raw_input() returns a string, not a number. So if the user types for example 5, then what raw_input() returns is the string '5'. So every comparison you make is a string comparison (e.g. '2' < '5'). Because string comparisons are based on character codes, this will incidentally work for single-digit numbers but you should really convert the strings into proper numbers first.
You mention an allowed range of -10 to 9 but you never actually enforce that.
Something like this will work:
smallest = None
largest = None
while True:
number = raw_input('Enter a number from -10 to 9: ')
if number == 'done':
break
# convert into a number
try:
num = int(number)
except ValueError:
print('That was not a valid number')
continue # restart the loop
# validate the number range
if num < -10 or num > 9:
print('The number is out of the allowed range')
continue
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
print 'Largest number is:', largest
print 'Smallest number is:', smallest
If you encounter done, your loop should break immediately. But in your codes, you have put the break at the end. So before that, previous logic is being executed. And done as a string can be compared.
>>> None < 'done'
True
>>>
So your largest is set to done since largest < None in that case.
Quick Fix
We now moved the break on top, so this should fix the issue:
smallest = None
largest = None
while True :
number = raw_input('Enter a number from -10 to 9: ')
if number == 'done':
break
if largest < number :
largest = number
if smallest is None :
smallest = number
elif number < smallest :
smallest = number
print 'Largest number is: ',largest
print 'Smallest number is ',smallest
Handling Numbers
The raw_input returns string. But we want to compare numbers. So we should convert the inputs to int.
try:
num = int(number)
except ValueError:
print('Please enter a valid integer')
continue # skip the input and continue with the loop