Python-implemented simple arithmetic game instances and python arithmetic instances

Source: Internet
Author: User

Python-implemented simple arithmetic game instances and python arithmetic instances

This example describes a simple arithmetic game implemented by Python. Share it with you for your reference. The specific implementation method is as follows:

#! /Usr/bin/env pythonfrom operator import add, sub from random import randint, choiceops = {'+': add ,'-': sub} # define a dictionary MAXTRIES = 2 def doprob (): op = choice ('+ -') # Use choice to randomly select the operator nums = [randint () for I in range (2)] From '+-' # Use randint) generate a random number ranging from 1 to 10, and use range (2) nums twice. sort (reverse = True) # sort by ascending order ans = ops [op] (* nums) # Use the function pr = '% d % s % d =' % (nums [0], op, nums [1]) oops = 0 # oops for failure testing, when three times from While True: try: if int (raw_input (pr) = ans: print 'correct' break if oops = MAXTRIES: print 'answer \ n % s % d' % (pr, ans) break else: print 'encrect... try again 'oops + = 1 hour T (KeyboardInterrupt, EOFError, ValueError): print 'invalid ipnut... try again 'def main (): while True: doprob () try: opt = raw_input ('again? [Y] '). lower () if opt and opt [0] = 'N': break t (KeyboardInterrupt, EOFError): breakif _ name _ = '_ main __': main ()

The running result is as follows:

8 - 1 = 7correctAgain? [y]y7 - 1 = 6correctAgain? [y]y9 + 4 = 0incorrect... try again9 + 4 = 

I hope this article will help you with Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.