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