Python BASICS (3) --- process control, python ---

Source: Internet
Author: User

Python BASICS (3) --- process control, python ---

Process Control

What is different from the C language is that the python process control code block is not expressed in braces ({}), but forced indentation. The indentation must be consistent. It is recommended that four spaces be used, we do not recommend that you use tabs for indentation. First, tabs of different systems occupy different widths and are messy. Second, python requires that the indentation at the same level be consistent, so sometimes it looks like alignment l, but some are spaces and some are tab keys, making it difficult to troubleshoot. In addition, the statements for condition judgment do not need to be included in (), but the condition statements are followed:

1. Condition judgment-if statement

Conditional judgment is to judge before executing a code segment. If a code block meets the condition

For example, enter the age. If the age is less than 18, tell too yong toosimple!

Age = 17if age <18; print ('too yong too simple') # Run this Code if the returned value is True.
View Code

You can also add an else statement after if to tell the Python interpreter that if the code segment does not meet the execution condition (False is returned), for example, if the age is not less than 18 years old, just tell him do you marry me?

Age = 19if age <18: print ('too young too simple') else: print ('Do you marry me? ') # Run this Code if the returned value is False.
View Code

Because Python does not have a case statement, the condition branch can be nested like else if. For the sake of technology, elif can be abbreviated as elif. For example, if a condition is over 30 years old, tell him too old!

age = 33if age < 18:    print('too young too simple')elif age > 32:    print('too old!')else:    print('do you marry me?')
View Code

Note: Keep indentation all the time. Do not forget the colon:

 

Application Example:

Now we have such a need to design a lucky number quiz game, which allows users to guess your lucky number by entering it on the console, if the number entered by the user is larger than your lucky number, the prompt is smaller. If the number entered is smaller than your lucky number, the prompt is larger. if you guess it, the prompt is Bingo.

''' @ Author: xiaocaoDescription: Guess lucky number 1. If the number to be guessed is larger than lucky number, the prompt is smaller. 2. If the number to be guessed is smaller than lucky number, the prompt is bigger than 3. if the values are equal, the prompt is Bingo ''' if _ name _ = '_ main __': # define lucky number lucky_num = 5 # obtain the user input's guess lucky number lucky_num_input = int (input ("Enter lucky number (1-10 ):")) # determine the user-entered guess lucky number if lucky_num_input> lucky_num: # The input value is larger than the luky number print ("a little smaller") elif lucky_num_input <lucky_num: # print ("larger") else: # correct print ("Bingo ")
View Code

 

 

2. while loop: if the condition is met (True is returned by the Condition Statement), a code segment is executed cyclically.

For example, our program allows the user to input and process (for example, the menu Program), and exit the program if the user inputs q.

Choose = ''while choose! = 'Q': choose = input ('Enter the food you want and enter q to exit ')

Common keywords in the loop: break, continue, else:

In a loop, the keyword break indicates that the loop is exited, and continue indicates that the current loop is exited and the next loop is continued. The statements after the continue are not executed, else In else and if indicates the code segment executed when the condition is not met (that is, the normal exit loop is not forced to exit with break ).

The application example is the game that just guessed lucky numbers. Before that, it just enters a program and exits. It is unfriendly to continue guessing and re-run the program, we now allow the user to run the program three times at a time, and exit the program if the three guesses are incorrect.

''' @ Author: xiaocaoDescription: Guess lucky number 1. If the number to be guessed is larger than lucky number, the prompt is smaller. 2. If the number to be guessed is smaller than lucky number, tip: bigger 3. If the values are equal, the system prompts Bingo 4. If there is no guess, continue the loop until the guess is 5 and the limit is 3. If there is no guess, the system prompts three guesses, game termination ''' if _ name _ = '_ main _': # define luncky number lucky_num = 5 # define guess_count, calculate the number of guesses guess_count = 0 while guess_count <3: # obtain the user-input guess lucky number lucky_num_input = int (input ("Enter lucky number :")) # determine the lucky number of user input. if lucky_num_input> lucky_n Um: # print ("a little smaller") elif lucky_num_input <lucky_num: # print ("a little larger") else: # The entered and lucky number are equal print ("Bingo") # exit loop break # Count Plus 1 guess_count + = 1 else: # I guessed three cycles and exited print normally ("three times without guessing, the game is over! ")
View Code

3. for Loop

In Python, for loops often use in serialized objects (such as lists and tuples) for traversal. We haven't mentioned list tuples yet. We can use strings (strings are also serialized objects, each element can be traversed, that is, every character in the string). If we have a string 'abc', We need to output each character in the string separately. You can do this:

for i in 'ABC':    print(i)

If we need to be like C language for (I = 1; I <3; I ++), we can use the built-in method range (n) to generate a (, 2... n-1). For example, we need to specify the number of cycles (print 0-9 digits). This can be done:

for i in range(10):    print(i)

The for loop of Python can also use break, continue, and else. The usage is the same as that of the while loop.

In the application example, we change the game that guesses lucky numbers into a for loop.

''' @ Author: xiaocaofor cyclically implements Description: Guess lucky number 1. If the number to be guessed is larger than lucky number, the prompt is smaller. 2. If the number to be guessed is smaller than lucky number, tip: bigger 3. If the values are equal, the system prompts Bingo 4. If there is no guess, continue the loop until the guess is 5 and the limit is 3. If there is no guess, the system prompts three guesses, when the game ends, ''' if _ name _ = '_ main _': # define lucky number lucky_num = 5 for guess_count in range (3 ): # obtain the user-input lucky number lucky_num_input = int (input ("Enter lucky number:") # determine the user-input guess lucky number if lucky_num_input> lucky_num: # enter a pri larger than the lucky number Nt ("a little smaller") elif lucky_num_input <lucky_num: # the input is smaller than the luky number print ("a little larger") else: # print ("Binge") # exit loop break else: # Guess three cycles exit print ("three times no guess, the game is over! ")
View Code

 

Conclusion: although both the while and for loops can implement loops, they have their own characteristics and are chosen based on actual needs, for example, if the number of cycles is not limited, it is convenient to exit the loop and use the while loop as long as the conditions are met. It is more convenient to use the for loop to limit the number of cycles or to traverse the sequence object.

 

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.