0

So I have a program that takes one argument, an integer num. It is supposed to return a number that repeats the digits of num 3 times. If the argument is not an integer, the function should return None.

For example:

For input argument "hello!", it should return None, because the input argument is a string.

For input argument "23", it should return None, because the input argument is a string. .

For input argument 12.34, it should return None, because the input argument is a float. .

For input argument 1, it should return 111 or argument 241, it should return 241241241.

I don't know what I'm doing wrong in mine, any help would be appreciated!

def repeat_number(num):
    if num is type(str) and type(float):
        return None
    else:
        return str(num) * 3
Dom
  • 75
  • 1
  • 7

3 Answers3

3

You're close. There are two different problems here.

First, you really shouldn't have to type check (duck typing), but if you must, do it right:

if not isinstance(num, int):
  return None

This returns None if the argument isn't an integer. As for actually repeating the number, you just need to turn the string back into a number:

return int(str(num) * 3)

Full code:

def repeat_number(num):
  if not isinstance(num, int):
    return None
  else:
    return int(str(num) * 3)
Linuxios
  • 34,849
  • 13
  • 91
  • 116
1

To check the type of a variable, you should use isinstance

def repeat_number(num):
    if isinstance(num, int):
        return int(str(num) * 3)
    else:
        return None

>>> repeat_number(241)
241241241
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

Try this syntax

if type(num) is int or type(num) is float:
    return None
else:
    return str(num) * 3
calmond
  • 189
  • 7