练习题|文件操作和函数

文件操作练习题

  1 —— 全局替换程序:

  • 写一个脚本,允许用户按以下方式执行时,即可以对指定文件内容进行全局替换

'python your_script.py old_str new_str filename'
  • 替换完毕后打印替换了多少处内容

 https://www.cnblogs.com/shengyang17/p/8688915.html

  2 —— 模拟登陆:

  • 用户输入帐号密码进行登陆
  • 用户信息保存在文件内
  • 用户密码输入错误三次后锁定用户,下次再登录,检测到是这个用户也登录不了
i = 0
file = open("正确用户信息",'r',encoding='utf-8')
file_wrong = open("锁定信息",'r+',encoding='utf-8')
line = eval(file.readline())
line_wrong = eval(file_wrong.readline())

name = input("请输入用户名:")
passworld = input("请输入密码:")
if name in line and name not in line_wrong:
    while i <= 3:
        if passworld == line[name]:
            print('登录成功')
            break
        else:
            i +=1
            print('\n您已经第%d次输错密码,输错3次账户将会被锁定'%(i))
            if i < 3:
                passworld = input("请重新输入密码:")
            elif i == 3:
                print("已经输错3次,账户已被锁定")
                line_wrong.append(name)
                file_wrong.seek(0)
                file_wrong.write(str(line_wrong))
                #file_wrong.tell()
                break
elif name in line_wrong:
    print("该用户名已被锁定")
else:
    print("该用户名不存在")
    exit()

 递归练习题

#递归练习题  http://www.cnblogs.com/xiao-apple36/p/8607835.html
menus = [
    {
        'text':'北京',
        'children':[
            {'text':'朝阳','children':[]},
            {'text':'昌平','children':[
                {'text':'沙河','children':[]},
                {'text':'回龙观','children':[]},
            ]}
        ]
    },
    {
        'test':'上海',
        'children':[
            {'test':'宝山','children':[]},
            {'test':'金山','children':[]},
        ]
    }
]
#有时面试 深度查询
#1.打印所有的节点
#1.输入一个节点名字,沙河,你要遍历找,找到了,就打印它,并返回true
# 打印所有的节点
def recu_Menu(menu):
    for sub_menu in menu:
        menu_text = sub_menu['text']
        menu_children = sub_menu['children']
        print(menu_text)
        recu_Menu(menu_children)

recu_Menu(menus)
# 打印所有的节点,输入一个节点名字,沙河, 你要遍历找,找到了,就打印它,并返回true,
flag = False
def recu_Menu_node(menu, node, layer):
    global flag
    for sub_menu in menu:
        menu_text = sub_menu['text']
        menu_children = sub_menu['children']
        if node == menu_text:
            print("找到%s在第%s层" % (node, layer))
            flag = True
            return flag
        else:
            recu_Menu_node(menu_children, node, layer + 1)
            print("menu_text=", menu_text)

    return flag

node_str = input("输入一个节点名字-> ")
print(recu_Menu_node(menus, node_str, 1))


#方法二
menus = [
    {
        'text': '北京',
        'children': [
            {'text': '朝阳', 'children': []},
            {'text': '昌平', 'children': [
                {'text': '沙河', 'children': []},
                {'text': '回龙观', 'children': []},
            ]},
        ]
    },
    {
        'text': '上海',
        'children': [
            {'text': '宝山', 'children': []},
            {'text': '金山', 'children': []},
        ]
    }
]
#打印所有的节点
def recu_Menu(menu):
    for sub_menu in menu:
        #print(sub_menu)
        menu_text = sub_menu['text']
        menu_children = sub_menu['children']
        print(menu_text)
        recu_Menu(menu_children)
recu_Menu(menus)

#打印所有的节点,输入一个节点名字,沙河,你要遍历找,找到了,就打印它,并返回true
def recu_Menu_node(menu, node, layer):
    # if len(menu)>0:
    for sub_menu in menu:
        menu_text = sub_menu['text']
        menu_children = sub_menu['children']
        print("menu_text=", menu_text)
        if node == menu_text:
            print("找到%s在第%s层" % (node, layer)) #返回到外层  node节点| layer层次
            return True
        else:
            if recu_Menu_node(menu_children, node, layer + 1) == True: #如果里层返回True,继续向上返回True
                return True
            else:
                recu_Menu_node(menu_children, node, layer + 1)
node_str = input("输入一个节点名字-->>> ")
print(recu_Menu_node(menus, node_str, 1))

函数练习题

修改个人信息程序,在一个文件里存多个人的个人信息,如以下:

username password  age position department 
alex     abc123    24   Engineer   IT
rain     df2@432    25   Teacher   Teching
....

  1.输入用户名密码,正确后登录系统 ,打印

    1. 修改个人信息
    2. 打印个人信息
    3. 修改密码

  2.每个选项写一个方法

  3.登录时输错3次退出程序

def print_user_info(account_dic,username):
    person_info = account_dic[username]
    msg = '''
    Name:  %s
    Age:   %s
    Job:   %s
    Dept:  %s
    Phone: %s
    ''' % (person_info[2],
           person_info[3],
           person_info[4],
           person_info[5],
           person_info[6])
    print(msg)

def save_back_to_file(account_dic):
    f.seek(0)
    f.truncate()
    for line in account_dic:
        row = ','.join(account_dic[line])
        f.write('%s\n' % row)
    f.flush()

def update_user_info(account_dic,username):
    person_info = account_dic[username]
    print('old data:', person_info)
    str = ['Username','Password','Name','Age','Job','Dept','Phone']
    for index, i in enumerate(person_info):
        if index > 1:   #用户名 密码 不显示
            print('%s. %s:  %s' % (index, str[index], i))
    choice = input('select column id to change >>>:').strip()
    if choice.isdigit():
        choice = int(choice)
        if choice > 1 and choice < len(person_info):
            print('current value:', person_info[choice])
            new_val = input('new value:').strip()
            if new_val: #不为空
                person_info[choice] = new_val
                print('new data:', person_info)
                save_back_to_file(account_dic)
            else:
                print('不能为空!')


f = open('account.txt', 'r+', encoding='utf-8')
data = f.readlines()
print(data)
account_dic = {}

for i in data:
    items = i.replace(' ', '').split(',')
    account_dic[items[0]] = items   # 将文件读出来存到字典形式中
print(account_dic)

msg = '''
1.打印个人信息
2.修改个人信息
'''

count = 0
while count < 3:
    username = input('Username:').strip()
    password = input('Password:').strip()
    if username in account_dic:
        if password == account_dic[username][1]:
            print('welcome %s '.center(50,'-') % username)
            while True:
                print(msg)
                user_choice = input('>>>:').strip()
                if user_choice.isdigit():
                    user_choice = int(user_choice)
                    if user_choice == 1:
                        print_user_info(account_dic,username)
                    elif user_choice == 2:
                        update_user_info(account_dic,username)

                elif user_choice == 'q':
                    exit('bye bye')
        else:
            print('Wrong Username or password')
    else:
        print('Username dose not exist')
    count += 1
else:
    print('Too many attempts')
f.close()

函数进阶练习题

一:编写3个函数,每个函数执行的时间是不一样的,

提示:可以使用time.sleep(2),让程序sleep 2s或更多,

import time
a = time.localtime()
def func1():
    print("%s-%s-%s"%(a.tm_year,a.tm_mon,a.tm_mday))
def func2():
    time.sleep(2)
    print("%s-%s-%s"%(a.tm_year,a.tm_mon,a.tm_mday))
def func3():
    time.sleep(4)
    print("%s-%s-%s"%(a.tm_year,a.tm_mon,a.tm_mday))
func1()
func2()
func3()

二:编写装饰器,为每个函数加上统计运行时间的功能

提示:在函数开始执行时加上start=time.time()就可纪录当前执行的时间戳,函数执行结束后在time.time() - start就可以拿到执行所用时间

import time
def deco(func):
    start_time = time.time()
    func()
    stop_time = time.time()
    print('the func run time is %s'%(stop_time - start_time))
def test1():
    time.sleep(2)
    print('in the test1')
def test2():
    time.sleep(4)
    print('in the test2')
deco(test1)     #test1()加括号就是把它的运行结果传进去了
deco(test2)   #这种是改变了函数的调用方式



import time
def timer(func):  #timer(test1)  func=test1
    def deco():
        start_time = time.time()
        func()  #运行test1()
        stop_time = time.time()
        print('the func run time is %s'%(stop_time - start_time))
    return deco
def test1():
    time.sleep(2)
    print('in the test1')
def test2():
    time.sleep(4)
    print('in the test2')
#print(timer(test1))  #返回的是deco的一个内存地址
test1 = timer(test1)
test1()  ## 实际上运行执行的是deco    #既没有改变调用方式也没有改变原代码
test2 = timer(test2)
test2()

三:编写装饰器,为函数加上认证的功能,即要求认证成功后才能执行函数

import time
a = time.localtime()
def logger(func):
    def inner():
        _usename = 'kris'
        _passworld = 'abc123'
        usename = input('请输入用户名:')
        passworld = input('请输入密码:')
        if usename == _usename and passworld == _passworld:
            print('认证成功')
            func()
        else:
            print("您的输入有误")
    return inner
def log1():
    print("%s-%s-%s"%(a.tm_year,a.tm_mon,a.tm_mday))#13
@logger
def log2():
    time.sleep(2)
    print('%s-%s-%s' % (a.tm_year, a.tm_mon, a.tm_mday))
@logger
def log3():
    time.sleep(4)
    print('%s-%s-%s' % (a.tm_year, a.tm_mon, a.tm_mday))
log1()
log2()
log3()

四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码

提示:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式

 https://www.cnblogs.com/xiugeng/p/8617831.html

https://www.cnblogs.com/wangmengzhu/p/7234471.html

https://blog.csdn.net/q409561046/article/details/73346401

文件操作和函数总结练习

文件处理相关

1.编码问题

  • 请说明python2 与python3中的默认编码是什么?

    python2的默认编码是ASCII码,python3的默认编码是utf-8

  。为什么会出现中文乱码?你能列举出现乱码的情况有哪几种?(https://blog.csdn.net/ggggiqnypgjg/article/details/53271541#终端为utf-8locale为zhcngbk)

#coding:utf-8 #.py文件是什么编码就需要告诉python用什么编码去读取这个.py文件。
sys.stdout.encoding,默认就是locale的编码,print会用sys.stdout.encoding去encode()成字节流,交给terminal显示。所以locale需要与terminal一致,才能正确print打印出中文。
sys.setdefaultencoding(‘utf8’),用于指定str.encode() str.decode()的默认编码,默认是ascii。
以下几种(local 为软件运行时的语言环境):
 终端为UTF-8,locale为zh_CN.GBK
 终端为UTF-8,locale为zh_CN.UTF-8
 终端为GBK,locale为zh_CN.GBK
 终端为GBK,locale为zh_CN.UTF-8

2.如何进行编码转换?

  字符串在python内部中是采用unicode的编码方式,所以其他语言先decode转换成unicode编码,再encode转换成utf8编码。

3.#-*-coding:utf-8-*- 的作用是什么?

  编码声明

4.解释py2 bytes vs py3 bytes的区别:

Python 2 将 strings 处理为原生的 bytes 类型,而不是 unicode(python2 str == bytes),
Python 3 所有的 strings 均是 unicode 类型(python3 中需要通过 unicode )
   string -> encode  -> bytes

   bytes -> decode  -> string

5.文件处理

i  r和rb的区别是什么?

    r是只读模式;rb是二进制读取模式。

ii 解释一下以下三个参数的分别作用?  open(f_name,'r',encoding="utf-8")

    f_name是文件;r为只读模式;encoding是编码

函数基础:

  1. 写函数,计算传入数字参数的和。(动态传参)                                                                                                                                                                                                                                                                          
    def calc(x,y):
        print('x + y')
    calc(3,4)
  2. 写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作                                                                                                                                                                                             
    def file_de(file):
    a = []
    for line in file:
        b = line.capticalize()
        a.append(b)
    print(a)

    写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。                                                                                                                                                                                              

    1. def file_k(file):
          n = 0
          for i in file:
              if i ==" ":
                n +=1
          print('有%s个空%" %n)
  3. 写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

    dic = {"k1": "v1v1", "k2": [11,22,33,44]}
    PS:字典中的value只能是字符串或列表     

  4.闭包

   在函数里边又套了一层子函数,在子函数被返回了,就是当外层函数执行的时候子函数被返回了返回了内存地址;然后在外边执行这个子函数的时候它又引用了外边函数的这个变量,

  相当于这个子函数跟外层函数有某种扯不清的关系,这种关系就叫闭包。

def func():
    n = 10
    def func2():
        print('func',n)
    return func2
f = func()
print(f)
f()

函数进阶:

  1. 写函数,返回一个扑克牌列表,里面有52项,每一项是一个元组
    1. 例如:[(‘红心’,2),(‘草花’,2), …(‘黑桃A’)]                                                                                                                                                                                

 def cards():
     num = []
     for i in range(2,11):
         num.append(i)
     num.extend(['J','Q','K','A'])
     type = ['红心','草花','方块','黑桃']
     result = []
     for i in num:
         for j in type:
             result.append((j,i))
     return result
 print(cards())
  1. 写函数,传入n个数,返回字典{‘max’:最大值,’min’:最小值}

    例如:min_max(2,5,7,8,4) 返回:{‘max’:8,’min’:2} 
def max_min(*args):
     the_max = args[0]
     the_min = args[0]
     for i in args:
         if i > the_max:
             the_max = i
         if i < the_min:
             the_min = i
     return {'max': the_max, 'min': the_min}

 print(max_min(2, 4, 6, 48, -16, 999, 486, ))
  1. 写函数,专门计算图形的面积

    • 其中嵌套函数,计算圆的面积,正方形的面积和长方形的面积
    • 调用函数area(‘圆形’,圆半径) 返回圆的面积
    • 调用函数area(‘正方形’,边长) 返回正方形的面积
    • 调用函数area(‘长方形’,长,宽) 返回长方形的面积
    def area(): def 计算长方形面积(): pass def 计算正方形面积(): pass def 计算圆形面积(): pass
import math
  print('''
  请按照如下格式输出:
      调用函数area(‘圆形’,圆半径) 返回圆的面积
      调用函数area(‘正方形’,边长) 返回正方形的面积
      调用函数area(‘长方形’,长,宽) 返回长方形的面积''')
  def area(name,*args):
      def areas_rectangle(x,y):
          return ("长方形的面积为:",x*y)

      def area_square(x):
          return ("正方形的面积为:",x**2)

      def area_round(r):
          return ("圆形的面积为:",math.pi*r*r)
      if name =='圆形':
          return area_round(*args)
      elif name =='正方形':
          return area_square(*args)
      elif name =='长方形':
          return areas_rectangle(*args)


  print(area('长方形', 3, 4))
  print(area('圆形', 3))
  print(area('正方形', 3))
  1. 写函数,传入一个参数n,返回n的阶乘

    例如:cal(7)
    计算7*6*5*4*3*2*1
def cal(n):
   res= 1
   for i in range(n,0,-1):
       # print(i)
       res = res*i
       print(res)
   return res

print(cal(7))
  1. 编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码

def login(func):
    def wrapper(*args,**kwargs):
        username = input("account:").strip()
        password = input("password:").strip()
        with open('userinfo.txt','r',encoding='utf-8') as f:
            userinfo = f.read().strip(',')
            userinfo = eval(userinfo)
            print(userinfo)
            if username in userinfo['name'] and password in userinfo['password']:
                print("success")
            else:
                print("pass")

    return wrapper

@login
def name():
    print("hello")

name()

生成器和迭代器

  1. 生成器和迭代器的区别?                                                                                                                                                                                                                                                                                                               

    对于list、string、tuple、dict等这些容器对象,使用for循环遍历是很方便的。
    在后台for语句对容器对象调用iter()函数。iter()是python内置函数。
    iter()函数会返回一个定义了 next()方法的迭代器对象,它在容器中逐个访问容器内的
    元素。next()也是python内置函数。在没有后续元素时,next()会抛出
    一个StopIteration异常,通知for语句循环结束。
    迭代器是用来帮助我们记录每次迭代访问到的位置,当我们对迭代器使用next()函数的
    时候,迭代器会向我们返回它所记录位置的下一个位置的数据。实际上,在使用next()函数
    的时候,调用的就是迭代器对象的_next_方法(Python3中是对象的_next_方法,
    Python2中是对象的next()方法)。所以,我们要想构造一个迭代器,
    就要实现它的_next_方法。但这还不够,python要求迭代器本身也是可迭代的,
    所以我们还要为迭代器实现_iter_方法,而_iter_方法要返回一个迭代器,
    迭代器自身正是一个迭代器,所以迭代器的_iter_方法返回自身self即可。
  2. 生成器有几种方式获取value?                                                                                                                                                                                                                       for循环和next获取

  3. 通过生成器写一个日志调用方法, 支持以下功能

    • 根据指令向屏幕输出日志
    • 根据指令向文件输出日志
    • 根据指令同时向文件&屏幕输出日志
    • 以上日志格式如下

      2017-10-19 22:07:38 [1] test log db backup 3
      2017-10-19 22:07:40 [2] user alex login success
      #注意:其中[1],[2]是指自日志方法第几次调用,每调用一次输出一条日志
    • 代码结构如下

      def logger(filename,channel='file'):
      """
      日志方法
      :param filename: log filename
      :param channel: 输出的目的地,屏幕(terminal),文件(file),屏幕+文件(both)
      :return:
      """
      ...your code...
      
      #调用
      log_obj = logger(filename="web.log",channel='both')
      log_obj.__next__()
      log_obj.send('user alex login success')

内置函数

  1. 用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb

    name=['alex','wupeiqi','yuanhao','nezha']
    
    def sb(x):
       return x+'_sb'
    
    res = map(sb,name)
    print(list(res))

    map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把
    函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。

      注意:map()函数在不改变原有的lisy,而是返回一个新的list

  2. 用filter函数处理数字列表,将列表中所有的偶数筛选出来

    num = [1,3,5,6,7,8]
    def func(x):
       if x%2 == 0:
           return True
    
    ret = filter(func,num)
    print(list(ret))
  3. 如下,每个小字典的name对应股票名字,shares对应多少股,price对应股票的价格

    portfolio = [
        {'name': 'IBM', 'shares': 100, 'price': 91.1},
        {'name': 'AAPL', 'shares': 50, 'price': 543.22},
        {'name': 'FB', 'shares': 200, 'price': 21.09},
        {'name': 'HPQ', 'shares': 35, 'price': 31.75},
        {'name': 'YHOO', 'shares': 45, 'price': 16.35},
        {'name': 'ACME', 'shares': 75, 'price': 115.65}
    ]

    计算购买每支股票的总价,用filter过滤出,单价大于100的股票有哪些?

f = filter(lambda d:d['price']>=100,portfolio)
  print(list(f))

1、请分别介绍文件操作中不同的打开方式之间的区别:

r    
rb    
r+    
rb+    
w    
wb    
w+    
wb+    
a    
ab    
a+    
ab+


2、有列表 li = ['alex', 'egon', 'smith', 'pizza', 'alen'], 请将以字母“a”开头的元素的首字母改为大写字母;

 

li = ['alex', 'egon', 'smith', 'pizza', 'alen']
li_new = []
for i in li:
    if i.startswith('a'):
        li_new.append(i.capitalize())
    else:
        li_new.append(i)
print(li_new)

for i in range(len(li)):
    if li[i][0] == 'a':
        li[i] = li[i].capitalize()
    else:
        continue
print(li)

3、有如下程序, 请给出两次调用show_num函数的执行结果,并说明为什么:

num = 20
def show_num(x=num):
    print(x)
show_num()
num = 30
show_num()

两次都是20;

如果函数收到的是一个不可变对象(比如数字、字符或者元组)的引用,就不能直接修改原始对象,相当于通过“传值’来传递对象,
此时如果想改变这些变量的值,可以将这些变量申明为全局变量。

4、有列表 li = ['alex', 'egon', 'smith', 'pizza', 'alen'], 请以列表中每个元素的第二个字母倒序排序;

li = ['alex', 'egon', 'smith', 'pizza', 'alen']
print(sorted(li, key=lambda x: x[1], reverse=True))

输出

['smith', 'alex', 'alen', 'pizza', 'egon']

5、有名为poetry.txt的文件,其内容如下,请删除第三行;

   昔人已乘黄鹤去,此地空余黄鹤楼。
   黄鹤一去不复返,白云千载空悠悠。
   晴川历历汉阳树,芳草萋萋鹦鹉洲。
   日暮乡关何处是?烟波江上使人愁。
  方法一:
  import os
  p = 'poetry.txt'
  file = open(p,'r',encoding='utf-8')
  print(file)
  pnew = '%s.new'%p
  filenew = open(pnew,'w',encoding='utf-8')
  str1 = '晴川历历汉阳树,芳草萋萋鹦鹉洲。'
  for i in file:
      if str1 in i:
          i = ''
          filenew.write(i)
      else:
          filenew.write(i)
  file.close()
  filenew.close()
  os.replace(pnew,p)

  方法二:逐行读取文件
  import os
  f1=open('poetry.txt', 'r',encoding='utf-8')

  str='晴川历历汉阳树,芳草萋萋鹦鹉洲。'
  with open('poetry1.txt', 'w', encoding='utf-8') as f2:
      ff1='poetry.txt'
      ff2='poetry1.txt'
      for line in f1:
          if str in line:
              line=''
              f2.write(line)

          else:
              f2.write(line)
  f1.close()
  f2.close()
  os.replace(ff2,ff1)

6、有名为username.txt的文件,其内容格式如下,写一个程序,判断该文件中是否存在"alex", 如果没有,则将字符串"alex"添加到该文件末尾,否则提示用户该用户已存在;

   pizza
   alex
   egon
with open('username.txt','r+',encoding='utf-8') as f:
    str1 = 'alexx'
    i = f.read()
    print(i)
    if str1 in i:
        print("the user already exist in")
    else:
        f.write('\nalexx')

7、有名为user_info.txt的文件,其内容格式如下,写一个程序,删除id为100003的行;

   pizza,100001
   alex, 100002
   egon, 100003
import os
  a = 'user_info.txt'
  b = 'user_info1.txt'
  with open(a,'r',encoding='utf-8') as f:
      with open(b, 'w', encoding='utf-8') as f2:
          for i in f:
              if '100003' in i:
                  pass
              else:
                  f2.write(i)
  os.replace(b,a)

8、有名为user_info.txt的文件,其内容格式如下,写一个程序,将id为100002的用户名修改为alex li

   pizza,100001
   alex, 100002
   egon, 100003
file = 'user_info.txt'
  old_str = '100002'
  new_str = 'alex, 100002'
  file_data=''
  with open(file,'r',encoding='utf-8') as f1:

      for line in f1:
          if old_str in line:
              line =new_str
          file_data +=line

          with open(file,'w',encoding='utf-8') as f1:
              f1.write(file_data)

9、写一个计算每个程序执行时间的装饰器;

 import time
  def timer(func):
      def wrapper(*args,**kwargs):
          start_time = time.time()
          func(*args)
          stop_time = time.time()
          print(stop_time-start_time)
      return wrapper

  @timer
  def sayhi():
      print("hello word")

  sayhi()

10、lambda是什么?请说说你曾在什么场景下使用lambda?

lambda函数就是可以接受任意多个参数(包括可选参数)并且返回单个表达式值得函数
    好处:
        1.lambda函数比较轻便,即用即扔,适合完成只在一处使用的简单功能
        2.匿名函数,一般用来给filter,map这样的函数式编程服务
        3.作为回调函数,传递给某些应用,比如消息处理

11、题目:写一个摇骰子游戏,要求用户压大小,赔率一赔一。

要求:三个骰子,摇大小,每次打印摇骰子数

import random

def roll_dice(numbers=3, points=None):
    """
     定义骰子,循环三次
    :param numbers:
    :param points:
    :return:
    """

    print('----- 摇骰子 -----')
    if points is None:
        points = []
    while numbers > 0:
        point = random.randrange(1, 7)
        points.append(point)
        numbers -= 1
    return points

def roll_result(total):
    """
    定义大小,三个大或者一个小两个大。三个小或者两个小一个大
    :param total:
    :return:
    """

    is_big = 11 <= total <= 18
    is_small = 3 <= total <= 10
    if is_big:
        return "big"
    elif is_small:
        return "small"

def start_game():
    your_money = 1000
    while your_money > 0:
        print('----- 游戏开始 -----')
        choices = ["", ""]
        your_choice = input("请下注, 大 or 小")
        your_bet = input("下注金额:")
        if your_choice in choices:
            points = roll_dice()
            total = sum(points)
            you_win = your_choice == roll_result(total)
            if you_win:
                your_money = your_money + int(your_bet)
                print("骰子点数", points)
                print("恭喜, 你赢了%s元, 你现在的本金%s 元" % (your_bet, your_money + int(your_bet)))
            else:
                your_money = your_money - int(your_bet)
                print("骰子点数", points)
                print("很遗憾, 你输了%s元, 你现在的本金%s 元" % (your_bet, your_money - int(your_bet)))
        else:
            print('格式有误,请重新输入')
    else:
        print("game over")

start_game()

猜你喜欢

转载自www.cnblogs.com/shengyang17/p/8586502.html