Add commas into number string [duplicate] - python

This question already has answers here:
How to print a number using commas as thousands separators
(30 answers)
Closed 10 months ago.
I have a value running through my program that puts out a number rounded to 2 decimal places at the end, like this:
print ("Total cost is: ${:0.2f}".format(TotalAmount))
Is there a way to insert a comma value every 3 digits left of the decimal point?
e.g. 10000.00 becomes 10,000.00 or 1000000.00 becomes 1,000,000.00.

In Python 2.7 and 3.x, you can use the format syntax :,
>>> total_amount = 10000
>>> print("{:,}".format(total_amount))
10,000
>>> print("Total cost is: ${:,.2f}".format(total_amount))
Total cost is: $10,000.00
This is documented in PEP 378 -- Format Specifier for Thousands Separator and has an example in the Official Docs "Using the comma as a thousands separator"

if you are using Python 3 or above, here is an easier way to insert a comma:
First way
value = -12345672
print (format (value, ',d'))
or another way
value = -12345672
print ('{:,}'.format(value))

You could use locale.currency if TotalAmount represents money. It works on Python <2.7 too:
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.utf8'
>>> locale.currency(123456.789, symbol=False, grouping=True)
'123,456.79'
Note: it doesn't work with the C locale so you should set some other locale before calling it.

another way very short is
value = -122212123.12
print(f"{value:,}")

'{:20,.2f}'.format(TotalAmount)

This is not particularly elegant but should work too :
a = "1000000.00"
e = list(a.split(".")[0])
for i in range(len(e))[::-3][1:]:
e.insert(i+1,",")
result = "".join(e)+"."+a.split(".")[1]

A function that works in python2.7+ or python3.1+
def comma(num):
'''Add comma to every 3rd digit. Takes int or float and
returns string.'''
if type(num) == int:
return '{:,}'.format(num)
elif type(num) == float:
return '{:,.2f}'.format(num) # Rounds to 2 decimal places
else:
print("Need int or float as input to function comma()!")

Latest versions of python use f-strings. So you can do this:
print("Total cost: {total_amount:,}
As long as total_amount is a not a string. Otherwise you'd need to cast it to a number type first like so:
print("Total cost: {Decimal(total_amount):,}

The above answers are so much nicer than the code I was using in my (not-homework) project:
def commaize(number):
text = str(number)
parts = text.split(".")
ret = ""
if len(parts) > 1:
ret = "."
ret += parts[1] # Apparently commas aren't used to the right of the decimal point
# The -1 offsets to len() and 0 are because len() is 1 based but text[] is 0 based
for i in range(len(parts[0]) - 1,-1,-1):
# We can't just check (i % 3) because we're counting from right to left
# and i is counting from left to right. We can overcome this by checking
# len() - i, although it needs to be adjusted for the off-by-one with a -1
# We also make sure we aren't at the far-right (len() - 1) so we don't end
# with a comma
if (len(parts[0]) - i - 1) % 3 == 0 and i != len(parts[0]) - 1:
ret = "," + ret
ret = parts[0][i] + ret
return ret

Started learning Python about 5 hours ago, but I think I came up with something for integers (sorry, couldn't figure out floats). I'm in high school, so big chance the code could be way more efficient; I just made something from scratch that made sense to me. If anyone has any ideas on how to improve with ample explanation of how it works, let me know!
# Inserts comma separators
def place_value(num):
perm_num = num # Stores "num" to ensure it cannot be modified
lis_num = list(str(num)) # Makes "num" into a list of single-character strings since lists are easier to manipulate
if len(str(perm_num)) > 3:
index_offset = 0 # Every time a comma is added, the numbers are all shifted over one
for index in range(len(str(perm_num))): # Converts "perm_num" to string so len() can count the length, then uses that for a range
mod_index = (index + 1) % 3 # Locates every 3 index
neg_index = -1 * (index + 1 + index_offset) # Calculates the index that the comma will be inserted at
if mod_index == 0: # If "index" is evenly divisible by 3
lis_num.insert(neg_index, ",") # Adds comma place of negative index
index_offset += 1 # Every time a comma is added, the index of all items in list are increased by 1 from the back
str_num = "".join(lis_num) # Joins list back together into string
else: # If the number is less than or equal to 3 digits long, don't separate with commas
str_num = str(num)
return str_num

I feel comfortable using like this in python:
input_value=float(input())
print("{:,}".format(input_value))

Related

Stopping summation loop as soon as digits after decimal points stop changing

I have a loop that calculates a approximation. The loop should stop as soon as 10 digits after the decimalpoint stop changing. But I just can't get it to stop.
This is what I tried:
summe = 0
i = 0
l = []
while True:
i = i + 1
summe = summe + 1/(i**3)
l.append(format(summe, '.20f'))
if l[i][:14] == l[i+1][:14]:
break
Here is a example of what the first elements of the list looks like:
['1.00000000000000000000',
'1.12500000000000000000',
'1.16203703703703697947',
'1.17766203703703697947',
'1.18566203703703698658',
'1.19029166666666652574']
So it should continue until the first 10 digits after the decimal point stop changing. Also tried it with i-1 instead of i+1 in the if statement. So shouldn't it compare the element and the element before with each other? Like l[3] == l[2].
Edit: I just saw it should be [:12] instead of [:14]. But same problem is still there
Solution:
summe = 0
summe_10dps = f'{summe:.10f}'
prev_summe_10dps = '' # anything as long as it's != summe_10dps
i = 0
while summe_10dps != prev_summe_10dps:
i = i + 1
prev_summe_10dps = summe_10dps # remember previous sum
print(f'i={i} {summe_10dps} {prev_summe_10dps}') # check
summe = summe + 1/(i**3)
summe_10dps = f'{summe:.10f}'
Notes:
since you only want to inspect the first 10 dps, only output 10dps! Instead of outputting unlimited precision then having to string-slice it.
Using f-strings f'{summe:.10f}' is more compact than the old str.format.
Inside your loop, keep the previous 10dps string value prev_summe_10dps. Then the loop termination condition is simpler and more efficient, just checking if summe_10dps == prev_summe_10dps
There's no reason at all to keep a list, you can just directly compare and termination condition: while summe_10dps != prev_summe_10dps: in a while-loop. Or I had done a while True: ... with an if summe_10dps == prev_summe_10dps: break termination. The former seems slightly better style.
One slight caveat about implementing the "first 10 decimal places stop changing": beware that ':.f' format rounds the unwanted dp's (rather than truncate), and '{:.10f}'.format(1.2000000991500) rounds down to '1.2000000991'
(FYI by the way, the well-known way to get more accuracy, instead sum the series from smallest absolute value to largest, i.e. in reverse order for i = range(large_value_of_i, 0, step=-1). But you're not being asked to do that here.)
Result:
...
i=2190 1.2020567989 1.2020567989
i=2191 1.2020567990 1.2020567990
i=2192 1.2020567991 1.2020567991
The if statement requires the list to contain at least two elements. During the first iteration it will only contain one.
Seems a shame to use strings for this when you can check it mathematically:
summe = 0
i = 1
add = 1.0
while add > 1e-11:
summe += add
i += 1
add = 1/(i**3)
print(summe)

Why do I get a wrong XOR output

I just started the cryptopals.com challenge and I'm already stuck at the second problem.. For some reason my output is wrong by only one character instead of 7 I get a 3 as the first number of my XOR operation.
Could you help me find the mistake in my code:
def XORfunction(input_1, input_2):
bin_input_1 = hexToBinary(input_1)
bin_input_2 = hexToBinary(input_2)
# check if length of strings is the same for XOR compare or add "0" to the end
if len(bin_input_1) != len(bin_input_2):
if len(bin_input_1) > len(bin_input_2):
number_length = len(bin_input_1)
temp_input = list(bin_input_2)
for x in xrange(0, number_length - len(bin_input_2)):
temp_input.insert(0, "0")
bin_input_2 = "".join(temp_input)
if len(bin_input_1) < len(bin_input_2):
number_length = len(bin_input_2)
temp_input = list(bin_input_1)
for x in xrange(0, number_length - len(bin_input_1)):
temp_input.insert(0, "0")
bin_input_1 = "".join(temp_input)
solution = []
# XOR is like a sum so if el1+el2 == 1 output is 1 else output is 0
for x in xrange(0, len(bin_input_1) - 1):
# the array is iterated from [0] to len(bin_input_1)-1 so the elements are calculated from last to first
current_compare = int(bin_input_1[x]) + int(bin_input_2[x])
if current_compare == 1:
solution.insert(-1, "1")
else:
solution.insert(-1, "0")
return dec_to_hex(int("".join(solution), 2))
# the final solution has to be converted from decimal to hexadecimal
def dec_to_hex(value):
dictionary_hex = "0123456789abcdef"
solution = []
while value != 0:
solution.insert(0, dictionary_hex[value % 16])
value = value / 16
return "".join(solution)
# Hex is converted to a binary string to make comparisons easy as the digits become easy to select as an array of chars
def hexToBinary(text):
# first Hex is converted to decimal, then to binary (that needs to be sliced for a clean output), lastly it becomes a string
return str(bin(int(text, base=16))[2:])
print XORfunction("1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965")
# expected output: 746865206b696420646f6e277420706c6179
# my output: 346865206b696420646f6e277420706c6179
This is my first time posting, so any tip on formatting/on the code is welcome.
PS: I know I should be using libraries, but I want to figure out what is my mistake first
You have several issues:
Your hexToBinary() function doesn't produce padded binary. bin() will not return 8 bits per byte; leading zeros are not included! As such, you are missing 000 from the start of the first string, 0 from the other. You try to compensate for this in your XORfunction function, but that only adds back 2 zeros, not 3.
You could use the str.format() method instead to ensure that you get the right number of bits, zero padded:
return '{:0{}b}'.format(int(text, base=16), len(text) * 4)
The b formatting instruction tells str.format() to produce the binary representation of a number. 0 before the width means to zero-pad the number to the required length, and the {} placeholder for the length is taken from the len(text) * 4 value, so 4 bits per hex character in the input.
You are inserting the solution bits before the last element in the list. This leaves the very first bit right at the end of your solution, with everything else inserted before it:
>>> demo = []
>>> demo.insert(-1, 'foo') # inserting into an empty list
>>> demo
['foo']
>>> demo.insert(-1, 'bar') # inserting before the last element
>>> demo
['bar', 'foo']
>>> demo.insert(-1, 'spam') # inserting before the last element
['bar', 'spam', 'foo']
Just use appending to add elements to the end of a list:
solution.append("1")
and
solution.append("0")
You skip processing the last bit. You need to iterate all the way to len(bin_input_1):
for x in xrange(len(bin_input_1)):
With those 3 fixes applied, your code works and produces the expected output.
Your code is indeed re-inventing standard wheels in the Python language and standard library:
Rather than manually XOR every bit, use the ^ operator to work on a whole byte at a time.
Use the binascii.hexlify() and binascii.unhexlify() functions to convert between hexadecimal and bytes.
In Python 2, use the bytearray() type to work with binary data as a sequence of integers, this is much easier to apply XOR operations to.
Use the zip() function to iterate over two sequences together, pairing up elements from both.
Put together as a Python 2 solution:
from binascii import hexlify, unhexlify
def XORfunction(input_1, input_2):
input_1 = bytearray(unhexlify(input_1))
input_2 = bytearray(unhexlify(input_2))
return hexlify(bytearray(
a ^ b for a, b in zip(input_1, input_2)))
In Python 3, you can simply omit the first two bytearray() calls, and replace the last with bytes().

Is there a better way to write the following method in python?

I am writing a small program, in python, which will find a lone missing element from an arithmetic progression (where the starting element could be both positive and negative and the series could be ascending or descending).
so for example: if the input is 1 3 5 9 11, then the function should return 7 as this is the lone missing element in the above AP series.
The input format: the input elements are separated by 1 white space and not commas as is commonly done.
Here is the code:
def find_missing_elm_ap_series(n, series):
ap = series
ap = ap.split(' ')
ap = [int(i) for i in ap]
cd = []
for i in range(n-1):
cd.append(ap[i+1]-ap[i])
common_diff = 0
if len(set(cd)) == 1:
print 'The series is complete'
return series
else:
cd = [abs(i) for i in cd]
common_diff = min(cd)
if ap[0] > ap[1]:
common_diff = (-1)*common_diff
new_ap = []
for i in range(n+1):
new_ap.append(ap[0] + i*common_diff)
missing_element = set(new_ap).difference(set(ap))
return missing_element
where n is the length of the series provided (the series with the missing element:5 in the above example).
I am sure there are other shorter and more elegant way of writing this code in python. Can anybody help ?
Thanks
BTW: i am learning python by myself and hence the question.
Based on the fact that if an element is missing it is exactly expected-sum(series) - actual-sum(series). The expected sum for a series with n elements starting at a and ending at b is (a+b)*n/2. The rest is Python:
def find_missing(series):
A = map(int, series.split(' '))
a, b, n, sumA = A[0], A[-1], len(A), sum(A)
if (a+b)*n/2 == sumA:
return None #no element missing
return (a+b)*(n+1)/2-sumA
print find_missing("1 3 5 9") #7
print find_missing("-1 1 3 5 9") #7
print find_missing("9 6 0") #3
print find_missing("1 2 3") #None
print find_missing("-3 1 3 5") #-1
Well... You can do simpler, but it would completely change your algorithm.
First, you can prove that the step for the arithmetic progression is ap[1] - ap[0], unless ap[2] - ap[1] is lower in magnitude than it, in which case the missing element is between terms 0 and 1. (This is true as there is a single missing element.)
Then you can just take ap[0] + n * step and print the first one that doesn't match.
Here is the source code (also implementing some minor shortcuts, such as grouping your first three lines into one):
def find_missing_elm_ap_series(n, series):
ap = [int(i) for i in series.split(' ')]
step = ap[1] - ap[0]
if (abs(ap[2] - ap[1]) <= abs(step)): # Check missing elt is not between 0 and 1
return ap[0] + ap[2] - ap[1]
for (i, val) in zip(range(len(ap)), ap): # And check position of missing element
if ap[0] + i * step != val:
return ap[0] + i * step
return series # missing element not found
The code appears to be working. There is perhaps a slightly easier way to get it done. This is due to the fact that you don't have to attempt to look through all of the values to get the common difference. The following code simply looks at the difference between the 1st and 2nd as well as the last and second last.
This works in the event that only a single value is missing (and the length of the list is at least 3). As the min difference between the values will provide you the common difference.
def find_missing(prog):
# First we cast them to numbers.
items = [int(x) for x in prog.split()]
#Then we compare the first and second
first_to_second = items[1] - items[0]
#then we compare the last to second last
last_to_second_last = items[-1] - items[-2]
#Now we have to care about which one is closes
# to zero
if abs(first_to_second) < abs(last_to_second_last):
change = first_to_second
else:
change = last_to_second_last
#Iterate through the list. As soon as we find a gap
#that is larger than change, we fill in and return
for i in range(1, len(items)):
comp = items[i] - items[i-1]
if comp != change:
return items[i-1] + change
#There was no gap
return None
print(find_missing("1 3 5 9")) #7
print(find_missing("-1 1 3 5 9")) #7
print(find_missing("9 6 0")) #3
print(find_missing("1 2 3")) #None
The previous code shows this example. First of all attempting to find change between each of the values of the list. Then iterating till the change is missed, and returning the value that has been expected.
Here's the way I thought about it: find the position of the maximum difference between the elements of the array; then regenerate the expected number in the sequence from the other differences (which should be all the same and the minimum number in the differences list):
def find_missing(a):
d = [a[i+1] - a[i] for i in range(len(a)-1)]
i = d.index(max(d))
x = min(d)
return a[0] + (i+1)*x
print find_missing([1,3,5,9,11])
7
print find_missing([1,5,7,9,11])
3
Here are some ideas:
Passing the length of the series seems like a bad idea. The function can more easily calculate the length
There is no reason to assign series to ap, just do a function using series and assign the result to ap
When splitting the string, don't give the sep argument. If you don't give the argument, then consecutive white space will also be removed and leading and trailing white space will also be ignored. This is more friendly on the format of the data.
I've combined a few operations. For example the split and the list comprehension converting to integer make sense to group together. There is also no need to create cd as a list and then convert that to a set. Just build it as a set to start with.
I don't like that the function returns the original series in the case of no missing element. The value None would be more in keeping with the name of the function.
Your original function returned a one item set as the result. That seems odd, so I've used pop() to extract that item and return just the missing element.
The last item was more of an experiment with combining all of the code at the bottom into a single statement. Don't know if it is better, but it's something to think about. I built a set with all the correct numbers and a set with the given numbers and then subtracted them and returned the number that was missing.
Here's the code that I came up with:
def find_missing_elm_ap_series(series):
ap = [int(i) for i in series.split()]
n = len(ap)
cd = {ap[i+1]-ap[i] for i in range(n-1)}
if len(cd) == 1:
print 'The series is complete'
return None
else:
common_diff = min([abs(i) for i in cd])
if ap[0] > ap[1]:
common_diff = (-1)*common_diff
return set(range(ap[0],ap[0]+common_diff*n,common_diff)).difference(set(ap)).pop()
Assuming the first & last items are not missing, we can also make use of range() or xrange() with the step of the common difference, getting rid of the n altogether, it can also return more than 1 missing item (although not reliably depending on number of items missing):
In [13]: def find_missing_elm(series):
ap = map(int, series.split())
cd = map(lambda x: x[1]-x[0], zip(ap[:-1], ap[1:]))
if len(set(cd)) == 1:
print 'complete series'
return ap
mcd = min(cd) if ap[0] < ap[1] else max(cd)
sap = set(ap)
return filter(lambda x: x not in sap, xrange(ap[0], ap[-1], mcd))
....:
In [14]: find_missing_elm('1 3 5 9 11 15')
Out[14]: [7, 13]
In [15]: find_missing_elm('15 11 9 5 3 1')
Out[15]: [13, 7]

Define a function using a variable?

I am trying to define a function that will include a variable n where n will be a string of numbers e.g. "3884892993", the definition of the function starts as is_true(n), however if n is going to be a string should it be is_true(n) and then once the string is defined I can test the function with an example string such as n = "3884892993". I get a syntax error when I use is_true(n) however. And I am just wondering how I would go about testing this function with an example string for n.
My entire function to define is shown here: http://oi44.tinypic.com/282i3qo.jpg but bear in mind I am an absolute novice so there will most probably be many mistakes, but I would appreciate some help from some experts if at all possible :)
def is_valid("n"): #n is the number to be checked.
number =
[int(y) for y in A] #converts the string into a list of useable digits.
altern1 = integer[-2::-2] #sets altern1 as one set of alternating digits.
double = [x*2 for x in altern1] #doubles each element of the list altern1.
sum1 = sum(double) # adds together all the doubled items of the list.
altern2 = integer[-1::-2] #sets altern2 as the other set of alternating digits.
return sum2 = sum(altern2)#sums the other set of alternating digits.
sumtotal = sum1 + sum2 #works out the total sum to be worked with.
for mod = sumtotal % 10: #works out remainder when sumtotal is divided by 10
if mod == 0 : #if remainder is zero sumtotal is a multiple of 10
print 'True' #sumtotal is a multiple of 10 therefore n is a credit card number
else:
print 'False' #sumtotal is NOT a multiple of 10 therefore not a valid credit card number
Here is the actual question:
The algorithm for verifying a number is as follows:
(a) Starting with the penultimate digit, and working towards the rst digit, double each alternating digit.
(b) Sum the doubled digits, treating 13 as 1+3, etc, and add the result to the sum of the undoubled
digits
(c) If the sum is divisible by 10 the number is a valid credit card number.
Write and test a function is_valid() which takes as an argument a credit card number as a string
(eg is valid("49927398716")) and returns True or False depending on whether the number is a
valid credit card number.
Quotes are only used for string literals, you wouldn't enclose a variable or parameter name in quotes to indicate that it will be a string. The function definition would look like:
def is_true(n):
And then in the body of the function you use n to reference the value that is passed in by the caller.
To call the function on a specific value, you do:
is_true("3884892993")
Side suggestion: Think of more explanatory names for your functions and variables. For instance, it seems like your function might be reasonably called is_valid_card_number.
I am not sure what is your question, but if you are trying to:
correctly define the function:
pay attention to the indentation (this is required by Python!),
see here for examples of function definitions,
convert a string variable into integer, you can do this:
new_var = int(old_var)
Generally please pay attention to types, because it is not like in some other dynamically typed languages and strings are not dynamically converted into numbers - you should do it explicitly.
read the value of the variable, based on its name:
my_var = vars().get('variable_name')
(where variable_name is the name of the variable and optionally you can give context within brackets after vars - see help(vars) for details)
Did any of the above solve your problem?
EDIT (based on the clarification):
This should solve your problem:
def is_true(my_variable):
# Here the variable named "my_variable" is accessible
If you want to do something "in-place" on the passed variable, I have a bad news: strings and integers are immutable in Python, thus you are not able to simply change them - you should probably return them as a result of the function (there are at least two workarounds, but I do not recommend them if you are a novice in Python).
EDIT (for proper code styling):
You should probably read PEP 8 to get familiar with what is the coding standard for Python scripts - this is commonly used across Python community and you should follow that (at some point you should appreciate it).
From the Wikipedia article on the Luhn algorithm:
def is_luhn_valid(cc):
num = map(int, str(cc))
return sum(num[::-2] + [sum(divmod(d * 2, 10)) for d in num[-2::-2]]) % 10 == 0
I have no idea what your function is supposed to do, but here are some remarks.
First of all, if you define the function then you use the following syntax
def is_true(n):
# do something
you can call this function like this is_true("3884892993"), i.e. you can pass string as n. Your function now need to treat variable n as a string. So you can use
number = [int(d) for d in n]
which will result in converting string into a list of digits.
One more remark: you used a return statement inside your is_true function. This statement will stop executing the function and return the value. Every code below return will never be executed.
May be like this. I leave your comments
def is_valid(n): #n is the number to be checked.
numbers = [int(y) for y in n] #converts the string into a list of useable digits.
double_alt = [sum([int(i) for i in str(x*2)]) for x in numbers[-2::-2]] #doubles and sum if more than 10each element of the list altern1.
sum1 = sum(double_alt) # adds together all the doubled items of the list.
sum2 = sum(numbers[-1::-2]) #sums the other set of alternating digits.
sumtotal = sum1 + sum2 #works out the total sum to be worked with.
return not sumtotal % 10
Here an implementation of the luhn algorithm that I had to make recently.
def is_valid_luhn(cc):
return not sum([sum(divmod(int(d) * 2, 10)) for d in cc[-2::-2]] + [int(d) for d in cc[-1::-2]]) % 10
# | double | |--- every -2th --| |--- every -1th --|
# |--------- step 1 -----------------|
# |------------- sum doubled digits --------------| |-- sum undoubled digits --|
# |---------------------- step 2: sum doubled/undoubled digits -----------------------|
# |-------------------------- step 3: sum % 10 == 0 --> not sum % 10 --------------------------|
Or if you'd like a more verbose version:
def is_valid_luhn(cc):
total = 0
# Double and sum every 2nd digit starting at -2.
for d in cc[-2::-2]:
# divmod(d*2, 10) returns (d*2 // 10, d*2 % 10)
# sum(divmod) return (d*2 // 10) + (d*2 % 10)
total += sum(divmod(int(d) * 2, 10))
# Sum every 2nd digit starting at -1.
for d in cc[-1::-2]:
total += int(d)
# Check module 10 of total: total % 10 == 0 --> not total % 10
return not total % 10

How to check last digit of number

Is there a way to get the last digit of a number. I am trying to find variables that end with "1" like 1,11,21,31,41,etc..
If I use a text variable I can simply put
print number[:-1]
but it works for variables with text(like "hello) but not with numbers. With numbers I get this error:
TypeError: 'int' object is not subscriptable
I am trying to see if there's a better way to deal with numbers this way. I know a solution is to convert to a string and then do the above command but I'm trying to see if there's another way I have missed.
Thanks so much in advance...
Remainder when dividing by 10, as in
numericVariable % 10
This only works for positive numbers. -12%10 yields 8
Use the modulus operator with 10:
num = 11
if num % 10 == 1:
print 'Whee!'
This gives the remainder when dividing by 10, which will always be the last digit (when the number is positive).
So you want to access the digits in a integer like elements in a list; easiest way I can think of is:
n = 56789
lastdigit = int(repr(n)[-1])
# > 9
Convert n into a string, accessing last element then use int constructor to convert back into integer.
For a Floating point number:
n = 179.123
fstr = repr(n)
signif_digits, fract_digits = fstr.split('.')
# > ['179', '123']
signif_lastdigit = int(signif_digits[-1])
# > 9
I can't add a comment yet, but I wanted to iterate and expand on what Jim Garrison said
Remainder when dividing by 10, as in
numericVariable % 10
This only works for positive numbers. -12%10 yields 8
While modulus (%) is working as intended, throw on an absolute value to use the modulus in this situation.
abs(numericVariable) % 10
Lostsoul, this should work:
number = int(10)
#The variable number can also be a float or double, and I think it should still work.
lastDigit = int(repr(number)[-1])
#This gives the last digit of the variable "number."
if lastDigit == 1 :
print("The number ends in 1!")
Instead of the print statement at the end, you can add code to do what you need to with numbers ending in 1.
Hope it helped!
Convert to string first:
oldint = 10101
newint = int(str(oldint)[-1:])
The simplest and most efficient way is to use the reminder :
last_digit = orginal_number % 10
This is a simple yet effective way to do it
if number < 0:
remainder = number % -10
else:
remainder = number % 10
By using iteration and the in built function of 'digit' the number is treated as binary and so it goes from backwards to forwards. Here is an example of a bit of code for you.
for digit in binary:
denary= denary*2 + int(digit)
Try this efficient one-liner code to call the last digit of any integer.
The logic is first to convert the given value to a string and then convert it into the list to call the last digit by calling the -1 index. After that, convert it into an integer to wrap it up.
val is a variable that represents any integer.
int(list(str(val))[-1])
Example:
val = 23442
int(list(str(val))[-1])`
Output: 2

Categories

Resources