Write a program that prints integers from 1 to 100 (inclusive) in one line of code, however

I am new to python and would like to write a program that prints integers from 1 to 100 (inclusive) on 1 line using python, however:

  • For multiples of three, type shell

    (instead of number)
  • For multiples of five, type fish

    (instead of number)
  • For multiples of both three and five, type shellfish

    (instead of number)

I can do this, but not in one line of code, unfortunately:

 for i in xrange(1, 101):
    if i % 15 == 0:
        print "shellfish"
    elif i % 3 == 0:
        print "shell"
    elif i % 5 == 0:
        print "fish"
    else:
        print i

      

How do I make this source code in one line?

+3


source to share


2 answers


To convert your attempt to 1 line, you can use *

, which is the repeat operator in python:



for i in xrange(1,101): print("shell"*(i%3==0) + "fish"*(i%5==0) or i)

      

+3


source


With a conditional: true_value if cond else false_value

we get this - a bit boring solution:



for i in xrange(1, 101): print (i if i % 5 else "fish") if i % 3 else ("shell" if i % 5 else "shellfish")

      

+1


source







All Articles