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)).
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.
Given question - Given a list of 10 numbers, find the average of all such numbers which is a multiple of 3
num = []
newlist = []
for i in range(1, 11):
num.append(input())
for i in num:
if i%3==0:
newlist.append(i)
length = len(newlist)
total = sum(newlist)
average = total/length
print(average)
Getting this type error below at line 9 i.e. if i%3==0
not all arguments converted during string formatting
input() returns a string, so i%3 will actually perform printf-style string formatting. Since your input doesn't have any formatting specifiers, but the % operator's right operand is not empty, you get the error, because you attempted to format a sting that doesn't have enough formatting specifiers.
To solve this, convert your input to integers:
num.append(int(input()))
When you num.append(input()), the value of input() is a string. You need to first convert that to an int and handle any possible errors before continuing. One way to do this is to change it to:
num.append(int(input()))
Since all the values in num are strings, i % 3 tries to perform old-string formatting, which is not what you expect.
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.
I started to learn python last week and I have to write a while loop where the user is repeatedly asked to input an even number. Then, as long as he inputs an even number, the program should put out the sum of all of the previously added numbers. As soon as an odd number is added, the loop should stop without putting out the odd-numbered result.
Do you have any tipps?
thank you!
total = 0
while True:
number = int(input("enter number:" ))
if number % 2 == 0:
total += number
print(f"Total: {total}")
else:
print(f"Final total: {total}")
break
total = 0 - First, we want to initialize our total variable so that we can use it within the loop to count up the sum of all entries.
The while True: line starts an infinite loop. These can be dangerous, but we're going to break out of it later when a condition is met (in this case, an odd number being entered).
number = int(input("enter number: ")) asks the user for input, converts that input into and int and stores it in the variable called number.
if number % 2 == 0: - This checks whether or not the number is even using the modulo operator. This returns the remainder from the division of the first number into the second. For a number to be even, it must have a remainder of 0 when divided by 2.
total += number is shorthand for total = total + number. This simply adds the user's input to the total.
print(f"Total: {total}") prints out the total using an f-string. See PEP 498 for more info. Essentially, creating an f-string is as easy as putting an f before the literal string creation. This allows you to plug variables directly into strings instead of having to rely on the .format() method.
The above print line would be written as print("Total: {}".format(total)) if not using f-strings.
The else statement catches any number that is not even, so therefore must be odd. It prints out the final total and then break will make us leave our infinite loop.
I'm trying to make a program that will tell the user if the inputted number is either a prime number or not. I would like to know how to format it to where it will return the remainder. I have the following .py file that I made, but I keep getting error "not all arguments converted during string formatting":
i = 2
x = input("Input your proposed prime number now:\n")
number = x % i
print (number)
#Rishav had incorrect formatting, try:
x = int(input(Input your proposed prime number now:\n"))
if you are working with decimals, you can use:
y = float(input("Input a decimal > "))
input returns a string in Python3. Use :
x = int(input("Input your proposed prime number now:\n")