笨辦法學Python - 習題11-12
- 2020 年 2 月 10 日
- 筆記
目錄
1、習題 11: 提問
學習目標:了解人機交互場景,熟悉raw_input 的用法。
1、在 Python2.x 中 raw_input( ) 和 input( ),兩個函數都存在,具體區別詳情請參考習題5,其中區別為:
- raw_input( ) 將所有輸入作為字元串看待,返回字元串類型。
- input( ) 只能接收「數字」的輸入,在對待純數字輸入時具有自己的特性,它返回所輸入的數字的類型( int, float )。
2、在 Python3.x 中 raw_input( )和 input( ) 進行了整合,去除了 raw_input( ),僅保留了 input( ) 函數,其接收任意任性輸入,將所有輸入默認為字元串處理,並返回字元串類型。
習題十一中的練習程式碼是:
#! -*-coding=utf-8-*- print("How old are you?"), age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight)C:Python27python.exe D:/pythoncode/stupid_way_study/demo11/Exer11-1.py How old are you? 14 How tall are you? 34 How much do you weigh? 123 So, you're '14' old, '34' tall and '123' heavy. Process finished with exit code 0
上述程式碼有一個問題,就是每一個print 一句後面都有一個逗號,這是因為這樣的話print 就不會輸出新行符而結束這一行跑到下一行去了,具體詳情用法請參考習題7。
2、習題 12: 提示別人
學習目標:繼續學習raw_input 的用法,了解怎麼添加提示資訊。
習題十二中的練習程式碼是:
age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weigh? ") print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)上述程式碼的運行結果為:
C:Python27python.exe D:/pythoncode/stupid_way_study/demo11/Exer11-1.py How old are you? 23 How tall are you? 45 How much do you weigh? 123 So, you're '23' old, '45' tall and '123' heavy. Process finished with exit code 0
了解一下pydoc的用法:
D:pythoncodestupid_way_studydemo11>python -m pydoc Exer11-1 How old are you? 12 How tall are you? 23 How much do you weigh? 123 So, you're '12' old, '23' tall and '123' heavy. Help on module Exer11-1: # 展示該文件具體內容 NAME Exer11-1 FILE d:pythoncodestupid_way_studydemo11exer11-1.py DESCRIPTION # print("How old are you?"), # age = raw_input() # # print "How tall are you?", # height = raw_input() # # print "How much do you weigh?", # weight = raw_input() # # print "So, you're %r old, %r tall and %r heavy." % ( # age, height, weight) DATA age = '12' height = '23' weight = '123'pydoc是python自帶的一個文檔生成工具,使用pydoc可以很方便的查看類和方法結構
同時我們可以在本地開啟埠,然後在瀏覽器端看源程式碼解釋:
本地窗口使用命令python3 -m pydoc -p 1234 開啟:

瀏覽器端可直接訪問開放的埠:http://localhost:1234/

當然還可以在命令行下直接查看某一模組的源程式碼:
使用命令:python3 -m pydoc os

3、總結
這兩題主要是學習了和電腦交互的函數raw_input() ,注意由於Python2中input() 自身的原因會導致一些問題,所以一般在Python2中只使用input(),然後學習了解pydoc的用法。
