python初級算法圖解(理解Python布爾值原理)
2023-05-18 10:53:16 4
本文閱讀時間大概為5分鐘
Hello,小數先生粗線啦~~~今天教大家製作一款美食推薦器
先看下美食推薦器效果(文中最後有美食推薦器代碼)
上傳視頻封面
Python製造 —— 美食推薦器
用數據做判斷:布爾值
計算機的邏輯判斷,只有兩種結果,就是True(真)和False(假),計算真假的過程 ,叫做布爾運算。True和False就叫布爾值
例
print(1>2)print(1 2 and 2 > 1: print('(1>2) and (2>1) is True') #1>2為假,1>2 and 2>1為假if 1 > 2 or 2 > 1: print('(1>2)or(2>1) is True')if not (1>2): print('not (1>2) is True')
輸出
(1>2)or(2>1) is Truenot (1>2) is True
break語句
break 語句可以跳出 for 和 while 的循環體
例(for循環)
for i in range(5): print(i) if i == 3: break #當i等於3的時候結束循環
輸出
0123
例(while循環)
while True: answer = input('喜不喜歡Python?') if answer == '喜歡': break #輸入喜歡跳出循環
輸出
喜不喜歡Python?不喜歡喜不喜歡Python?不喜歡喜不喜歡Python?喜歡
continue語句
continue語句被用來告訴 Python 跳過當前循環塊中的剩餘語句,然後繼續進行下一輪循環
for i in range(1,5): print('關注數仁信息的第{}天'.format(i)) if i == 3: continue #當i等於3的s時候回到循環開頭 print('Moring,小數先生')
輸出
關注數仁信息的第1天Moring,小數先生關注數仁信息的第2天Moring,小數先生關注數仁信息的第3天關注數仁信息的第4天Moring,小數先生
pass語句
pass 不做任何事情,一般用做佔位語句
例
for i in range(5): if i == 3: pass # i等於3的時候什麼都不做 else: print(i)
輸出
0124
美食推薦器代碼
import timeimport randomfoods_list = ['肯德基','麥當勞','漢堡王','達美樂','必勝客', '水餃','酸菜魚','煲仔飯','過橋米線','杭幫菜', '火鍋','冒菜','麻辣燙','麻辣香鍋','輕食','木桶飯']recommend_list = foods_list[:]print('{} 小數先生的美食推薦器 {}'.format('-'*20,'-'*20) '\n')time.sleep(0.5)while True: print(' ') time.sleep(0.5) print('美食推薦,選擇當前美食輸入y,繼續推薦按回車') if len(recommend_list) > 0: recommend_food = random.choice(recommend_list) time.sleep(0.5) choice = input('吃{}怎麼樣?'.format(recommend_food)) print(' ') time.sleep(0.5) print('-'*60) if choice == 'y': print('那就這麼開心的決定了,中午去吃{}'.format(recommend_food)) if recommend_food in ['漢堡王','肯德基','麥當勞','必勝客']: print(r''' _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . ___ ."" '< `.___\__/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 佛祖保佑 不會長肉 ''') break else: recommend_list.remove(recommend_food) else: choose_like = input('所有美食已經推薦完,重新推薦輸入r,按任意鍵美食推薦器給出最佳選擇:') if choose_like == 'r': recommend_list = foods_list[:] else: print('{}是不錯的選擇'.format(random.choice(foods_list))) print('-'*60) break
,