Python Basic Learning if statement

Source: Internet
Author: User
The If statement checks to determine the current condition and executes the appropriate action.

1 if a in a:2     if a condition: 3     Execute command else:5     execute command 7 If judging condition can also be abbreviated 8 if X:9     print (' True ')

Evaluates to TRUE if X is not a 0 value, a non-empty string, a non-empty list, and so on, otherwise false

4.1-piece test (conditional judgment)

1. The core of each if statement is a condition that evaluates to TRUE or FALSE, which is called a conditional test .

2.Python determines whether the following code is executed based on the value of the condition test, true or false, and if the IF statement evaluates to TRUE, executes the following code and evaluates to False to ignore the following code.

3. In Python, anything that is not a 0,null or an empty object is true.

4.2 Checking for equality

1.Python comparison size is case sensitive.

2.! = denotes unequal, exclamation point indicates no, can compare numbers, characters.

4.2.1 Checking multiple conditions

1. Use the keyword and connect, both satisfy to true, one does not satisfy all is false. To improve readability, each test can be written in ().

2. Use the keyword or Connect, satisfy one is true, is not satisfied is false.

4.2.2 checks if a specific value is included in the list

1. Use the keyword in to determine the inclusion relationship.

2. Use the keyword not in to determine that the relationship is not included.

4.2.3 Boolean expression

1. The Boolean expression is the alias of the conditional test, and the result is either true or false. A Boolean value is exactly the same as a Boolean algebra, with a Boolean value of only true, false two, or true, or false, in Python, which can be used to denote a Boolean value directly with True and False ( note case )

Boolean values can be operated with and, or, and not. Boolean operator.

1.True and True

True

2.True or False

True

3.not True

False

4.3IF statements

1. Simple if statement, one test, one operation, attention indent, and colon.

2.if-else statement a condition test, 2 operations.

3.IF-ELIF-ELSE structure Multi-conditional test, ELIF is the abbreviation of else if, can have more than one elif.

If < condition judgment 1>:

< Executive 1>

Elif < condition judgment 2>:

< Executive 2>

Elif < condition judgment 3>:

< Executive 3>

Else

< Executive 4>

4.if statement execution has a characteristic, it is to judge from the top, if in a certain judgment is true, the judgment corresponding to the execution of the statement, will ignore the remaining elif and else.

5. You can omit else and replace with elif to avoid introducing more error messages.

6. Syntax format = =, >=, and <= add a space on each side of the comparison operator, for example, if age < 4: is better than if age<4: OK.

5. Dictionaries

Python built-in dictionary: dict support, Dict full name dictionary, in other languages also known as map, using key-value (Key-value) storage, with a very fast search speed.

Features: unordered, Dictionary is Dynamic Data, dictionaries are composed of {}, separated by semicolons. The dictionary contains keys and values, which correspond to each other. The value associated with the key can be a number, a string, a list, or even a dictionary, which can be used as a value in the dictionary for any Python object. It is important to use dict correctly, and the first thing to keep in mind is that the dict key must be an immutable object.

Set

1.1. Set is similar to Dict and is also a collection of key sets, but does not store value. because key cannot be duplicated, there is no duplicate key in set.

1.2. Set can be regarded as a set of unordered and non-repeating elements in mathematical sense, so that two sets can do the intersection of mathematical meanings, and the intersection of:&. | and set;

The only difference between 1.3. Set and Dict is that it does not store the corresponding value, but the set principle is the same as the dict, so it is also not possible to put mutable objects, because there is no way to tell if two mutable objects are equal, and there is no guarantee that there will be no duplicate elements inside the set. Try putting the list in set to see if it will give an error.

1.4. The add element can be added to the set via the Add (key) method and can be added repeatedly, but will not be effective.

1.5. You can delete an element by using the Remove (key) method.

List and dict comparison

Compared with list, Dict has the following features:

The speed of finding and inserting is very fast and will not slow with the increase of key;

It takes a lot of memory, and it wastes a lot of memory.

And the list is the opposite:

The time to find and insert increases as the element increases;

Small footprint and little wasted memory.

So, Dict is a way of exchanging space for time.

5.1 Accessing the value of a dictionary

1. Key-Value access

Knowing that the key value can access the value:

Alien_0 = {' Color ': ' green ', ' Points ': 5}

To avoid a key that does not exist, there are two ways to determine whether a key exists by using in:

' Thomas ' in D

False

2.get method

The second is the get method provided by Dict, if key does not exist, you can return none, or the value you specified:

D.get (' Thomas ')

D.get (' Thomas ',-1) #在d中不存在 ' Thomas ', return-1

-1

>>> picnicitems = {' Apples ': 5, ' Cups ': 2}

>>> ' I am bringing ' + str (picnicitems.get (' cups ', 0)) + ' cups. '

' I am bringing 2 cups. '

>>> ' I am bringing ' + str (picnicitems.get (' eggs ', 0)) + ' eggs. '

' I am bringing 0 eggs.

Note: When none is returned, the interactive command line of Python does not display the results.

3.setdefault () method

The SetDefault () method provides a way to do this in one line. The first argument passed to the method, which is the key to check. The second parameter is the value to set if the key does not exist. If the key does exist, the method returns the value of the key.

>>> spam = {' name ': ' Pooka ', ' Age ': 5}

>>> spam.setdefault (' Color ', ' black ') #键不存在, return ' black '

' Black '

4.pprint Module

To import the Pprint module, you can use the Pprint () and Pformat () functions, which will "pretty print" a dictionary of words.

Pprint.pprint (Somedictionaryvalue)

Print (Pprint.pformat (somedictionaryvalue))

5.2 Adding keys and values

A dictionary is a dynamic data that can be added to a key and value at any time, by adding data through key

Alien_0 = {' Color ': ' green ', ' Points ': 5}

alien_0[' x_position '] = 0

alien_0[' y_position '] = 25

Print (ALIEN_0)

5.3 Deleting keys and values

1. To delete a key, using the Pop (key) method, the corresponding value is also removed from the dict:

D.pop (' Bob ')

75

2. Use Del

Del alien_0[' points ']

5.4 Traversing the dictionary item ()

The Python dictionary (Dictionary) items () function returns an array of traversed (key, value) tuples in a list.

For key, value in User_0.items ():

Actual

For name, language in Favorite_languages.items ():

Simple variable Name:

For K, V in User_0.items ()

Note that the return order of key-value pairs is different from the stored order, even when the dictionary is traversed. Python does not care about the order in which key-value pairs are stored, but only the association between keys and values.

Judging an object is an iterative object, the method is judged by the iterable type of the collections module;

>>> from collections Import iterable

>>> isinstance (' abc ', iterable) # whether STR can iterate

Python's built-in enumerate function can turn a list into an index-element pair so that both the index and the element itself can be iterated in the For loop.

Use the built-in isinstance function to determine if a variable is a string.

5.4.1 Traverse Dictionary All keys (for loop)

There are two types of Python loops, one is the for...in loop, and each of the elements in the list or tuple is iterated in turn to see an example:

For name in Favorite_languages.keys ():

When you traverse a dictionary, all keys are traversed by default, so if you replace the for name in Favorite_languages.keys (): With the for name in Favorite_languages:, the output will not change. If you explicitly use the method keys () to make the code easier to understand, you can choose to do so, but omit it if you want.

5.4.2 to iterate through all the keys in the dictionary sequentially

Sorted ()

Use the function sorted () to get a copy of the list of keys arranged in a particular order.

Sort by first letter

One way to do this is to sort the returned keys in the For loop. To do this, you can use the function sorted () to get a copy of the list of keys in a particular order.

5.4.3 iterating through all the values in the dictionary

VALUES ()

Use the method values () , which returns a list of values without any keys.

For language in Favorite_languages.values ():

To reject duplicates, set set ()is used. A collection is similar to a list, but each element must be unique:

For language in Set (Favorite_languages.values ()):

5.5 Nesting

You can also use a two-layer loop to generate a full array.

5.5.1 Dictionary List

Alien_0 = {' Color ': ' green ', ' Points ': 5}

alien_1 = {' Color ': ' Yellow ', ' Points ': 10}

alien_2 = {' Color ': ' Red ', ' points ': 15}

Aliens = [Alien_0, alien_1, alien_2]

5.5.2 storing dictionaries in a dictionary

Nested dictionaries in dictionaries

5.6 Exit loop (Break)

In a loop, the break statement can exit the loop prematurely. This statement must usually be used with the IF statement.

5.7continue

In the loop process, you can also skip the current cycle through the Continue statement, and start the next loop directly. This statement must usually be used with the IF statement.

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.