In Python for loop if loop break

Source: Internet
Author: User

The most basic syntax format in Python is probably indentation. Common loops in Python: for loops, if loops. A little game illustrates the use of for,if, break.

Guess number game:

1. The system generates a random number within 20

2. The player has 6 chances to guess, each guess will have feedback results, guess big, guess small or guessed right-end

3.6 Chances, guess right, player wins

4, 6 chances, no guess, system wins.

The code is as follows:

[email protected] python-scripts]# cat 12.py
#!/usr/bin/python
#coding =utf-8
Import Random
SJS = Random.randint (1,20)//random number generated
Print SjS//printing random number
For I in Xrange (1,7)://6 chance Value
num = Int (raw_input ("Please input a number[1-20]:"))
If num > SJS:
Print "Guess big, and%s chance"% (6-i)
Elif Num < sjs:
Print "Guess small, and%s chance"% (6-i)
elif num = = SjS:
Print "Guess right, you win, and%s chance"% (6-i)
Break//If it's right, jump out of the For loop

The code runs as follows:

[[email protected] python-scripts]# python 12.py
1//generated random number
Please input a number[1-20]: 10
Guess big, 5 more chances.
Please input a number[1-20]: 9
Guess big, 4 more chances.
Please input a number[1-20]: 5
Guess big, 3 more chances.
Please input a number[1-20]: 2
Guess big, 2 more chances.
Please input a number[1-20]: 1
Guess right, you win, you got 1 more chances.

In Python for loop if loop break

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.