以下的文章部分翻译自kinght lab的博客,原文链接: https://medium.com/learning-journalism-tech/five-mini-programming-projects-for-the-python-beginner-21492f6ce0f3#.boemvvuxf
通常来讲,最好的学习一门编程语言的方法是在项目中使用它,但是当你没有什么大型的项目可以参加的时候,找个小的程序来练练受也是不错的选择,接下来让我们一起用python做一些小的编程项目吧。
第一个项目: 色子模拟器
目标:模拟一个玩色子的小游戏
以下是自己写的小程序,聊做记录,以后更改
#!usr/bin/env python # _*_ coding: utf-8 _*_ from random import randint class Dice(object): "The definition of dise model" def __init__(self, sides=6): self.sides = sides def play_dice(self): return randint(1,self.sides) def choose_game(): "Which game is the one you want to paly?" games = { "game_1": "Throw one dice", "game_2": "sai-bo" } welcom_str = "Which game do you want to play?\n\t1. %s\n\t2. %s\n\t" %(games["game_1"], games["game_2"]) user_choose = raw_input(welcom_str) # never trust any user's input try: user_choose = int(user_choose) if user_choose == 1: return games["game_1"] elif user_choose == 2: return games["game_2"] else: print("Opps, no this game") choose_game() except ValueError: print("Please give me the righe choice.") choose_game() def one_dice_game(): "Throw a dice and guess a number, then boooooom" dice = Dice() dice_number = dice.play_dice() user_guess = raw_input("Please guess a number: ") try: user_guess = int(user_guess) if user_guess == dice_number: print("Great,you got it!") else: print("The right number is %d." % dice_number) except ValueError: print("Wrong input") def sai_bo(): "Do you want to buy the hi, lo or the big boom?" dice1 = Dice() dice2 = Dice() dice3 = Dice() dice1_result, dice2_result, dice3_result = dice1.play_dice(), dice2.play_dice(), dice3.play_dice() if dice1_result == dice2_result == dice3_result: result = "boom" elif dice1_result + dice2_result + dice3_result <= 10: result = "low" else: result = "high" gamble = raw_input("High-Low or Boom, make a dicision! ") if gamble.strip().lower() == result or gamble.strip().lower() == result[0]: if result == "boom": print("Oh my God, you win the world!") else: print("You win the game") else: if result == "boom": print("You lose the world!") else: print("You lose the game.") if __name__=="__main__": while(True): play_or_not = raw_input("Do you want to play a game with me?(y/n)") if play_or_not.strip().lower() == 'y': game = choose_game() if game == "Throw one dice": while(True): one_dice_game() more_or_not = raw_input("Once more?(y/n)") if more_or_not.strip().lower() == 'n': break else: print("Come on!!!") else: while(True): sai_bo() more_or_not = raw_input("Once more?(y/n)") if more_or_not.strip().lower() == 'n': break else: print("Come on") else: break