Python-implemented simple arithmetic game instance

Source: Internet
Author: User

Python-implemented simple arithmetic game instance

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

#! /Usr/bin/env python

From operator import add, sub

From random import randint, choice

Ops = {'+': add, '-': sub}

# Define a dictionary

MAXTRIES = 2

Def doprob ():

Op = choice ('+ -')

# Use choice to randomly select operators from '+ -'

Nums = [randint (1, 10) for I in range (2)]

# Use randint () to randomly generate a number ranging from 1 to 10. Use range (2) twice)

Nums. sort (reverse = True)

# Sort in ascending order

Ans = ops [op] (* nums)

# Using Functions

Pr = '% d % s % d =' % (nums [0], op, nums [1])

Oops = 0

# Oops is used to calculate the failure test. Answers are automatically given three times.

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

Except T (KeyboardInterrupt, EOFError, ValueError ):

Print 'invalidipnut... try again'

Def main ():

While True:

Doprob ()

Try:

Opt = raw_input ('again? [Y] '). lower ()

If opt and opt [0] = 'N ':

Break

Except T (KeyboardInterrupt, EOFError ):

Break

If _ name _ = '_ main __':

Main ()

The running result is as follows:

?

1

2

3

4

5

6

7

8

9

8-1 = 7

Correct

Again? [Y] y

7-1 = 6

Correct

Again? [Y] y

9 + 4 = 0

Incorrect... try again

9 + 4 =

I hope this article will help you with Python programming.

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.