Introduction
Comparing to languages like C, Python's IF statement might be the simplest: There isn't even a single bracket in the statement.
The logical architecture is much simpler:
- ==, >=, <=, <, > comparison operators
- Manipulation of characters, numbers, and letters
- 'and' with 'or' multi-conditional comparison judgments
# and or judgement. (Can't use && and || operators in Python)
age_0 = 23
age_1 = 17
print(age_0 >= 21 and age_1 >= 21)
print(age_0 >= 21 or age_1 >= 21)
Output
False
True
'in' and 'not in' for list checking
topping = ['mushroom', 'pineapple']
if 'mushroom' in topping:
print('OK')
else:
print('No mushroom')
Output
OK
However, if you want to check whether an element is in an array in language like C (propose a number similar structure), this will be an extremely complicated operation to realize, because it's necessary to start from the data structure and determine the element type. Thus the judgment operation is a lot more complicated.
Multiple elif blocks
age = 8
if age < 3:
price = 0
elif age < 12:
price = 3
elif age < 18:
price = 5
else:
price = 10
print(price)
Output
3
Using the combination of list and 'if' operator to select
toppings = ['mushrooms', 'green peppers', 'onion', 'cheese', 'pineapple']
for topping in toppings:
if topping == 'green peppers':
print("No more green peppers.")
else:
print("OK, adding " + topping + ".")
print("Here is your pizza!")
Output
OK, adding mushrooms.
No more green peppers.
OK, adding onion.
OK, adding cheese.
OK, adding pineapple.
Here is your pizza!
Q: Does the list support value re-assignment operations in tuples (immutable after value assignment)?
A: The list is used internally in the tuple, although the tuple is immutable, but we can still mutate the list inside the tuple.
How to determine if the list is 'NULL'
From the perspective of the code, there are many ways to detect whether the list is 'NULL' or 'EMPTY', here are some examples such as the direct detection (if operation) and length detection (if len() is 0):
# Method 1: Using if else
topping = []
if topping:
print('Non-empty.')
else:
print('Empty.')
# Method2: Using len(LIST)
if len(topping) == 0:
print('Empty.')
Comments 2 comments
Blogger 125915708
The comment is private
Blogger 48752187218
https://go88-tài-xỉu.net
https://8us.my