In Python, how do I print integer one below the other:
a1 = "Great"
a2 = 100
for all in a1:
print(all)
Output:
G
r
e
a
t
Question: How do I write for/print statement for the variable a2, so that my output will be:
1
0
0
?
You need to convert a2, an int into something that is iterable. One way you could do this is by converting a2 into a string:
a2 = 100
for str_digit in str(a2): # if a2 is negative use str(a2)[1:] to not print '-' sign
print(str_digit)
And another way could be by extracting the individual digits (still as ints) from a2 into a list (or another iterable):
def get_digits(num):
num = abs(num)
digits = []
while num != 0:
digits.append(num % 10)
num //= 10
return digits
a2 = 100
for str_digit in get_digits(a2):
print(str_digit)
Output:
1
0
0
for all in str(a2): print(all)intobjects aren't iterable, so convert it into some appropriate iterable object, e.g. astr