1

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

?

4
  • for all in str(a2): print(all) Commented Nov 23, 2020 at 23:08
  • int objects aren't iterable, so convert it into some appropriate iterable object, e.g. a str Commented Nov 23, 2020 at 23:09
  • The reason why your code fails when you try to iterate through an integer is because integers are unique numbers. Python sees 100, not 1 and 0 and 0. Whereas strings are sequences of characters. Commented Nov 23, 2020 at 23:18
  • @DarknessPlusPlus: nice explanation! Thank you Commented Nov 25, 2020 at 7:28

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

An object of type int is not iterable. So force it to be iterable by making it a string.

x = 1337
for num in str(x):
  print(num)

Comments

0

To get letters of a word or elements of a number by a for loop you need a string

a = 100 is an integer so you need to convert it to a string like below :


a=str(100)
for i in a:
    print(i)


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.