مثال17:
منوی زیر را ایجاد کنید:
1)add to file
2)view all records
3)delete record
4)quit program
✅اگر کاربر 1 را انتخاب کرد، به او اجازه دهید به فایلی به نام Salaries.csv اضافه کند که نام و حقوق آنها ذخیره می شود.
✅ اگر آنها 2 را انتخاب کنند باید تمام رکوردهای موجود در فایل Salaries.csv نمایش داده شود.
✅ گزینه 3 حذف آیتم موردنظر از فایل
✅ اگر آنها 4 را انتخاب کنند باید برنامه را متوقف کند.
✅ اگر گزینه نادرستی را انتخاب کنند باید یک پیام خطا ببینند.
👈 آنها باید به بازگشت به منو ادامه دهند تا زمانی که گزینه 4 را انتخاب کنند.
import csv
def add_file():
file=open('salaries.csv','a')
name=input('Enter your name:')
salary=int(input('Enter your salary:'))
newrecord=name +',' + str(salary)+'\n'
file.write(str(newrecord))
file.close()
def view():
file=open('salaries.csv','r')
for item in file:
print(item)
file.close()
def delete():
file=open('salaries.csv','r')
x=0
list=[]
for item in file:
list.append(item)
file.close()
for item in list:
print(x,item)
x+=1
itemtodelete=int(input('Enter the number to delete:'))
del list[itemtodelete]
file=open('salaries.csv','w')
for item in list:
file.write(item)
file.close()
tryagain=True
while tryagain==True:
selection=input('1)Add to file\n2)view all records\n3)Delete records\n4)Quit prigram\nenter yourselection:')
if selection=='1':
add_file()
elif selection=='2':
view()
elif selection=='3':
delete()
elif selection=='4':
tryagain=False
else:
prrint('Incorrect selection!')مثال22: دریافت عدد n از کاربر و چاپ اعداد دنباله فیبوناچی از ابتدا تا عدد شماره n.
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
terms = int(input("Enter the number of terms: "))
print("Fibonacci sequence:")
for i in range(terms):
print(fibonacci(i))