python编程练习:漏洞百出的四则运算器

在拜读到《python简明教程》最后一张“接下来学习什么”到时候,发现都是图形工具了,并且声称如果熟练掌握了前面章节,能够编写大多数程序= =!好吧,我一直在看书籍,还没有编写任何程序!那岂不是都不知道自己有没有掌握到,于是就练练手,想到初学者就是写写计算器、通讯录/图书管理系统,那我就先写一个简单的计算器吧,很多内置函数还不知道或者不熟练,所以还是花了快两个小时才憋出来这么一小段代码,以此记录,等我去学习学习别人更好的编写方法再回来更新,以供有缘看到的python学习者们共同学习。

import sys


def homepage():
    print('welcome to use the calculator\n'
          'please input what you want to calculate in the right way(like this:2+1 or 4*2)'
          )
    x = input("input:")
    calculate(x)


def calculate(a):
    if '+' in a or '-' in a or '*' in a or '/' in a:  # 判断是否有算术符号
        print(eval(a))
        print("would u like to exit or calculate again?")
        print("1.exit 2.calculate again")
        choice = input("chose ur number:")              # 是否继续计算
        if choice == '1':
            sys.exit()
        elif choice == '2':
            homepage()
        else:
            print('wrong input and process is exited')
            sys.exit()
    else:
        print('wrong input')


homepage()

 

posted @ 2017-12-11 21:21  opw3n  阅读(527)  评论(0编辑  收藏  举报