Python3中的输入输出

input()函数

我们可以通过Python3解释器查看Python3中input()的含义:

>>> type(input)
<class 'builtin_function_or_method'>
>>> help(input)


Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
(END)

即:打印提示字符串(如果给定)到标准输出,并从标准输入中读取字符串,尾部换行符被剥离。如果用户输入EOF,会触发EOFError。

请注意,Python3中input()一次读取一行,并当作字符串,与Python2中的raw_input()相同。例如:

>>> a = input()
a b c d
>>> a
'a b c d'
>>> a = input()
3.1425926
>>> a
'3.1425926'

三种示例

在OJ上做题比较常见。

'''
Python的输入是野生字符串,所以要自己转类型
strip去掉左右两端的空白符,返回str
slipt把字符串按空白符拆开,返回[str]
map把list里面的值映射到指定类型,返回[type]'''

#多组测试数据,没告诉具体组数,处理到文件结束。
while True:
    try:
        a, b = map(int, input().strip().split())
        print(a + b)
    except EOFError:
        break


#输入一个整数告诉你接下来有多少组,接着输入每组数据
T = int(input().strip())
for case in range(T):
    a, b = map(int, input().strip().split())
    print(a + b)


#多组测试数据,没告诉具体组数,但满足一定条件结束
while True:
    a, b = map(int, input().strip().split())
    if a == 0 and b == 0:
        break
    print(a + b)

有兴趣可以去这里提交一下:https://vjudge.net/problem/HRBUST-1883

参考链接:

1、https://blog.csdn.net/luovilonia/article/details/40860323

2、https://blog.csdn.net/lt17307402811/article/details/77184179

3、https://blog.csdn.net/desporado/article/details/81409573

猜你喜欢

转载自www.cnblogs.com/lfri/p/10373431.html