Python 自定义函数输出结果

2017-09-04  本文已影响142人  倔强的潇洒小姐

我们在定义函数的时候是可以指定任意个参数的,有些参数会进行默认值的设置

代码如下:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
    ok = input('请输入yes或no: ')
    if ok in ('y', 'ye', 'yes'):
        return True
    if ok in ('n', 'no', 'nop', 'nope'):
        return False
    retries = retries - 1
    if retries < 0:
        quit()
    print(prompt, reminder)

ask_ok(prompt='OK to overwrite the file?', retries=2, reminder='Come on, only yes or no!')

这里面涉及到 input 函数,它在对待纯数字输入时具有自己的特性,返回所输入的数字的类型( int, float )。

注意事项

1、input() 希望能够读取一个合法的 python 表达式

即输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError 。

SyntaxError .png
2、python3 里 input() 默认接收到的是 str 类型

(可用type输出类型)

ok = input(123)
print(type(ok))
# 结果
<class 'str'>
3、如果 input() 指定了函数中的参数名,那么想输出print()输出所有变量项,该如何做?

很多时候我们都是被眼睛看到的给欺骗了,比如我给 input函数 指定了prompt 参数,那么运行时只看到了prompt输出,函数中的其余变量并没有输出

实际上我们看到的只是input的输出,需要我们在运行终端中继续输入,print 中的参数值就会输出到页面上了

Paste_Image.png

input()的数据修改下,就更容易理解了

ok = input('请输入函数变量')
4、位置参数必须写在关键字参数之前
ask_ok(prompt = 'OK to overwrite the file?', 2)

如果调用以上参数会报错

SyntaxError: positional argument follows keyword argument
上一篇下一篇

猜你喜欢

热点阅读