题目
通过 input
和 argv
配合实现一个简单的互动程序。
加分练习
- 了解 Zork 和 Adventure 是怎样的游戏。
- 将
prompt
变量改成完全不同的内容运行一遍。 - 给你的脚本添加一个参数,让你的程序用到这个参数。
- 确认你弄懂了三引号
"""
可以定义多行字符串,而%
是字符串格式化工具。
我的答案
基础练习答案
from sys import argv
script, user_name = argv
prompt = '> '
print("Hi %s, I'm the %s script." % (user_name, script))
print("I'd like to ask you a few questions.")
print("Do you like me %s?" % user_name)
likes = input(prompt)
print("Where do you live %s?" % user_name)
lives = input(prompt)
print("What kind of computer do you have?")
computer = input(prompt)
print("""
Alright, so you said %r about liking me.
you live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer))
运行一下
14.2 其他 prompt
from sys import argv
script, user_name = argv
prompt = '%s > ' % user_name # 改成这样试试
print("Hi %s, I'm the %s script." % (user_name, script))
print("I'd like to ask you a few questions.")
print("Do you like me %s?" % user_name)
likes = input(prompt)
print("Where do you live %s?" % user_name)
lives = input(prompt)
print("What kind of computer do you have?")
computer = input(prompt)
print("""
Alright, so you said %r about liking me.
you live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer))
14.3 加一个参数
from sys import argv
script, user_name, call = argv # 加一个 call
prompt = '%s > ' % user_name # 改成这样试试
print("Hi %s, I'm the %s script." % (user_name, script))
print("Hmmm, you want me call you %s" % call) # call 在这里
print("I'd like to ask you a few questions.")
print("Do you like me %s?" % user_name)
likes = input(call + " " + prompt)
print("Where do you live %s?" % user_name)
lives = input(call + " " + prompt)
print("What kind of computer do you have?")
computer = input(call + " " + prompt)
print("""
Alright, so you said %r about liking me.
you live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer))