Erwy Lionel
Erwy Lionel

Reputation: 71

Repeat a number 3 times for output

I need to define a function which repeats a number 3 times. I can only get it to work as a list where the output is [1, 1, 1] if the input is 1. However I need the output to be 111 This is what I have

def repeat_number(num):
    if not type(num) is int:
        return None

    list_1 = []
    x = list_1.append(num)
    y = list_1*3

    for i in y:

    return i,i,i

a = 12

print (repeat_number(a))

and again I want the output to be 121212

Upvotes: 0

Views: 2213

Answers (5)

Ajay
Ajay

Reputation: 5347

def repeat_num(x):
    return str(x)*3

Upvotes: 0

M. Adam Kendall
M. Adam Kendall

Reputation: 1282

You can cast the number as a string and multiply.

def repeat(num):
    return str(num)*3

a = 12
print(repeat(a))

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49318

If the output is [1, 1, 1] and you were looking for 111, you can do the following:

print (*repeat_number(a), sep='')

However, I'd recommend doing the following with your function:

def repeat_number(num):
    if type(num) != int: return
    return int(str(num)*3)

And then all you have to do is:

print (repeat_number(a))

as you originally attempted. Plus, this function returns an actual number, which is probably good.

Upvotes: 0

Reut Sharabani
Reut Sharabani

Reputation: 31339

You can use a simple str.join for this, and create a general function:

def repeat(something, times, separator):
    return separator.join([str(something) for _ in range(times)])

And now use it to create your specific function:

def repeat_three_times(something):
    return repeat(something, 3, '')

Output:

>>> repeat_three_times(1)
'111'

Few things to note:

  1. I've used str to cast the expected integer to a string
  2. I've used a list comprehension to create an iterable which is what str.join expects
  3. I've used str.join to create a string which is a concatenation of the strings in the list (see 2).

Here is an example of using the more general function in a different way:

>>> repeat(1, 4, ',')
'1,1,1,1'

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113950

def repeat_number3(a):
    return str(a)*3

Upvotes: 1

Related Questions