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())
   nums = [int(i) for i in input().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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM