ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Mosh老师的几个Python趣味示例程序

Mosh老师的几个Python趣味示例程序 Mosh老师的Python Projects for Beginners – Master Problem-Solving! 这个视频讲解的几个Python示例兼具趣味性和易学性。其Github源代码地址为https://github.com/mosh-hamedani/python-projects-for-beginners对应的项目描述PDF文件下载地址为https://cdn.codewithmosh.com/image/upload/v1725636826/guides/python-projects-for-beginners.pdf1. 掷骰子游戏Python程序代码实现如下importrandomwhileTrue:choiceinput(Roll the dice? (y/n): ).lower()ifchoicey:die1random.randint(1,6)die2random.randint(1,6)print(f({die1},{die2}))elifchoicen:print(Thanks for playing!)breakelse:print(Invalid choice!)程序运行结果如下2. 猜数字游戏Python程序代码实现如下importrandom guess_numberrandom.randint(1,100)whileTrue:sinput(Guess the number between 1 and 100: )try:numberint(s)ifnumberguess_number:print(Too low!)elifnumberguess_number:print(Too high!)else:print(Congratulations! You guessed the number.)breakexceptValueError:print(Invalid input! Please enter a valid number.)运行结果如下3. 石头剪刀布游戏石头剪刀布是我们小时候经常玩的一个小游戏了出手双方有石头、剪刀、布的三种选择双方如果都出一样的则平局否则石头 剪刀剪刀 布布 石头。Python程序代码实现如下importrandom ROCKrSCISSORSsPAPERpemojis{ROCK:,SCISSORS:✂️,PAPER:}choicestuple(emojis.keys())defget_user_choice():whileTrue:user_choiceinput(Rock, paper, or scissors? (r/p/s): ).lower()ifuser_choiceinchoices:returnuser_choiceelse:print(Invalid choice!)defdisplay_choices(user_choice,computer_choice):print(fYou chose{emojis[user_choice]})print(fComputer chose{emojis[computer_choice]})defdetermine_winner(user_choice,computer_choice):ifuser_choicecomputer_choice:print(Tie!)elif((user_choiceROCKandcomputer_choiceSCISSORS)or(user_choiceSCISSORSandcomputer_choicePAPER)or(user_choicePAPERandcomputer_choiceROCK)):print(You win)else:print(You lose)defplay_game():whileTrue:user_choiceget_user_choice()computer_choicerandom.choice(choices)display_choices(user_choice,computer_choice)determine_winner(user_choice,computer_choice)should_continueinput(Continue? (y/n): ).lower()ifshould_continuen:breakplay_game()程序运行结果如下4. 二维码生成器Python实现代码如下importqrcode datainput(Enter the text or URL: ).strip()filenameinput(Enter the filename: ).strip()qrqrcode.QRCode(box_size10,border4)qr.add_data(data)imageqr.make_image(fill_colorblack,back_colorwhite)image.save(filename)print(fQR code saved as{filename})其运行结果如下图所示当然我们运行这个程序之前除了要安装qrcode二维码库之外还需要安装pillow这个包。命令如下pipinstallqrcode pipinstallpillow参考资料Python Projects for Beginners – Master Problem-Solving! Github源代码地址为https://github.com/mosh-hamedani/python-projects-for-beginners项目描述PDF文件下载地址为https://cdn.codewithmosh.com/image/upload/v1725636826/guides/python-projects-for-beginners.pdfhttps://pypi.org/project/qrcode/https://pypi.org/project/pillow/
返回列表