search
HomeBackend DevelopmentPython TutorialPython basics learning if statement

Python basics learning if statement

Jul 23, 2017 am 11:28 AM
pythonBaseSummarize

The If statement can check and determine the current conditions and perform corresponding measures.

1 if a in A:2     if a 条件:3     执行命令14   else:5       执行命令26 7 if判断条件还可以简写8 if x:9     print('True')

As long as x is a non-zero value, a non-empty string, a non-empty list, etc., it will be judged as True, otherwise it will be False

4.1 Conditional Test (Conditional Judgment)

1. The core of each if statement is the conditional judgment True or False. This expression is called Conditional Test.

2.Python determines whether to execute the following code based on the value of the conditional test, True or False. If the if statement is True, the following code will be executed. If it is False, the following code will be ignored.

3. In python, anything that is not 0, Null or an empty object is True.

4.2 Check for equality

1. Python compares sizes case-sensitive.

2.! = means not equal, the exclamation mark means No, can compare numbers and characters.

4.2.1 Check multiple conditions

1. Use the keyword and to connect, if both are satisfied, it will be True, if one is not satisfied, it will be False. To improve readability, write each test in ( ).

2. Use the keyword or to connect. If one is satisfied, it will be True, and if neither is satisfied, it will be False.

4.2.2 Check whether 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 whether there is a relationship.

4.2.3 Boolean expression

1. Boolean expression is an alias for conditional testing, and the result is True or False. The representation of Boolean values ​​and Boolean algebra is exactly the same. A Boolean value has only two values, True and False, either True or False. In Python, you can directly use True or False to represent Boolean values ​​(Please pay attention to the 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 statement

1. Simple if statement, a test , an operation, pay attention to indentation, and colon.

2.if-else statement A conditional test, 2 operations.

3.if-elif-else structure Multi-condition test, elif is the abbreviation of else if, and there can be multiple elifs.

4. If statement execution has a characteristic, it is judged from top to bottom. If a certain judgment is True, after the statement corresponding to the judgment is executed, the remaining elif and else will be ignored.

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

6. Syntax format: Add a space on both sides of comparison operators such as ==, >= and

5. Dictionary

Python has built-in dictionary: support for dict. The full name of dict is dictionary. It is also called map in other languages. It uses key-value (key-value) storage and has extremely Fast search speed.

Features: Unordered, the dictionary is dynamic data, the dictionary consists of { }, separated by semicolons. Dictionaries contain keys and values ​​in one-to-one correspondence. The value associated with a key can be a number, string, list, or even a dictionary. Any Python object can be used as a value in a dictionary. It is very important to use dict correctly. The first thing to remember is that the key of dict must be an immutable object.

set:

1.1. Set is similar to dict, it is also a collection of keys, but does not store value . Since keys cannot be repeated, there are no duplicate keys in the set.

1.2. A set can be regarded as a collection of unordered and non-repeating elements in the mathematical sense. Therefore, two sets can perform operations such as intersection and union in the mathematical sense: ⋂ | Union;

1.3. The only difference between set and dict is that the corresponding value is not stored. However, the principle of set is the same as that of dict. Therefore, variable objects cannot be placed because it is impossible to judge two variable objects. Whether they are equal or not, there is no guarantee that "there will be no duplicate elements" inside the set. Try putting the list into the set and see if you get an error.

1.4. You can add elements to the set through the add(key) method, and you can add them repeatedly, but it will have no effect.

1.5. Elements can be deleted through the remove(key) method.

Comparison between list and dict

Compared with list, dict has the following characteristics:

The search and insertion speed are extremely fast and will not change as the key increases. Slow;

It takes up a lot of memory and wastes a lot of memory.

On the contrary, list:

The time for searching and inserting increases as the number of elements increases;

It takes up little space and wastes very little memory.

So, dict is a way to trade space for time.

5.1 Access dictionary values

1. Key value access

You can access the value if you know the key value:

if :

elif :

elif :

else:

alien_0 = {'color': 'green', 'points': 5}

To avoid the error that the key does not exist, there are Two methods, one is to determine whether the key exists through in:

'Thomas' in d

False

2.get method

The second is the getmethod provided through dict. If the key does not exist, None can be returned. Or a value specified by yourself:

d.get('Thomas')

d.get('Thomas', -1) # 'Thomas' does not exist in d, returns -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: Python’s interactive command line does not display the results when None is returned.

3.setdefault() method

The setdefault() method provides a way to accomplish this in one line. The first parameter passed to this method is the key to check. The second parameter is the value to be set if the key does not exist. If the key does exist, the method returns the key's value.

##>>> spam = {'name': 'Pooka', 'age': 5}

>> ;> spam.setdefault('color', 'black') #The key does not exist, return 'black'

'black'

4.pprint module

Import the pprint module, and you can use the pprint() and pformat() functions, which will "pretty print" the words of a dictionary.

##pprint.pprint(someDictionaryValue)

5.2 Add keys and values

The dictionary is dynamic data, you can add keys and values ​​to it at any time, and add data through key

print(pprint.pformat(someDictionaryValue))

alien_0 = {'color': 'green', 'points': 5}

alien_0['x_position'] = 0

alien_0['y_position '] = 25

print(alien_0)

5.3 Delete keys and values ​​

1. To delete For a key, using the pop(key) method, the corresponding value will also be deleted from the dict:

d.pop('Bob')

75

2. Use del

del alien_0['points']

5.4 Traverse dictionary item()

Python Dictionary (Dictionary) items() function returns a traversable (key, value) tuple array as 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 even when traversing the dictionary, the return order of key-value pairs is different from the storage order. Python does not care about the storage order of key-value pairs, but only tracks the association between keys and values.

Judge whether an object is an iterable object by judging the Iterable type of the collections module;

##>>> from collections import Iterable

>>> isinstance('abc', Iterable) # Whether str is iterable

Python's built-in enumerate function You can turn a list into an index-element pair, so that you can iterate both the index and the element itself in a for loop.

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

5.4.1 Traverse all the keys in the dictionary (for loop)

There are two types of loops in Python. One is the for...in loop, which sequentially takes each item in the list or tuple. The elements are iterated out, see the example:

for name in favorite_languages.keys():

When traversing the dictionary, all keys will be traversed by default. Therefore, if you replace for name in favorite_languages.keys(): in the above code with for name in favorite_languages:, the output will remain unchanged. If using the keys() method explicitly makes the code easier to understand, you can choose to do so, but you can omit it if you prefer.

5.4.2 Traverse all keys in the dictionary in order

sorted()

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

Sort by first letter

One way is to sort the returned keys in a for loop. To do this, use the function sorted() to obtain a copy of the list of keys in a specific order.

5.4.3 Traverse all values ​​in the dictionary

values()

Use the method

values() , which returns a list of values ​​instead of Contains any key.

for language in favorite_languages.values():

To eliminate duplicates, you can use the set

set(). Sets are similar to lists, but each element must be unique:

for language in set(favorite_languages.values()):

5.5 Nesting

is okay Using a two-level loop, a full permutation can be generated.

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 Store dictionary in dictionary

Nested dictionary in dictionary

5.6 Exit the loop (break)

In the loop, the break statement can exit the loop early. This statement must usually be used with an if statement.

5.7continue

During the loop process, you can also use the continue statement to skip the current loop and start the next loop directly. This statement must usually be used with an if statement.

The above is the detailed content of Python basics learning if statement. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools