-2

I'm trying to write a function that takes two integers x and y. And it should return a string containing the integer x repeated y times.

My code:

def repeat_int_str(x, y):
    int = "x" * y
    return int

What the result is supposed to look like:

assert(repeat_int_str(0, 4) == "0000")
assert(repeat_int_str(-5, 3) == "-5-5-5")
  • What did you do to trace the problem? For instance, what is that *actual* value of `"x"`? That's where you made your error. – Prune Sep 10 '20 at 17:33
  • [Converting integer to string](https://stackoverflow.com/questions/961632/converting-integer-to-string-in-python) – Wups Sep 10 '20 at 17:39

2 Answers2

3

This code is close to being workable, few insights:

  1. Use str() to convert int to string
  2. Then, as you discovered, multiplying string by int would make it duplicate as a repeating string
  3. Don't use int as a name for a variable (it's a builtin class for integer numbers)
def repeat_int_str(x, y):
    val = str(x) * y
    return val

# All the following pass
assert repeat_int_str(0, 4)  == "0000"
assert repeat_int_str(-5, 3) == "-5-5-5"
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
  • 2
    just a small correction: `int` is **not** a reserved keyword. The fact that it *can* be used as a variable name shows that it is not a reserved keyword (compare with what happens when you try to use `class`, `def`, `if` etc as a variable name). `int` is merely a built-in `class` – DeepSpace Sep 10 '20 at 17:33
1

what you forget to do is turn x to a string. 'x' won't do, this just gives you the letter x as a string.

try the function str(x). like that:

def repeat_int_str(x, y):
    int = str(x) * y
    return int
Nadavo
  • 250
  • 2
  • 9