I am trying to count the number of digits of an input. However, whenever I input 10 or 11 or any two digit number, the output is 325. Why doesn't it work?
inputnumber = int(input())
countnumber = inputnumber
digitcount = 0
while countnumber > 0:
digitcount += 1
countnumber = countnumber/10
print(digitcount)
# result is 325 when input is 10 or 11
Your error mainly happened here:
countnumber=countnumber/10
Note that you are intending to do integer division. Single-slash division in Python 3 is always "float" or "real" division, which yields a float value and a decimal part if necessary.
Replace it with double-slash division, which is integer division: countnumber = countnumber // 10. Each time integer division is performed in this case, the rightmost digit is cut.
You also have to watch out if your input is 0. The number 0 is considered to be one digit, not zero.
I would not convert that beautiful input to int to be honest.
print(len(input())
would be sufficient.
An easily understandable one liner that no one can complain about.
But of course, if negative sign bothers you like wisty said,
len(str(abs(int (v))))
will be safer for sure.
Again, if you are worried about the non numeric inputs like mulliganaceous said, you better cover that case.
str = input()
if str.isnumeric():
print(len(str(abs(v))))
else:
print("bad input")
The reason is that in python 3 the division of two integers yields a floating point number. It can be fixed using the // operator:
number = int(input())
digits_count = 0
while number > 0:
digits_count += 1
number = number // 10
You must be using Python3, logically your function is right. You just have to change
countnumber = countnumber // 10
because Python3, // is floor division, meanwhile / is true division.
>>>print(1 / 10)
0.1
>>>print(1 // 10)
0
Btw, as #chrisz said above, you can just simply using the len() function to get the number of digits of the input
>>>print(len(input())
num = int(input())
count = 0
while num > 0:
count += 1
num = num // 10
print(count)
def digits(number):
number = str(number)
lenght = len(number)
return lenght
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
Related
i made a code to split an integer and add them individually but in some scenario the sum is wrong
for example the output expected for 555 is 15 but it shows 16
def find_sum_of_digits(number):
sum_of_digits=0
sum=0
var=0
#Write your logic here
while number>0:
var = number%10
sum += var
number = number/10
sum_of_digits=sum
return int(sum_of_digits)
#Provide different values for number and test your program
sum_of_digits=find_sum_of_digits(123)
print("Sum of digits:",sum_of_digits)
The output i want is to add 123 to display 6 and as vice versa to other integer values
A simple print to trace your values would show the problem:
number = number/10
You need integer division:
number = number//10
Your code computes the infinite sum, and then has to divide by 10 until the remaining number dwindles to 0 for the internal representation.
An easier way to do this is to take the original string input and convert each character of the string to a single-digit integer. Add those integers.
You can also do this:
number = int(input("Enter the Number: "))
sum_of_digits = 0
while number > 0:
digit = number % 10
sum_of_digits = sum_of_digits + digit
number = number // 10
An alternative solution would be:
def find_sum_of_digits(number):
return sum([int(n) for n in str(number)])
Below is a solution that uses the example provided in your original question as a starting point.
def find_sum_of_digits(number):
result = 0 # Variable to store result
while number > 0:
digit = number % 10 # Current digit is remainder from number / 10
result += digit # Add digit to result and assign value to result variable
number //= 10 # Number is number // 10 to shift left to next digit, disregarding fractional part of quotient
return result
Note the use of the floor division operator(//) instead of the standard division operator (/) when dividing number by 10 to shift left to the next digit. It is this change that will stop you from getting erroneous return values (such as 16 instead of 15 when number = 555).
Python floor division returns an int representing the truncated division of two numbers; instead of a float (as standard division does in Python), this is required for your purposes as you are only concerned with the int digits of number and not any fractional portions that may arise from standard division - these are being summed before you cast back to int in your original example.
Here is another valid solution that results in the desired output. This time we are returning the result of the sum function which is given a list comprehension of int instances representing each digit of number.
def find_sum_of_digits(number):
return sum([int(d) for d in str(number)])
In this case, the int representing each digit of number is found by first casting number to a str, then iterating across each char of the number str, casting each back to an int.
This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 3 years ago.
I have created a small Python program in repl.it to illustrate the Collatz Conjecture, which says that if you start with any positive integer number n and you apply the following operations recursively: n/2 if n is even, 3n+1 if n is odd, you will always reach 1.
This is the code:
invalid_input = 0
while(invalid_input == 0):
n = input("Give me a positive integer: ")
try: #check for positive integer. If it cannot do int(n) it means a string was entered, and it goes to except.
if(int(n)>0):
invalid_input = 1 #this is to tell the while loop above that the right input was entered
print("Thank you.")
print("Now loading:")
else: #an integer was entered, but it was negative
print("Please enter a positive integer")
except: #a string was entered
print("Please enter a positive integer")
n=int(n)
nentered = n #this will keep track of the initial n
npeak = n #this will keep track of the highest n reached
iteration = 1 #this will keep track of the number of iterations
iterationmax = 1 #this will keep tack of the iteration at which npeak was reached
while(n != 1):
print("%5i: %5i" % (iteration,n))
if(n % 2 == 0): #divide by 2 if even
n=n/2
else: #if it is odd, multiply by 3 and add 1
n=3*n+1
iteration = iteration + 1
if(n>npeak): #record the higher n and its iteration
npeak = n
iterationmax = iteration
It works. But there is a problem: if the entered number is big enough, for example 6666666666666666666666666, then it does something really strange. This is what I get:
Give me a positive integer: 6666666666666666666666666
Thank you.
Now loading:
1: 6666666666666666666666666
2: 3333333333333333277409280
3: 1666666666666666638704640
4: 833333333333333319352320
5: 416666666666666659676160
6: 208333333333333329838080
7: 104166666666666664919040
8: 52083333333333332459520
9: 26041666666666666229760
10: 13020833333333333114880
etc
As you can see, I am expecting the second number to be exactly 3333333333333333333333333, but instead I am getting different numbers at the end.
As another example, entering 1000000000000000000000000 returns 499999999999999991611392 in the second iteration.
What could be the reason for this?
The reason of why what #ruohola said is true, is because when you use floating-point division with a single /, what happens is that a floating-point number is created. However, it cannot be represented as the number is so large, so it is rounded to the closest most accurate representation. So you will have to use // instead of /.
However, using //, is integer division. This results in an integer which can be represented much easier than a high float.
A very similar question can be found here, it contains some more explanation.
Change your / operation to be //, so that they don't result in (inaccurate) floating point values.
So this:
if(n % 2 == 0): #divide by 2 if even
n=n/2
Should be:
if(n % 2 == 0): #divide by 2 if even
n=n//2
Or as properly formatted by Python conventions:
if n % 2 == 0:
n //= 2
With my code, I want to get the last two digits of an integer. But when I make x a positive number, it will take the first x digits, if it is a negative number, it will remove the first x digits.
Code:
number_of_numbers = 1
num = 9
while number_of_numbers <= 100:
done = False
num = num*10
num = num+1
while done == False:
num_last = int(repr(num)[x])
if num_last%14 == 0:
number_of_numbers = number_of_numbers + 1
done = True
else:
num = num + 1
print(num)
Why don't you extract the absolute value of the number modulus 100? That is, use
abs(num) % 100
to extract the last two digits?
In terms of performance and clarity, this method is hard to beat.
To get the last 2 digits of num I would use a 1 line simple hack:
str(num)[-2:]
This would give a string.
To get an int, just wrap with int:
int(str(num)[-2:])
Simpler way to extract last two digits of the number (less efficient) is to convert the number to str and slice the last two digits of the number. For example:
# sample function
def get_last_digits(num, last_digits_count=2):
return int(str(num)[-last_digits_count:])
# ^ convert the number back to `int`
OR, you may achieve it via using modulo % operator (more efficient), (to know more, check How does % work in Python?) as:
def get_last_digits(num, last_digits_count=2):
return abs(num) % (10**last_digits_count)
# ^ perform `%` on absolute value to cover `-`ive numbers
Sample run:
>>> get_last_digits(95432)
32
>>> get_last_digits(2)
2
>>> get_last_digits(34644, last_digits_count=4)
4644
to get the last 2 digits of an integer.
a = int(input())
print(a % 100)
You can try this:
float(str(num)[-2:])
How can I pick one of the digits from an Integer like: 97723
and choose (for example) the number 2 from that number and check if its an odd or an even number?
Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)
Thanks in advance
2 is the 4th digit.
You can get the digits of a number using this construct.
digits = [int(_) for _ in str(97723)]
This expression will be true if the 4th digit is even.
digits[3] % 2 == 0
# choose a digit (by index)
integer = 97723
digit_3 = str(integer)[3]
print(digit_3)
# check if even:
if int(digit_3) % 2 == 0:
print(digit_3, "is even")
# get all odd numbers directly
odd_digits = [digit for digit in str(integer) if int(digit) % 2 == 1]
print(odd_digits)
even = lambda integer: int("".join([num for num in str(integer) if int(num) % 2 == 0]))
or
def even(integer):
result = ""
integer = str(integer)
for num in integer:
if int(num) % 2 == 0:
result += num
result = int(result)
return(result)
If you want to "parse" a number the easiest way to do this is to convert it to string. You can convert an int to string like this s = string(500). Then use string index to get character that you want. For example if you want first character (number) then use this string_name[0], for second character (number) use string_name[1] . To get length of your string (number) use len(string). And to check if number is odd or even mod it with 2.
# Converting int to string
int_to_sting = str(97723)
# Getting number of characters in your string (in this case number)
n_of_numbers = len(int_to_sting)
# Example usage of string index
print("First number in your number is: ",int_to_sting[0])
print("Second number in your number is: ",int_to_sting[1])
# We need to check for every number, and since the first number is int_to_sting[0] and len(int_to_sting) returns actual length of string we need to reduce it by 1
for i in range(n_of_numbers-1):
if int_to_sting[i]%2==0:
print(int_to_sting[i]," is even")
else:
print(int_to_sting[i]," is odd")
I'm working on a problem that involves putting in an input, integer n, that when doing so will print off the following 4 "multiples" of the integer. I need to do this for 3 integers, n = 5, n = 0, n = 3.
Original Question:
Implement a program that requests a positive
integer n from the user and prints the first four multiples of n: Test
your module for n = 5; n = 0 and n = 3.
The output of the code should look like:
>>>
Enter n: 5
5
10
15
20
So, what I've come up with so far is this
n = (input("Enter n:"))
This allows me to input an integer value.
Next using print(n), this will print the value I input (Ex. number 5), but I'm not sure how to print off multiples of it after. I realize it's a loop question, most likely involving if or in, but I'm not sure where to go after this.
You've pretty much figured out the question on your own. The correct code is:
n = int(input("Enter n:"))
for i in range(4):
print(n*(i+1))
So, what this for loop does for you is repeat your print statement 4 times, where you give i the values of the expression range(4).
If you just print(range(4)), you'll see that it evaluates to [0,1,2,3]. That's why I had to add 1 to it each time.
The int() function call is needed because input() returns a string, not a number. So if we want the mathematical operators to do what we expect, we need to first convert it to a number (in this case, an integer).
This is the general logic:
n = (input("enter n:"))
for(int i = 1; i <= 4; i++){
print(int(float((n))*i);
}
if you want the list to start with 0 you can do this, it has an error but it can be fixed...
number = int(input("Give a number:"))
for multiples in range(10):
getal1 = number * multiples
print("\t The", str(multiples + 1) + "e multiple of," + number, "is", str(getal1) + ".")