Learn Python the Hard Way 14 Prompting and Passing

Chenyu Tsai
UXAI
Published in
5 min readSep 3, 2019

將 argv 和 input 結合

from here

這次要來把 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?
> Mac
Alright, 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 系列文章

  1. LPTHW 01 First Program
  2. LPTHW 02 Comments & Pound Characters
  3. LPTHW 03 Numbers & Math
  4. LPTHW 04 Variables &Names
  5. LPTHW 05 More Variables & Printing
  6. LPTHW 06 Strings and text
  7. LPTHW 07 More Printing
  8. LPTHW 08 Printing, Printing
  9. LPTHW 09 Printing, Printing, Printing
  10. LPTHW 10 What Was That ?
  11. LPTHW 11 Ask Questions
  12. LPTHW 12 Prompting People
  13. LPTHW 13 Parameters, Unpacking, Variables
  14. LPTHW 14 Prompting & Passing

--

--