如何让python不打印东西

时间:2014-01-24 16:33:35

标签: python function

我正在尝试编写代码,该代码会将值打印到代表指示的特定时间。

离。

def bla(value, rep):
   value*rep
bla('x', 2) # output: xx

我不知道该怎么做的部分是函数应该确保给出的参数是有效的。

如果rep值不是整数,我希望rep值不运行。 例如:

def bla(value, rep):
   print (value*rep)
bla ('a', hello)

“抱歉'你好'不是一个有效的参数”

3 个答案:

答案 0 :(得分:5)

def bla(value, rep):
    try:
        print value*rep
    except TypeError:
        print "sorry '%s' is not a valid parameter" % rep

请参阅"Ask forgiveness not permission" - explain

答案 1 :(得分:0)

def bla(value, rep):
    if isinstance(value, int ):
        print(value*rep)
    else:
        print("sorry '" + rep "' is not a valid parameter")

答案 2 :(得分:-1)

对于Python中的类型检查,您可以使用type()函数http://docs.python.org/2/library/functions.html#type ig:

>>> a = 2
>>> type(a) is int
True
>>> type(a) is str
False
>>> a = '2'
>>> type(a) is str
True
>>> type(a) is int
False

你可以这样使用它:

def bla(value, rep):
   if type(rep) is int:
       print (value*rep)
   else: 
       print ("Bad parameter type")