用Notepad++打下列的程式碼,
另存為ex11.py.
print ("How old are you?", end = " ") age = input () print ("How tall are you?", end = " ") height = input () print ("How much do you weigh?", end = " ") weigh = input () print (f"So, you're {age} old, {height} tall and {weigh} heavy.")
然後用Windows的cmd, 執行python打開它.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW C:\Users\Peter\Desktop\Python\LP3THW>python .\ex11.py How old are you? 111 How tall are you? 222 How much do you weigh? 333 So, you're 111 old, 222 tall and 333 heavy. C:\Users\Peter\Desktop\Python\LP3THW>
完成
這次練習主要是學習對字符串做更多複雜的格式化.
我們來修改一下程式碼.
Line 2 - 3, int是轉換成整數,並打印出該數據類型(應為整數).
Line 5 - 6, float是轉換成浮點數,並打印出該數據類型(應為浮點數).
Line 8 - 9, str是轉換成字串,並打印出該數據類型(應為字串).
Line 12, 用另外一個方法表示出相同的格式化結果.
print ("How old are you?", end = " ") age = int(input ()) print (type (age)) print ("How tall are you?", end = " ") height = float(input ()) print (type (height)) print ("What is your name?", end = " ") name = str(input ()) print (type (name)) print ("So, you're {} old, {} tall and {} heavy.".format (age, height, name))
結果,
C:\Users\Peter\Desktop\Python\LP3THW>python .\ex11.py How old are you? 111 <class 'int'> How tall are you? 222 <class 'float'> What is your name? 333 <class 'str'> So, you're 111 old, 222.0 tall and 333 heavy. C:\Users\Peter\Desktop\Python\LP3THW>
最初發表 / 最後更新: 2018.08.12 / 2018.08.12
0 comments:
張貼留言