Learn Python the Hard Way 14 Prompting and Passing
Published in
5 min readSep 3, 2019
將 argv 和 input 結合
這次要來把 argv 跟 input 結合在一起,可以拿來問使用者比較具體的問題,這次我們也會在 input 加個小提示 “ > “,來提醒使用者。
from sys import argvscript, user_name = argv
prompt = '> 'print(f"Hi {user_name}, I'm the {script} script.")
print("I's like to ask you a few questions")
print(f"Do you like me {user_name}?")
likes = input(prompt)print(f"Where do you live {user_name}?")
lives = input(prompt)print("What kind of computer do you have?")
computer = input(prompt)print(f"""
Alright, so you said {likes} about liking me.
You live in {lives}. Not sure where that is.
And you have a {computer} computer. Nice.
""")
接著在 Terminal 輸入:
python ex14.py Chenyu
output:
Hi Chenyu, I'm the ex14.py script.
I'm like to ask you a few questions.
Do you like me Chenyu?
> Yes
Where do you live Chenyu?
> Taipei
What kind of computer do you have?
> MacAlright, so you said Yes about liking me.
You live in Taipei. Not sure where that is.
And you have a Mac computer. Nice.
我們也可以把變數 prompt 改一下,程式看起來兇一點!
from sys import argvscript, user_name = argv
prompt = 'Huh? 'print(f"Hi {user_name}, I'm the {script} script.")
print("I's like to ask you a few questions")
print(f"Do you like me {user_name}?")
likes = input(prompt)print(f"Where do you live {user_name}?")
lives = input(prompt)print("What kind of computer do you have?")
computer = input(prompt)print(f"""
Alright, so you said {likes} about liking me.
You live in {lives}. Not sure where that is.
And you have a {computer} computer. Nice.
""")
output:
Hi Chenyu, I'm the ex14.py script.
I'm like to ask you a few questions.
Do you like me Chenyu?
Huh? No...
Where do you live Chenyu?
Huh? Secret
What kind of computer do you have?
Huh? I don't know...Alright, so you said No... about liking me.
You live in Secret. Not sure where that is.
And you have a I don't know... computer. Nice.
這系列文章的練習,都是來自於 Learn Python the Hard Way 這本書中,內容只針對練習做紀錄和自己的心得分享,為保護著作權故沒有透露太多內容,能力可及的話還是鼓勵大家買一本來自行練習,有問題都可以在下方進行討論。
Learn Python the Hard Way 系列文章
- LPTHW 01 First Program
- LPTHW 02 Comments & Pound Characters
- LPTHW 03 Numbers & Math
- LPTHW 04 Variables &Names
- LPTHW 05 More Variables & Printing
- LPTHW 06 Strings and text
- LPTHW 07 More Printing
- LPTHW 08 Printing, Printing
- LPTHW 09 Printing, Printing, Printing
- LPTHW 10 What Was That ?
- LPTHW 11 Ask Questions
- LPTHW 12 Prompting People
- LPTHW 13 Parameters, Unpacking, Variables
- LPTHW 14 Prompting & Passing