(Week 5)Python编程:从入门到实践(习题10-1至10-13选做)

10-2 C语言学习笔记

可使用方法replace() 将字符串中的特定单词都替换为另一个单词. 读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称, 如C. 将修改后的各行都打印到屏幕上.

with open('learning_python.txt', 'r') as f:
    lines = f.readlines()
    print(lines)
    for i in range(len(lines)):
        lines[i] = lines[i].replace('python', 'C')
    print(lines)
['in python, you can AA\n', 'in python, you can BB\n', 'in python, you can CC']
['in C, you can AA\n', 'in C, you can BB\n', 'in C, you can CC']
>>> 

10-3 访客 

编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。 

name = input("input your name: ")
with open('guest.txt', 'w') as f:
    f.write(name)
input your name: marc levy
>>> 
guest.txt
marc levy

10-6 加法运算 

提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引 发TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,并打印一 条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。

while(1):
    try:
        a = int(input("input first number: "))
        b = int(input("input second number: "))
        print(a + b)
    except ValueError:
        print('it\'s not number')
input first number: 2
input second number: 4
6
input first number: 2
input second number: dsa
it's not number
input first number: dsa
it's not number
input first number: 

10-11 喜欢的数字 

编写一个程序,提示用户输入他喜欢的数字,并使用json.dump() 将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印 消息“I know your favorite number! It's _____.”。

import json
while(1):
    try:
        a = int(input("input your number: "))
        with open('fav_num.json', 'w') as f:
            json.dump(str(a),f)
    except ValueError:
        print('it\'s not number')
    else: break
import json
with open('fav_num.json', 'r') as f:
    num = json.load(f)
    print('I know your favorite number! It\'s ' + num)
input your number: 4
>>> 
I know your favorite number! It's 4
>>> 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值