So, my exercise ask me to get inputs from the user (integer) and break the process of getting numbers once the user types "done". Then the desired output should be:
Smallest number =
Largest number =
Problem is:
I set 2 variables smallest and largest this way:
smallest = None
largest = None
But when i try to compare the user input with theses variables i get an error " TypeError: '>' not supported between instances of 'int' and 'NoneType', I tried casting the string to int an still getting the same error.
Can someone help me? Thanks,
My code so far:
largest = None
Smallest = None
while True:
num = input("Enter a number: ")
if num == "done": break
try:
val = float(num)
except:
print("Invalid input")
continue
number = int(num)
if number > largest:
largest =number
king
When the first valid input comes, the variable number is an int while the variable largest is still None. You try to compare them with '>' operator, that's why the error is thrown.
You can set the initial value of largest/smallest as the first valid number.
Related
while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
I've had a hard time understanding exactley what u want to do with this code, please use a proper code block next time, with proper indentation. My guess is that u want to get a input number like 345 and add 3+4+5 as a output. If the input is not a int it should break the loop. Ive come up with 2 diffrent solutions, depending on what you need.
This code will simply take the input and check if it is "done", if it is not "done" it will try to add. This is a easy to understand solution but it will produce a error if the input is any diffrent string than "done".
while True:
numbers = input(">")
if numbers == "done":
break
else:
total = 0
for number in numbers:
total += int(number)
print(total)
This approach will test for the "done" string again, but afterwards will also check if the input can be converted into a int. if not the error is captured and it will return "invalid input". If u want the programm to terminate at any string u can just put break in the except section.
while True:
numbers = input(">")
if numbers == "done":
break
else:
try:
testing = int(numbers)
total = 0
for number in numbers:
total += int(number)
except:
total = "invalid input"
print(total)
im a Beginner myself and if a experiencend person can show me a better way to do this i would be very interested
while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
Assuming this as your code:
Here's a solution to your problem-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
total=0
for number in numbers:
total = total + int(number)
print(total)
By default everything gets accepted as string so we convert it to integer to find total.
Also we use list to store all the values we accept.
Another Solution is-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
p=map(int,numbers)
print(sum(p))
Hope you understand the solution :-)
total = 0
average = 0
count = 0
while True:
numbers = input('> ')
if numbers == 'done': break
try:
total = int(numbers) + total
count = count + 1
except:
print('nope')
try:
average = total / count
except:
print('error')
print(total)
print(average)
print(count)
Try this:
total = 0
number_of_inputs = 0
while True:
number_string = input('Enter a number: ')
try:
total += float(number_string)
number_of_inputs += 1
except ValueError:
break # we weren't given a number, so exit the loop
# Now that we're outside of the loop, print out the total:
print('The total is:', total)
if number_of_inputs > 0:
average = total / number_of_inputs
print('The average is:', average)
else:
print('The average cannot be calculated, as no inputs were given.')
Do you see what's happening? The while loop keeps ask for and adding integers to total until a non-integer (like "done") is given. Once it gets that non-integer, the int() function will fail, and the exception it throws will get caught, and the code will immediately break out of the while loop.
And once out of the loop, the total and the average are printed out.
A few things you should be aware of:
If the user gave no inputs (which is possible here), the total will correctly print out as 0, but if you try to calculate the average, you will error, due to diving by number_of_inputs (which is also 0). That is why I check that number_of_inputs is greater than zero before I even attempt to calculate the average.
Originally I used int() to convert the string to a number, but I changed it to use float() instead. I figure that since you want to calculate an average, averages are not necessarily integers (even if all the inputs are), so there's no point in enforcing integer input. That is why I changed the int() to float(), but whether or not you want to use it is up to you.
ValueError isn't a function; it's an Exception. At this point you probably don't know what Exceptions are, so just know that they are special cases that can happen, and they're often used for catching errors, such as bad input values.
In the code I posted above, the loop is always expecting numerical input. But as soon as we have input that can't be converted to a number, the program then says, "Hey, I have an exception to what we're expecting! The exception is that there's an error in the value!" Then the program, instead of continuing to the next line of code (which is number_of_inputs += 1) will then execute the block of code under the except ValueError: section. And in the code above, all it does is call break, which exits the loop.
Once out of the loop, the code prints out the total and the average.
If it weren't for the try: and except ValueError: lines in the code, then the program would abruptly end (with a lengthy error message) once someone gave a non-numerical input. That happens because the call to float() wouldn't know how to convert a value like "done" to a number, so it does nothing more than just quitting.
However, by using try: and except ValueError:, we are anticipating that someone might give non-numerical input. When that happens (which it will, when the user is finished giving inputs) -- instead of quitting -- we want an alternate action to take. And we specify that alternate action to be a simple break out of the loop -- which will allow the program to continue with whatever is after the loop.
I hope this makes sense. If it doesn't, it will make more sense once you start learning about Exceptions in Python.
I'm trying to write a simple program where a variable will store the input type in by a user until the word "done" is seen. After that, the program will print out the maximum and minimum value store in the variable. However, I would like to prevent the variable from storing characters or strings where the user may accidentally type in. What are ways that I can use? Try and except?
a=0
store1=''
store2=''
while store1 !='done':
store1 = input('Enter a number: ')
store2=store2+' '+store1
a =a+1
store3=store2.split()
store4=store3[:a-1]
print('Maximum: %s'%(max(store4)))
print('Minimum: %s'%(min(store4)))
I tried another way and I got this problem. Does anyone know what is wrong?
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
a=0
store1=''
store2=''
while store1 !='done':
store1 = input('Enter a number: ')
b = RepresentsInt(store1)
if(b==True):
store2=store2+' '+store1
# a =a+1
store3=store2.split()
#store4=store3[:a-1]
print(store3)
print('Maximum: %s'%(max(store3)))
print('Minimum: %s'%(min(store3)))
#print(len(store3))
The stored value seems to contain only numbers in string-format. However, when it prints out the max and min values, it doesn't print out the correct max and min as the picture shown below.
Using your current implementation (number of issues), here's how you'd perform the check:
a=0
store1=''
store2=''
while store1 !='done':
store1 = input('Enter a number: ')
if store1 == 'done':
break;
try:
int(store1)
except ValueError:
continue
store2=store2+' '+store1
a =a+1
store3=store2.split()
store4=store3[:a-1]
print('Maximum: %s'%(max(store4)))
print('Minimum: %s'%(min(store4)))
I added in an immediate check for the input value (otherwise it executes the with the 'done' value, causing the Maximum: d output).
For the input checking, the approach is trying to convert the string to an integer and returning to the start of the loop if a ValueError is caught.
Using this looks like:
$ python3 input.py
Enter a number: 1
Enter a number: 2
Enter a number: what
Ivalid input.
Enter a number: 3
Enter a number: 4
Enter a number: done
Maximum: 3
Minimum: 1
So, we still have a problem with actually finding the maximum value. Which begs the question, why all the string manipulation?
Here's a simpler implementation using an array instead:
numbers = []
while True:
input_value = input('Enter a number: ')
if input_value == 'done':
break
try:
int_value = int(input_value)
except ValueError:
print("Ivalid input.")
continue
numbers.append(int_value)
print('Maximum: %s'%(max(numbers)))
print('Minimum: %s'%(min(numbers)))
Usage:
$ python3 input.py
Enter a number: 1
Enter a number: 2
Enter a number: what
Ivalid input.
Enter a number: 3
Enter a number: 4
Enter a number: done
Maximum: 4
Minimum: 1
EDIT: The problem with your second attempt is that you are performing a lexicographic sort, instead of a numerical one. This is due to fact that the array is storing string values.
# sorting strings, lexicographically
>>> [x for x in sorted(['1000', '80', '10'])]
['10', '1000', '80']
# sorting numbers, numerically
>>> [x for x in sorted([1000, 80, 10])]
[10, 80, 1000]
In my fixed example above, the strings are converted to integer values before they get stored in the array, so they end up being sorted numerically.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I'm learning python, and am stuck on a project. The main part of the project was to code the collatz sequence, which wasn't a problem. The next part is to validate the user input using try and except, in order to make sure only an integer value is given in.
So far, I have the following code:
def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return (3*number) + 1
print('Please enter a number:')
number = ''
try:
number = int(input())
except ValueError:
print('Incorrect type of data entered.\nPlease enter an integer!')
while number is not int:
try:
number = int(input())
except ValueError:
print('Incorrect type of data entered.\nPlease enter an integer!')
output = number
while output != 1:
output = collatz(output)
print(output)
My problem is I'm not sure how to repeat the try/except statement until I get an integer from the user. Right now, if I enter a string instead of an integer, the program goes into a loop and entering an integer subsequently does not help. I read quite a few threads on the topic, but they didn't shed light as to the aforementioned problem.
Would really like to understand where I'm going wrong.
You can use:
valid=False
while not valid:
try:
number=int(input())
valid=True
except ValueError:
print('Incorrect type of data entered.\nPlease enter an integer!')
Just use isinstance(x, int), where x is input.
It returns True if x is an int. Just another solution, in case you were looking for a different way!
I am very new to programming, please advise me if my code is correct.
I am trying to 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.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))
This is what I want to accomplish:
let the user type in a number with four digits
if this number is not equal to 6174 (Kaprekar’s constant) then sort the numbers in two ways:
a. from the biggest to the smallest number
b. from the smallest to the biggest
Subtract the bigger number with the smaller
If the result is not equal to 6174, then do the calculation again and write the result for each and every calculation
When the result is equal to 6174, write a message to show that the calculation is done
This is what I’ve tried:
print("type in a number")
number = (input())
while number != 6174:
start_big = "".join(sorted(number, reverse=True))
start_small = "".join(sorted(number))
number = (int(start_big)-int(start_small))
print(number)
print("Calculation finnished!")
I’m getting the error:
start_big = "".join(sorted(number, reverse=True)) TypeError: 'int'
object is not iterable
When you calculate this:
number = (int(start_big)-int(start_small))
The type of number becomes int, so in the next iteration the error occurs.
One solution would be
print("type in a number")
number = input()
while number != "6174":
start_big = "".join(sorted(number, reverse=True))
start_small = "".join(sorted(number))
number = str((int(start_big) - int(start_small)))
print(number)
print("Calculation finnished!")
you have to convert the input number to an iterable, you can just do
number = iter(number)
also you need to change the while loop condition:
while int(number) != 6174:
for printing the number just do this:
number = str((int(start_big)-int(start_small)))
You are almost there. You need to convert number to an iterable. I suggest:
start_big = "".join(sorted(str(number), reverse=True))
start_small = "".join(sorted(str(number)number))
You have multiple issues with your solution:
input() always returns a string, so number will never be an integer and as such it will never be equal to 6174. So your loop will still run for an input of 6174.
You need to convert the string into a number first, you can do that by simply calling int() on the string. Note that this may fail, so you might want to ask the user for input until they enter a valid number.
Once number is an integer, it is no longer an iterable, so you cannot call sorted() on it. If you want to sort the digits, then you need to convert it into a string first: sorted(str(number)).