美文网首页
【Python】-011-语句表达式-练习

【Python】-011-语句表达式-练习

作者: 9756a8680596 | 来源:发表于2017-07-27 13:55 被阅读45次

1.猜数字

  • 随机产生要猜的整数数字(1~100)
  • 接受用户输入的数字
  • 如果没猜对提示用户大了还是小了
  • 直到猜到数字或者达到一定的次数(6次),给出提示后结束游戏
  • 要求防作弊,错误输入判断
    import random

    bingo = random.randint(1, 100)  //随机生成一个1~100的整数
    guess, guess_int, i, counts = 0, 1, 0, 6  //初始化用到的变量
    print 'You have ', counts, 'times to input.'

    try:  //字符转为整数可能会报错
        while guess != bingo and i < counts:
            guess = raw_input('Please input a number[1, 100]:')
            guess_int = int(guess)  #类型转换,可能或报异常
            if guess_int < bingo:
                print 'Maybe a bigger number will correct.'
            if guess_int == bingo:
                print 'Congratulates, you get the number:', bingo
                break;
            if guess_int > bingo:
                print 'Maybe a smaller number will correct.'
            i = i + 1
        if i == 6:
            print 'Sorry you don\'t get the number. The number is ', bingo
    except Exception, e:
        print 'Invalid input, GAME OVER.'

2.利用上次用户名密码练习,模拟注册过程:

  • 用户输入用户名后进行查重,如果用户名已经存在需要返回合理的提示

  • 否则,则增加用户名和密码到文件中,密码需要进行MD5加密

  • 用户名:字母数字、下划线和横线的组合,且首字符是字母,6~18个字符

  • 密码:6~16个字符,区分大小写

     -*- coding: utf-8 -*-
    ##version 1.0
    ##利用随机函数产生一个用户的用户名,密码,并利用文件将用户名和密码保存下来
    ##将上述的文件中密码进行加密,使用python中md5库处理,在保存到文件中
    ##version 2.0
    ##用户输入用户名后进行查重,如果用户名已经存在需要返回合理的提示
    ##否则,则增加用户名和密码到文件中,密码需要进行MD5加密
    ##用户名:字母数字、下划线和横线的组合,且首字符是字母,6~18个字符
    ##密码:6~16个字符,区分大小写
    ##思路:
    ##-让用户根据规则输入用户名
    ##-利用正则表达式进行格式检测,如果格式不正确提示重新输入,否则进入下一步
    ##-将格式正确的用户名进行查重处理,检测与文件中的是否重复,如果重复需要重新输入,否则进入下一步
    ##-让用户根据规则输入密码
    ##-利用正则表达式进行格式检测,如果格式不正确提示重新输入,否则进入下一步
    ##-将密码进行MD5加密
    ##-追加用户信息到文件(/Users/caoweiwei/Box\ Sync/)中
    
    import re
    import hashlib
    
    print 'Please input a nickname: (press 0 to exit).'
    print '1.Please use between 6 and 18 characters.'
    print '2.Begin with letters (a-z|A-Z);'
    print '3.You can use letters, numbers,periods.'
    username = raw_input()
    
    p_username = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-\_]{5,17}$')  #用户名格式正则匹配
    p_password = re.compile(r'^[a-zA-Z0-9\-\_]{6,8}$')  #密码格式正则匹配
    usrpwd_list = []    #usrpwd_list
    usrpwd_dict = {}    #usrpwd_dict
    
    #读取文件中的用户名、密码MD5到字典中,检测用户名是否重复
    f = open("/Users/caoweiwei/Box Sync/aaa.txt", 'r+a')
    for line in f:
        sub_line = re.sub(r'[\s]', '', line)  #根据文件格式,确保每个用户信息最少又一个换行符
        if sub_line == '' and i != 1:
            usrpwd_list.append(usrpwd_dict.copy())  #字典拷贝数据放到列表中
            i = 1
            continue
        if sub_line != '':
            i = 0
            items = sub_line.split(':')
            usrpwd_dict[items[0]] = items[1]  #读取的数据放到字典中
    
    while username != 'q' :
        if re.findall(p_username, username) == []: 
            print 'Please check your nickname!'
            username = raw_input('Please input a nickname: (press q to exit).')
        else: #如果格式正确,再检测是否重复
            if username in [d['username'] for d in usrpwd_list]:
                print 'The nickname already has been used!'
                username = raw_input('Please input a nickname: (press q to exit).')
            else:#不重复就输入密码
                print 'Please input a password:'
                print 'Use at least 6~8 characters'
                print 'You can use letters, numbers,periods'
                password = raw_input()
                while re.findall(p_password, password) == []:
                    print 'Please check your password!'
                    password = raw_input('re-input your password:')
                else:
                    password_md5 = hashlib.md5(password).hexdigest()
                    break
    if username == 'q':
        print 'See you'
    else:#写入文件中
        print >> f, 'username: ', username, '\n', 'password: ', password, '\n', 'MD5: ', password_md5, '\n'
        print 'Sign up successful!'
    
    f.close()
    

3.公交系统练习,

  • 将所有线路的linenum和station保存到一个字典中

  • 查询公交站点名称,将所有包含该站点linenum和station存到字典并返回

    # -*- coding: utf-8 -*-
    ##公交查询系统练习,
    ##.将所有线路的linenum和station保存到一个字典中
    ##.查询公交站点名称,将所有包含这个站点的linenum存到字典进行返回
    ## 思路:
    ##-预览csv文件格式,根据csv库将读取linenum和station两列,并生成字典,key为linenum,value为station,其中station需要做空白字符处理
    ##-接受用户输入的公交站点名称,异常处理,可能不存在输入值
    ##-根据输入的站点名称,查询每个value的字符串,如果匹配子串,记录linenum和station到另外一个结果字典中
    
    import csv
    import re
    import json
    
    p = re.compile(r'[\s]')
    
    # The linenum and station dict
    with open('/Users/caoweiwei/Downloads/beijing_jt.csv', 'rb') as f1:
        reader = csv.DictReader(f1)
        line_station_dict = dict([(row['linenum'],re.sub(p, '', row['station'])) for row in reader])    #去除station中的空字符\b\t\n等
    # The dict of station: linenum
    reverse_ = dict([ (value, key) for key, value in line_station_dict.items() ])   #将原始字典的key,value反过来,方便通过value查询到key
    
    try:
         keywords = raw_input('Please input the station name: ')    #根据value查询key值,将查询到的key,value保存到字典中
         listLinenum = {}
         for values in line_station_dict.values():
             if values.find(keywords) != -1:
                 listLinenum.update({reverse_[values]: values})
    except Exception, e:
          print 'The station not exist!'
    
    print json.dumps(listLinenum, encoding="UTF-8", ensure_ascii=False)
    f1.close()
    

参考资料

相关文章

网友评论

      本文标题:【Python】-011-语句表达式-练习

      本文链接:https://www.haomeiwen.com/subject/rngukxtx.html