Getting Started with Python applet 1

Source: Internet
Author: User

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

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.