程序运行后提示用户输入1,2,q中的一个字符,如果用户输入的是1,就计算2-50之间的素数,并打印到屏幕,然后继续提示用户输入1,2,q中的一个;如果用户输入的是2,屏幕提示用户输入一些文字,用户如果输入的文字不是x,就将用用户输入的文字写入hello.txt中。如果用户翰入x就停止写文件。屏幕继续提示用户输入1,2,q中的一个;如果用户输入的是q就结束。
可以使用while循环获取用户输入的字符,如果输入的是1或2,则执行相应操作,输入的是q则退出程序,代码如下:
参考链接:
50以内的素数有哪些_百度知道
python基础之写文件操作_jiankang66的博客-CSDN博客_python 写文件
【Python 基础】Python 文件读写模式 mode_AiFool的博客-CSDN博客_python 文件读写模式
def findPrime2To50(): # 计算并输出2到50之间的素数
for i in range(2,51):
prime=1
for j in range(2,i):
#print("i=",i,"j=",j)
if i%j==0:
prime=0
break
if prime==1:
# https://zhidao.baidu.com/question/653705509068683165.html
print(i,end=" ")
print("")
choice=input("请输入1、2或q:")
while choice!='q': # 如果输入的不是q,则循环执行预定的操作
if choice=="1": # 输出2到50之间的素数
findPrime2To50()
elif choice=="2": # 获取输入写入文件
# https://blog.csdn.net/jiankang66/article/details/125981793
# https://blog.csdn.net/datapad/article/details/123041171
s = input("请输入一些文字以写入文件,或输入x退出写入文件:")
while s!='x':
file = open('hello.txt','a')
file.write(s)
s = input("请输入一些文字以写入文件,或输入x退出写入文件:")
file.close()
choice=input("请输入1、2或q:")