Learn FISHC's Python 0 basic Introductory Section 4th, this time with Python's while Loop statement and conditional statement.
1. Small program for guessing numbers with a conditional statement
The program sets a number and the user enters a number to determine whether to guess the right.
temp=input("猜猜我心中的数字:")guess=int(temp)if guess==8: print("猜对!")else: print("猜错了!")print("游戏结束!")
2. Improvement Procedure 1
In the previous program, the user guessed wrong to rerun the program, nested while loop so that the user can always guess, know guess right. In addition, the number set by the system can not be static, but instead randomly generated.
import randomtemp = input("猜猜我心中的数字:")guess=int(temp)secret=random.randint(1,10)while guess!=secret: if (guess< secret): print("猜小了!") print("剩余机会次数:",i) else: print("猜大了!") print("剩余机会次数:", i) temp = input("猜下我心中的数字:") guess = int(temp) i = i - 1else: if(i>0): print("猜对!游戏结束!") else: print("你的机会用完!")
3. Improved Program 2 Limited User Opportunities
Now, users have only three chances to guess the numbers. We can modify the condition of the loop, when the user does not guess and the opportunity is not finished, the loop has been executed.
import randomtemp = input("猜猜我心中的数字:")guess = int(temp)secret = random.randint(1,10)i = 2while (guess!=secret)and(i): if (guess < secret): print("猜小了!") print("剩余机会次数:",i) else: print("猜大了!") print("剩余机会次数:", i) temp = input("猜下我心中的数字:") guess = int(temp) i = i - 1else: if(i>0): print("猜对!游戏结束!") else: print("你的机会用完!")
4. General language
In Python, while ... else executes an ELSE statement block when the loop condition is false.
The and logical operator in Python can concatenate arbitrary expressions together and get a Boolean type value.
Getting Started with Python applet 1