Python basic 5 If-else process judgment, for loop and while loop

Source: Internet
Author: User



The main contents of this section:


    1. If-else Process Judgment
    2. For loop
    3. While loop
    4. Reference pages
If-else process Judgment If statement overview


Computers can do a lot of automated tasks, because it can make their own conditions to judge.



For example, to enter user age, print different content according to age, in a Python program, you can use the IF statement:


 
age = 20
if age >= 18:
    print ‘your age is‘, age
    print ‘adult‘
print ‘END‘
Attention:
    1. The indentation rules for Python code. Code with the same indentation is treated as a block of code, with 3, 4 lines of print statements constituting a block of code (but excluding print on line 5th). If the IF statement evaluates to True, the code block is executed.

    2. Indent please strictly follow Python's customary notation: 4 spaces, do not use tab, do not Mix tab and space, otherwise it is easy to cause syntax errors due to indentation.

    3. The IF statement is followed by an expression, and then begins with: Represents the code block.

    4. If you hit the code in a Python interactive environment, also pay special attention to indentation, and exit indentation requires more than one line of return:

    5. Not every if statement has an else.

    6. If...else ... The logic is either "or", or it meets the condition 1, or the condition 2. Else there is a ":" Behind it.

If statement scenario example scenario one, user login verification
#! / usr / bin / env python
#-*-coding: utf-8-*-
# Author: Cathy Wu

# Prompt for username and password
  
# Verify username and password
# If wrong, output username or password is wrong
# If successful, then output Welcome, XXX!
 
#import getpass
_name = "Cathy"
_password = "123456"

username = input ("username:")
password = input ("password")
#password = getpass.getpass ("password")

if username == _name and password == _password:
     print ("welcome user {name} login ...". format (name = username))
else:
     print ("invalid username or password!") 


The results of the operation are as follows:


 
username:cathywu
password123
invalid username or password! Process finished with exit code 0
Scenario two, Guess age game


Set your age in the program, and then start the program to let the user guess, after the user input, according to his input prompts the user to enter the correct, if the error, the hint is guessed big or small


 
my_age = 28
 
user_input = int(input("input your guess num:")) if user_input == my_age: print("Congratulations, you got it !")
elif user_input < my_age: print("think bigger!") else: print("think smaller!")


Outer variables, which can be used by the inner layer code.



The inner layer variable should not be used by the outer code.


For loop


A list or tuple can represent an ordered set. What if we want to access each element of a list in turn? such as list:


 
 
L = [‘Adam‘, ‘Lisa‘, ‘Bart‘]
print L[0]
print L[1]
print L[2]


If the list contains only a few elements, it is OK to write, and if the list contains 10,000 elements, we cannot write 10,000 lines of print.



This is where the loop comes in handy.



The python for loop can then iterate over each element of the list or tuple in turn:


L = [‘Adam‘, ‘Lisa‘, ‘Bart‘]for name in L: print name
Attention:


Name this variable is defined in the For loop, meaning that each element in the list is taken out in turn, the element is assigned to name, and then the For loop body (which is the indented block of code) is executed.



This makes it very easy to traverse a list or tuple.


Example of a scene example


After the class exam, the teacher to statistical average results, 4 students are known to list the results are as follows:



L = [75, 92, 59, 68]



Please use the For loop to calculate the average score.


L = [75, 92, 59, 68]sum = 0.0for i in L: sum = sum + iprint sum / 4
Example Two


Print 0,2,4,6,8.


for i in range(0,10,2): print("loop",i)
While loop


Another loop that differs from the For loop is the while loop, which does not iterate over the elements of the list or tuple, but rather determines whether the loop ends with an expression.



For example, to print an integer no greater than N from 0:


10x = 0while x < N:    print x    x = x + 1


The while loop first evaluates x < N, if true, executes the block of code for the loop body, otherwise, exits the loop.



In the loop, x = x + 1 causes X to increase and eventually exits the loop because X < N is not true.


Attention


Without this statement, the while loop always evaluates to True for x < N, it loops indefinitely and becomes a dead loop, so pay special attention to the exit condition of the while loop.


Examples of scenarios


Use the while loop to calculate an odd number of 100 or less.


 
sum = 0
x = 1 while x < 100: sum = sum + x
    x = x+2 print sum
Break exit loop and Continue continue loop break exit loop


When using a For loop or while loop, you can use the break statement if you want to exit the loop directly inside the loop.


Example One


For example, to calculate integers from 1 to 100, we use while to implement:


 
sum = 0
x = 1 while True: sum = sum + x
    x = x + 1 if x > 100: break print sum


At first glance, while True is a dead loop, but in the loop, we also determine that x > 100 pieces are set up, using the break statement to exit the loop, which can also achieve the end of the loop.


Example Two


Use the while True infinite loop with the break statement to calculate 1 + 2 + 4 + 8 + 16 + ... The first 20 items of the and.


 
sum = 0
x = 1
n = 1
while True:
    if n > 20:
        break
    sum = sum + x
    x= x * 2
    n= n + 1
print (sum)
Continue continue circulation


During the loop, you can use break to exit the current loop, and you can use continue to skip the subsequent loop code and continue the next loop.



Let's say we've written the code that calculates the average score using the For loop:


 
 
L = [75, 98, 59, 81, 66, 43, 69, 85]
sum = 0.0
n = 0
for x in L:
    sum = sum + x
    n = n + 1
print (sum / n)


Now the teacher just want to count the average of passing scores, it is necessary to cut off the score of x < 60, then, using continue, can be done when x < 60, do not continue to execute the loop body follow-up code, directly into the next cycle:


 
 
for x in L:
    if x < 60:
        continue
    sum = sum + x
    n = n + 1
Example


Transformation of the existing while loop of calculation 0-100, by adding continue statements, so that only odd-numbered and:


 
sum = 0
x = 1 while True: sum = sum + x
    x = x + 1 if x > 100: break print sum


The following changes are followed:


 
sum = 0
x = 0 while True:
    x = x + 1 if x > 100: break if x % 2 == 0: continue
    sum = sum + x
     
print (sum)
Reference pages


http://www.imooc.com/learn/177



Http://www.cnblogs.com/alex3714/articles/5465198.html



Python basic 5 If-else process judgment, for loop and while loop


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.