Interactive Python:Mini-project # 1 - "Guess the number" game"

这篇博客分享了作者在完成莱斯大学Python课程的一个迷你项目——'Guess the number'游戏时的心得体会,强调了编程风格的重要性,如运算符、逗号后的空格规则,以及CamelCase和lower_case_with_underscores的命名规范。同时,文章提到了Python中全局变量和局部变量的使用,指出在子函数中修改全局变量需先用global声明。提供了答案代码链接。
摘要由CSDN通过智能技术生成

加上这一次的作业,这门莱斯大学的python课程的所有project都已经完成了。

这次作业中,收获最大的是关于编程风格的问题。

在运算符前后和逗号后面都要添加空格,除非紧邻着括号。类名要使用CamelCase,但方法和函数要使用lower_case_with_underscores。参考链接

另外,python中的全局变量的用法和局部变量一样。在子函数中要对全局变量赋值,要事先使用global在子函数中声明。如果忘记了,错误很难被发现。

我的答案链接为这里,这个网站暂时只能在域名/save这个链接上保存代码。

答案代码如下:

# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console

import random, simplegui, math

# initialize global variables used in your code

canvas_width = 100
canvas_height = 300
control_width = 200
object_width = 100

num_range_low = 0
num_range_high = 100
real_num = 0

remain_guess_times = 0

# helper function to start and restart the game
def new_game():    
    global real_num, remain_guess_times
    real_num = random.randrange(num_range_low, num_range_high)
    remain_guess_times = int(math.ceil(math.log(num_range_high - num_range_low + 1, 2)))
    print ''
    print 'New game start, number range is [', num_range_low, ',', num_range_high, ').'
    print 'You have ', remain_guess_times, ' chances to guess.'


# define event handlers for control panel
def range100():
    # button that changes range to range [0,100) and restarts
    global num_range_low, num_range_high
    num_range_low = 0
    num_range_high = 100
    new_game()


def range1000():
    # button that changes range to range [0,1000) and restarts
    global num_range_low, num_range_high
    num_range_low = 0
    num_range_high = 1000
    new_game()
    

    
def input_guess(guess):
    # main game logic goes here	
    global remain_guess_times
    remain_guess_times -= 1
    guess_num = int(guess)
    
    print 'You guessed: ', guess_num, '. ',
    print 'Your remained ', remain_guess_times, 'guess chances.',
    
    if guess_num == real_num:
        print 'Correct!'
        new_game()
    elif guess_num > real_num:
        print 'Higher'
    e
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值