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")
Related
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))
can you please tell me why do i get error for this?
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 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
try:
num=input("Enter a number: ")
if num == 'done':
break
num=int(num)
if largest == None or largest<num:
largest = num
elif smallest == None or smallest > num:
smallest = num
except ValueError:
print ("Invalid input")
break
print ("Maximum number is", int(largest))
print ("Minimum number is", int(smallest))
You may be using Python 2 instead of Python 3 - please check this. If you are using Python 2, you should be using raw_input() instead of input().
Change elif to if:
if largest == None or largest<num:
largest = num
if smallest == None or smallest > num:
smallest = num
That will guarantee both largest and smallest are both integers (unless the first input is done or another invalid value).
You need to check if largest or smallest is None.
Append the user input to a list inside the while loop, and then slice it in the final print statements:
largest = None
smallest = None
nums = []
while True:
try:
num = input("Enter a number: ")
if num == 'done':
break
num = int(num)
nums.append(num)
except ValueError:
print("Invalid input")
break
print("Maximum number is", max(nums))
print("Minimum number is", min(nums))
Example run:
Enter a number: 22
Enter a number: 2
Enter a number: done
Maximum number is 22
Minimum number is 2
Posting the output and/or the error would be very helpful to help you.
You have to change elif into if and remove the break clause inside the except in order to keep asking for numbers even after an invalid input.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == 'done':
break
num=int(num)
if largest == None or largest < num:
largest = num
if smallest == None or smallest > num:
smallest = num
except ValueError:
print ("Invalid input")
print ("Maximum number is", int(largest))
print ("Minimum number is", int(smallest))
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)
I try to use python to prompt user to enter different number, and keep the largest one, and finish when user enter "done". but I find out it can not work with different digit of number. for example, 1st entry: 91, 2nd:94, it will run well. but 1st entry:91 and 2nd:100, it can not record 100 as the largest number. did somebody know what's going on? thank you so much!
code:
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done":
break
try: int (num)
except:
print "Please enter a numeric number"
if largest is None and smallest is None:
largest = num
smallest = num
#print "l", largest
#print "s", smallest
if num > largest:
largest = num
print largest, num
#if num < smallest:
# smallest = num
# print "s2", smallest
print num
print "Maximum is ", largest
#print "Minimum is ", smallest
you're doing ASCII comparisons, not numeric. you need to actually assign something like number = int(num) and use number for comparison.
The problem is you're not converting num to an integer, so it's using string comparison rather than numeric comparison. Change:
try: int (num)
to:
try:
num = int(num)
You've got a number of problems. Take a look at this, maybe you can incorporate it into your own code?
largest = 0
while True:
prompt = raw_input("Enter a number: ")
try:
num = int(prompt)
if num > largest:
largest = num
except:
if prompt == 'done':
break
print largest
raw_input returns a string. So when you compare num > largest you are using string (alphabetical) comparison. You want to compare numbers. The easiest way would be to simply rewrite the comparion to int(num) > int(largest).
try: int (num) ... already checks if the input is a number but it does not change the value of the variable.
Note: except without an exception type is generally not a good idea. You should explicitly write down the exception you want to catch: ValueError
I'm incredibly new to python, so I apologize. I finally got rid of all the syntax errors, but now I just have no idea what I did wrong.
#Get the integers from the user
def main():
largest = 0
smallest = 0
number = int(input('Input a number: '))
while (number != -99):
if number > largest:
largest = number
elif number < smallest:
smallest = number
number = int(input('Input a number, enter -99 to stop'))
# This module displays the smallest and largest integer entered.
def showNumber(smallest, largest):
print('The smallest number is: ', smallest)
print('The largest number is: ', largest)
#Call the main
main()
showNumber(smallest, largest)
This is supposed to ask the users for numbers until they put -99, then when they put -99 it's supposed to show the smallest and largest integer.
I know, it's so ugly. I can only use simple data types.
You can add additional 4 characters (spaces) to get it correct, which is by adding indentation on one line
def main():
largest = 0
smallest = 0
while (number != -99):
if number > largest:
largest = number
elif number < smallest:
smallest = number
number = int(input('Input a number, enter -99 to stop')) # Indent this line
You can compare your code with the code I show above. There are differences on the line I commented in, which is the amount of preceding space (the indentation)
Because otherwise the while loop will not end, since the number is updated outside the while loop.
Your incorrect code:
while (number != -99):
### The while loop starts here ###
if number > largest:
largest = number
elif number < smallest:
smallest = number
### The while loop ends here ###
number = int(input('Input a number, enter -99 to stop'))
So the while loop will never end, because it keeps comparing the same number, not comparing with the new input. In this case your program does not stop as you said, but rather it is stuck in what is called infinite loop
Python "code block" is defined by the indentation, so codes with the same level of indentation are considered to be in the same code block. So in order to your number to be changing each time you visit the loop, you need to put the input inside the while loop:
The corrected code:
while (number != -99):
### The while loop starts here ###
if number > largest:
largest = number
elif number < smallest:
smallest = number
number = int(input('Input a number, enter -99 to stop'))
### The while loop ends here ###
Update (by #MERM):
You also have some problem on the showNumber function, as it's not using the variables from the main function. You can call the showNumber function in the main function like MERM has said:
def main():
largest = 0
smallest = 0
while (number != -99):
if number > largest:
largest = number
elif number < smallest:
smallest = number
number = int(input('Input a number, enter -99 to stop'))
showNumber(smallest, largest)
And some words of encouragement, your code is not ugly. In fact it's good and concise, precisely solving the problem you're trying to solve. You seem to understand how you should lay out your logic in the code, even though you said you're "incredibly new to python".
Keep it up!
Python is indent sensitive.
The elif and number needs to be at the same indentation as the if. Also, you need to call showNumber from inside main otherwise smallest and largest are undefined (not in the same scope).
def main():
number = int(input('Input a number: '))
largest = number
smallest = number
while (number != -99):
if (number > largest):
largest = number
elif (number < smallest):
smallest = number
number = int(input('Input a number, enter -99 to stop'))
showNumber(smallest, largest)
That should take care of it.