Python basics learning if statement
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 |
if |
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' |
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 |
for name in favorite_languages.keys(): |
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 methodvalues() , which returns a list of values instead of Contains any key.
for language in favorite_languages.values():To eliminate duplicates, you can use the setset(). 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 listalien_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.7continueDuring 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
