10-2
withopen('learning_python.txt') as file:
for line in file:
print(line.replace("python","C").rstrip())
output:
In C you can use varible,list,dictoinary andstruct
In C you can use if and while
In C you can use input and fuction
10-4
filename = 'guest_book.txt'
n = 0
withopen(filename,'w') as file:
while n <3 :
visitor = input('please inputyour name:')
print("hello,"+visitor+"!")
file.write(visitor+'\n')
n+=1
output:
please input your name:lin
hello,lin!
please input your name:dong
hello,dong!
please input your name:sheng
hello,sheng!
10-5
filename = 'reasons.txt'
n = 0
while n <3 :
reason = input('please inputyour reason for loving progreaming:')
print("get!")
withopen(filename,'a') as file:
file.write(reason+'\n')
n+=1
output:
please input your reason for lovingprogreaming:funny
get!
please input your reason for lovingprogreaming:useful
get!
please input your reason for lovingprogreaming:interesting
get!
10-7
whileTrue :
num_ = input("pleaseinput the first number(input q to exit): ")
if num_ == 'q':
break
else:
try:
num1= int(num_)
except ValueError:
print("Youhaven't input a number!")
else:
num_= input("please input the second number(input q to exit): ")
if num_ == 'q':
break
else:
try:
num2 = int(num_)
except ValueError:
print("You haven't input a number!")
else:
print("the sum of them is "+str(num1+num2))
output:
please input the first number(input q toexit): 1
please input the second number(input q toexit): 1
the sum of them is 2
please input the first number(input q toexit): a
You haven't input a number!
please input the first number(input q toexit): 1
please input the second number(input q toexit): b
You haven't input a number!
please input the first number(input q toexit): q
10-8
filenames = ["cats.txt","dogs.txt"]
for filename in filenames:
try:
withopen(filename) as file:
for line in file:
print(line.rstrip())
except FileNotFoundError:
print("Sorry, thefile '"+filename+"' does notexist.")
output:
cat_a
cat_b
cat_c
Sorry, the file 'dogs.txt' does not exist.
10-12
import json
whileTrue:
try:
withopen("fav_num.json") as file:
print("I knowyour favourite number? It's "+file.read().rstrip()+".")
except FileNotFoundError:
fav_num = input("What isyour favourite number?")
withopen("fav_num.json","w") as file:
json.dump(fav_num,file)
else:
break
output:
What is your favourite number?666
I know your favourite number? It's"666".