Python growth path article 1 (4) _ if, for, while Condition Statement, python_if

Source: Internet
Author: User
Tags bitwise operators

Python growth path article 1 (4) _ if, for, while Condition Statement, python_if

With the above basic foundation, we have already written a few small exercises, and you will certainly have a lot of dissatisfaction. For example, why does one query quit? The following is a Learning Condition Statement.

 

I. the plus sign of all evil

In the past, if we had to add variables to print, we used + as the connection, but this was not good.

When the plus sign is used, a new memory address will be opened in the memory to store new content. The disadvantage is that the memory consumption is increased.

① Built-in placeholder

Python supports formatting string output. Although this may use a very complex expression, the most basic usage is to insert a value into a string with the string format character % s. In Python, string formatting uses the same syntax as the sprintf function in C.

For example, in the above example, we use another method:

>>> A = "abc"
>>> Print ("sssss % s" % ())
Sssssabc

Here we mainly add one more % s. Here, % s is called a placeholder. for different data types, we have many placeholders.

② Custom placeholder format Function

aa = "dsadsa{ss}" 
print(aa.format(ss='ccccc'))
dsadsaccccc
In print, ss = 'ccccccc' can be replaced with variables so that you do not need to consider the data type.
2. Replace the values of two variables

In some algorithms, we need to replace the variable values.

Method 1:

>>> A = 1
>>> B = 2

>>> C =
>>> A = B
>>> B = c

>>> Print (a, B)
2 1

In this way, we use another variable to temporarily transfer the value of a so that we have an extra variable that looks less advanced. Is there any other way?

Method 2:

>>> A = 1
>>> B = 2
>>> Print (a, B)
1 2
>>> A, B = B,
>>> Print (a, B)
2 1

Is it fun?

Iii. Boolean expression

A boolean expression is used to determine whether the expression is True or False. The computer code is expressed by 1 and 0. Therefore, 1 indicates whether the expression is True or not, and 0 indicates whether the expression is False or not.

Let's take a look at the following example:

From the example below, we can see that when 1 is equal to True, the return value is True, that is, True. When 0 is equal to True, the return value is false, that is, false, if 0 is false, True is returned.

>>> 1 = True
True
>>> 0 = True
False
>>> 0 = False
True

Example 2: The following example shows that when the value is null, the Boolean expression is considered false.

>>> Bool ('')
False
>>> Bool ('A ')
True

 

IV. if statement

(1)The if statement in python is used for logical judgment like other languages.

Requirement (1 ):

If the input value is a, the output is welcome; otherwise, the output is tumble. xxx

Inpot = input ("Enter the name :")

If inpot = "":
Print ('Welcome: % s' % (inpot ))
Else:
Print ('tumble: % s' % (inpot ))
Requirement (2 ):

If the input value is a, the output is welcome. If the input value is B, the output is welcomed by the director. Otherwise, the output is tumble. xxx

Inpot = input ("Enter the name :")

If inpot = "":
Print ('Welcome: % s' % (inpot ))
Elif inpot = "B ":
Print ('Welcome to Director [% s] '% (inpot ))
Else:
Print ('tumble: % s' % (inpot ))

 

From the two examples above, we can see that python does not have the case in the shell script, but is changed to the elif in the if statement. In the if statement, we can only use the if statement instead of the else statement.

5. while Loop

Why does the while LOOP exist? Because we need to repeat things. For example, if we want to print 1-, we don't need print 1 print 2 ..... Print100 is a waste of code, so we can do this.

(1) while loop-Counter

X = 1 # first set the value of a variable to 1
While x <= 100: # Run the following code when x is less than or equal to 100
Print (x) # print the value of x
X = x + 1 # Add 1 to every cycle x. The first cycle is x (1) + 1 = 2, and the second is x (2) + 1 = 3.
Such statements are called counters.
(2) while endless loop
We know the truth in the Boolean expression. Here we can combine the while expression into an endless loop. Isn't the endless loop always running,
What should I do? The break provided by python can exit the current loop. Let's take a look at the previous exercises.
Exercise 1:
Requirements:Enter the employee name to query the employee's phone number and serial number. The program must be able to continue the query unless the user enters the exit command.
Python3.5 Environment
#!/usr/bin/env python
# -*- coding:utf-8 -*-
Address = {
'A ':{
'Number': '01 ',
'Phone': '000000'
},
'B ':{
'Number': '02 ',
'Phone': '000000'
},
'C ':{
'Number': '03 ',
'Phone': '000000'
}
}
While True:
Inpu = input ("Enter the user name to query :")
If inpu in address. keys (): # address. keys () indicates obtaining all keys of the dictionary)
Print ("current user: % s" % (inpu ))
Print ('user ID: % s' % (address [inpu] ['number'])
Print ('user phone: % s' % (address [inpu] ['phone'])
Elif inpu = "exit ":
Print ('Thank you for using goodbye ')
Break
Else:
Print ("the user you entered [% s] does not exist" % (inpu ))
Result:
6. for Loop

(1) first recognized for Loop

While statements are very flexible, but some specific conditions are very complicated to use while loops. For example, if you want to print the content in the list separately in a list, you can also use while statements, but it's not as simple as the for loop. let's compare it with a list.
A = ['A', 'B', 'C', 'D'] We use while and for to print each element in the list.
while:
A = ['A', 'B', 'C', 'D']
X = 0
While x <len (a): # The value of len (a) is 4, so the index of list a is from 0-3, so here x is smaller than len ()
Print (a [x])
X = x + 1
for:
a = ['a','b','c','d']
for i in a:
print(i)
After comparison, at least two lines of code are missing for the for loop.
In the for loop code, for I in a: indicates that I is taken from sequence a to sequence a, so the first loop I = a, the second I = B, and so on.
(2) range Function
Remember to print 1-in a while loop. here we can use the for plus range function:
For I in range (1,101): # Why do I write 1-101 here? Because of the features of the range function, if it is 1-, it will generate 1-99
Print (I) # So here is 1-101
The range function works in a way similar to a shard.
(3) for Loop dictionary
Note: The order of the dictionary elements is not defined. That is to say, when the dictionary key-value pairs generated by the for loop are unordered
Method 1:
A = {
"A": "aa ",
"B": "bb ",
"C": "cc"
}
For key in:
Print ('Welcome [% s], your information is (% s) '% (key, a [key])
Method 2:
A = {
"A": "aa ",
"B": "bb ",
"C": "cc"
}
For key, value in a. items ():
Print ('Welcome [% s], your information is (% s) '% (key, value ))

 

Result The second distribution uses the items function, which converts Dictionary a to ([('B', 'bb'), ('A', 'A '), ('C', 'cc')]) This structure is assigned to the key and value respectively.

7. jump out of the loop

(1) break, Jump out of the current loop as described earlier

(2) contiuneIt is generally used for the if statement, that is, it can be used without further judgment after entering the current judgment.

Example:

For I in range (1, 6 ):
If I = 3:
Print ('OK ')
Continue # When I is equal to 3, output OK and end this judgment, that is, do not execute else
Else:
Print (I)

Result: for I in range (1, 6 ):
If I = 3:
Print ('OK ')
Continue
Elif I = 4:
Pass
Else:
Print (I)

Result

8. Operation

Python has a lot of operations here recommended site: http://www.runoob.com/python/python-operators.html

PythonArithmetic Operators

PythonComparison Operators

PythonValue assignment operator

PythonBitwise operators

 

 

PythonLogical operators

PythonMember Operators

PythonIdentity Operators

PythonOperator priority

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.