10-3 访客 :编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。
代码如下:
with open('guest.txt' ,'w' ) as fobj:
name = input('Please input your name:' )
fobj.write(name)
执行过程
Please input your name :Jack
guest.txt内容如下:
Jack
10-4 访客名单 :编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。
代码如下
with open('guest_book.txt' ,'w' ) as fobj:
while (1 ):
name = input('Please input your name:' )
if (name=='quit' ):
break
print('How are you, ' + name)
fobj.write(name+'\n' )
执行过程
Please input your name :Jack
How are you , Jack
Please input your name :John
How are you , John
Please input your name :Jullie
How are you , Jullie
Please input your name :Jenifer
How are you , Jenifer
Please input your name :Alice
How are you , Alice
Please input your name :Rose
How are you , Rose
Please input your name :quit
guest_book.txt内容如下:
Jack
John
Jullie
Jenifer
Alice
Rose
10-6 加法运算 :提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发ValueError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获ValueError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
代码如下:
try :
a = input('Please input oprand a:' )
b = input('Please input oprand b:' )
a = int(a)
b = int(b)
except ValueError:
print('Your input is not numerical! Please input again.' )
else :
print('a+b=' ,str(a+b))
执行过程与结果如下:
1.
Please input oprand a :1
Please input oprand b:2
a +b= 3
2.
Please input oprand a :a
Please input oprand b:b
Your input is not numerical! Please input again.
10-7 加法计算器 :将你为完成练习10-6而编写的代码放在一个while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。
代码如下:
执行过程与结果如下:
Please input oprand a :1
Please input oprand b:2
a +b= 3
Please input oprand a :a
Please input oprand b:c
Your input is not numerical! Please input again.
Please input oprand a :sda
Please input oprand b:erq
Your input is not numerical! Please input again.
Please input oprand a :2
Please input oprand b:6
a +b= 8
Please input oprand a :1
Please input oprand b:9
a +b= 10
10-11 喜欢的数字 :编写一个程序,提示用户输入他喜欢的数字,并使用json.dump() 将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favorite number! It’s _ .”。
写JSON的代码如下:
import json
fav_num = input("Your favorite number is:" )
with open('fav_num.json' ,'w' ) as fobj:
json.dump(fav_num,fobj)
写后的json文件内容如下:
"6"
读JSON的代码如下:
import json
with open('fav_num.json' ) as fobj:
fav_num = json.load(fobj)
print('My favorite number is:' + str(fav_num))
读JSON的代码运行结果如下:
My favorite number is :6