- Python If . Else
- Example
- Indentation
- Example
- Elif
- Example
- Else
- Example
- Example
- Short Hand If
- Example
- Short Hand If . Else
- Example
- Example
- And
- Example
- Or
- Example
- Not
- Example
- Nested If
- Example
- The pass Statement
- Python Compare Strings – How to Check for String Equality
- How to Check for String Equality in Python
- How to Compare Strings Using the == Operator
- How to Compare Strings Using the != Operator
- How to Compare Strings Using the < Operator
- How to Compare Strings Using the Recall that this operator checks for two things – if one string is less or if both strings are the same – and would return True if either is true. We got True because both strings are equal. How to Compare Strings Using the > Operator The > operator checks if one string is greater than another string. Since the string on the left isn’t greater than the one on the right, we got False returned to us. How to Compare Strings Using the >= Operator The >= operator checks if one string is greater than or equal to another string. Since one of both conditions of the operator is true (both strings are equal), we got a value of True . Conclusion In this article, we learned about the various operators you can use when checking the equality of strings in Python with examples. We also saw how case sensitivity can alter the equality of strings. Источник Checking for True or False The «bad» ways are not only frowned upon but also slower. Let’s use a simple test: $ python -m timeit -s "variable=False" "if variable == True: pass"
10000000 loops, best of 5: 24.9 nsec per loop
$ python -m timeit -s "variable=False" "if variable is True: pass"
10000000 loops, best of 5: 17.4 nsec per loop
$ python -m timeit -s "variable=False" "if variable: pass"
20000000 loops, best of 5: 10.9 nsec per loop Using is is around 60% slower than if variable (17.4/10.9≈1.596), but using == is 120% slower (24.9/10.9≈2.284)! It doesn’t matter if the variable is actually True or False — the differences in performance are similar (if the variable is True , all three scenarios will be slightly slower). Similarly, we can check if a variable is not True using one of the following methods: $ python -m timeit -s "variable=False" "if variable != True: pass"
10000000 loops, best of 5: 26 nsec per loop
$ python -m timeit -s "variable=False" "if variable is not True: pass"
10000000 loops, best of 5: 18.8 nsec per loop
$ python -m timeit -s "variable=False" "if not variable: pass"
20000000 loops, best of 5: 12.4 nsec per loop if not variable wins. is not is 50% slower (18.8/12.4≈1.516) and != takes twice as long (26/12.4≈2.016). The if variable and if not variable versions are faster to execute and faster to read. They are common idioms that you will often see in Python (or other programming languages). About the «Writing Faster Python» series # «Writing Faster Python» is a series of short articles discussing how to solve some common problems with different code structures. I run some benchmarks, discuss the difference between each code snippet, and finish with some personal recommendations. Are those recommendations going to make your code much faster? Not really. Is knowing those small differences going to make a slightly better Python programmer? Hopefully! You can read more about some assumptions I made, the benchmarking setup, and answers to some common questions in the Introduction article. And you can find most of the code examples in this repository. «truthy» and «falsy» # Why do I keep putting «bad» in quotes? That’s because the «bad» way is not always bad (it’s only wrong when you want to compare boolean values, as pointed in PEP8). Sometimes, you intentionally have to use one of those other comparisons. In Python (and many other languages), there is True , and there are truthy values. That is, values interpreted as True if you run bool(variable) . Similarly, there is False , and there are falsy values (values that return False from bool(variable) ). An empty list ( [] ), string ( «» ), dictionary ( <> ), None and 0 are all falsy but they are not strictly False . Sometimes you need to distinguish between True / False and truthy/falsy values. If your code should behave in one way when you pass an empty list, and in another, when you pass False , you can’t use if not value . Take a look at the following scenario: def process_orders(orders=None):
if not orders:
# There are no orders, return
return
else:
# Process orders
... We have a function to process some orders. If there are no orders, we want to return without doing anything. Otherwise, we want to process existing orders. We assume that if there are no orders, then orders parameter is set to None . But, if the orders is an empty list, we also return without any action! And maybe it’s possible to receive an empty list because someone is just updating the billing information of a past order? Or perhaps having an empty list means that there is a bug in the system. We should catch that bug before we fill up the database with empty orders! No matter what’s the reason for an empty list, the above code will ignore it. We can fix it by investigating the orders parameter more carefully: def process_orders(orders=None):
if orders is None:
# orders is None, return
return
elif orders == []:
# Process empty list of orders
...
elif len(orders) > 0:
# Process existing orders
... The same applies to truthy values. If your code should work differently for True than for, let’s say, value 1 , we can’t use if variable . We should use == to compare the number ( if variable == 1 ) and is to compare to True ( if variable is True ). Sounds confusing? Let’s take a look at the difference between is and == . is checks the identity, == checks the value # The is operator compares the identity of objects. If two variables are identical, it means that they point to the same object (the same place in memory). They both have the same ID (that you can check with the id() function). The == operator compares values. It checks if the value of one variable is equal to the value of some other variable. Some objects in Python are unique, like None , True or False . Each time you assign a variable to True , it points to the same True object as other variables assigned to True . But each time you create a new list, Python creates a new object: >>> a = True
>>> b = True
>>> a is b
True
# Variables that are identical are always also equal!
>>> a == b
True
# But
>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a is b
False # Those lists are two different objects
>>> a == b
True # Both lists are equal (contain the same elements) It’s important to know the difference between is and == . If you think that they work the same, you might end up with weird bugs in your code: a = 1
# This will print 'yes'
if a is 1:
print('yes')
b = 1000
# This won't!
if b is 1000:
print('yes') In the above example, the first block of code will print «yes,» but the second won’t. That’s because Python performs some tiny optimizations and small integers share the same ID (they point to the same object). Each time you assign 1 to a new variable, it points to the same 1 object. But when you assign 1000 to a variable, it creates a new object. If we use b == 1000 , then everything will work as expected. Conclusions # To check if a variable is equal to True/False (and you don’t have to distinguish between True / False and truthy / falsy values), use if variable or if not variable . It’s the simplest and fastest way to do this. If you want to check that a variable is explicitly True or False (and is not truthy/falsy), use is ( if variable is True ). If you want to check if a variable is equal to 0 or if a list is empty, use if variable == 0 or if variable == [] . Don’t miss new articles No spam, unsubscribe with one click. Источник - How to Compare Strings Using the > Operator
- How to Compare Strings Using the >= Operator
- Conclusion
- Checking for True or False
- About the «Writing Faster Python» series #
- «truthy» and «falsy» #
- is checks the identity, == checks the value #
- Conclusions #
- Don’t miss new articles
Python If . Else
Python supports the usual logical conditions from mathematics:
- Equals: a == b
- Not Equals: a != b
- Less than: a < b
- Less than or equal to: a
- Greater than: a > b
- Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in «if statements» and loops.
An «if statement» is written by using the if keyword.
Example
In this example we use two variables, a and b , which are used as part of the if statement to test whether b is greater than a . As a is 33 , and b is 200 , we know that 200 is greater than 33, and so we print to screen that «b is greater than a».
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.
Example
If statement, without indentation (will raise an error):
Elif
The elif keyword is Python’s way of saying «if the previous conditions were not true, then try this condition».
Example
In this example a is equal to b , so the first condition is not true, but the elif condition is true, so we print to screen that «a and b are equal».
Else
The else keyword catches anything which isn’t caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print(«b is greater than a»)
elif a == b:
print(«a and b are equal»)
else:
print(«a is greater than b»)
In this example a is greater than b , so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that «a is greater than b».
You can also have an else without the elif :
Example
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
Short Hand If . Else
If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:
Example
One line if else statement:
This technique is known as Ternary Operators, or Conditional Expressions.
You can also have multiple else statements on the same line:
Example
One line if else statement, with 3 conditions:
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b , AND if c is greater than a :
Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b , OR if a is greater than c :
Not
The not keyword is a logical operator, and is used to reverse the result of the conditional statement:
Example
Test if a is NOT greater than b :
Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
if x > 10:
print(«Above ten,»)
if x > 20:
print(«and also above 20!»)
else:
print(«but not above 20.»)
The pass Statement
if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
Python Compare Strings – How to Check for String Equality
Ihechikara Vincent Abba
When crafting the logic in your code, you may want to execute different commands depending on the similarities or differences between two or more strings.
In this article, we’ll see various operators that can help us check if strings are equal or not. If two strings are equal, the value returned would be True . Otherwise, it’ll return False .
How to Check for String Equality in Python
In this section, we’ll see examples of how we can compare strings using a few operators.
But before that, you need to have the following in mind:
- Comparisons are case sensitive. G is not the same as g.
- Each character in a string has an ASCII value (American Standard Code for Information Interchange) which is what operators look out for, and not the actual character. For example, G has an ASCII value of 71 while g has a value of of 103. When compared, g becomes greater than G.
How to Compare Strings Using the == Operator
The == operator checks if two strings are equal. Here is an example:
We got a value of True returned because both strings above are equal.
Let’s make it look a bit more fancy using some conditional logic:
string1 = "Hello" string2 = "Hello" if string1 == string2: print("Both strings are equal") else: print("Both strings are not equal") # Both strings are equal
In the code above, we created two strings and stored them in variables. We then compared their values. If these values are the same, we would get one message printed to the console and if they aren’t the same, we would have a different message printed.
Both strings in our case were equal, so we had «Both strings are equal» printed. If we changed the first string to «hello», then we would have a different message.
Note that using = would make the interpreter assume you want to assign one value to another. So make sure you use == for comparison.
How to Compare Strings Using the != Operator
The != operator checks if two strings are not equal.
string1 = "Hello" string2 = "Hello" if string1 != string2: print("Both strings are not equal") # return if true else: print("Both strings are equal") # return if false # Both strings are equal
We’re using the same example but with a different operator. The != is saying the strings are not equal which is False so a message is printed based on those conditions.
I have commented the code to help you understand better.
How to Compare Strings Using the < Operator
This returns True because even though every other character index in both strings is equal, H has a smaller (ASCII) value than h .
We can also use conditional statements here like we did in previous sections.
How to Compare Strings Using the
Recall that this operator checks for two things – if one string is less or if both strings are the same – and would return True if either is true.
We got True because both strings are equal.
How to Compare Strings Using the > Operator
The > operator checks if one string is greater than another string.
Since the string on the left isn’t greater than the one on the right, we got False returned to us.
How to Compare Strings Using the >= Operator
The >= operator checks if one string is greater than or equal to another string.
Since one of both conditions of the operator is true (both strings are equal), we got a value of True .
Conclusion
In this article, we learned about the various operators you can use when checking the equality of strings in Python with examples. We also saw how case sensitivity can alter the equality of strings.
Checking for True or False
The «bad» ways are not only frowned upon but also slower. Let’s use a simple test:
$ python -m timeit -s "variable=False" "if variable == True: pass"
10000000 loops, best of 5: 24.9 nsec per loop
$ python -m timeit -s "variable=False" "if variable is True: pass"
10000000 loops, best of 5: 17.4 nsec per loop
$ python -m timeit -s "variable=False" "if variable: pass"
20000000 loops, best of 5: 10.9 nsec per loop
Using is is around 60% slower than if variable (17.4/10.9≈1.596), but using == is 120% slower (24.9/10.9≈2.284)! It doesn’t matter if the variable is actually True or False — the differences in performance are similar (if the variable is True , all three scenarios will be slightly slower).
Similarly, we can check if a variable is not True using one of the following methods:
$ python -m timeit -s "variable=False" "if variable != True: pass"
10000000 loops, best of 5: 26 nsec per loop
$ python -m timeit -s "variable=False" "if variable is not True: pass"
10000000 loops, best of 5: 18.8 nsec per loop
$ python -m timeit -s "variable=False" "if not variable: pass"
20000000 loops, best of 5: 12.4 nsec per loop
if not variable wins. is not is 50% slower (18.8/12.4≈1.516) and != takes twice as long (26/12.4≈2.016).
The if variable and if not variable versions are faster to execute and faster to read. They are common idioms that you will often see in Python (or other programming languages).
About the «Writing Faster Python» series #
«Writing Faster Python» is a series of short articles discussing how to solve some common problems with different code structures. I run some benchmarks, discuss the difference between each code snippet, and finish with some personal recommendations.
Are those recommendations going to make your code much faster? Not really.
Is knowing those small differences going to make a slightly better Python programmer? Hopefully!
You can read more about some assumptions I made, the benchmarking setup, and answers to some common questions in the Introduction article. And you can find most of the code examples in this repository.
«truthy» and «falsy» #
Why do I keep putting «bad» in quotes? That’s because the «bad» way is not always bad (it’s only wrong when you want to compare boolean values, as pointed in PEP8). Sometimes, you intentionally have to use one of those other comparisons.
In Python (and many other languages), there is True , and there are truthy values. That is, values interpreted as True if you run bool(variable) . Similarly, there is False , and there are falsy values (values that return False from bool(variable) ). An empty list ( [] ), string ( «» ), dictionary ( <> ), None and 0 are all falsy but they are not strictly False .
Sometimes you need to distinguish between True / False and truthy/falsy values. If your code should behave in one way when you pass an empty list, and in another, when you pass False , you can’t use if not value .
Take a look at the following scenario:
def process_orders(orders=None):
if not orders:
# There are no orders, return
return
else:
# Process orders
...
We have a function to process some orders. If there are no orders, we want to return without doing anything. Otherwise, we want to process existing orders.
We assume that if there are no orders, then orders parameter is set to None . But, if the orders is an empty list, we also return without any action! And maybe it’s possible to receive an empty list because someone is just updating the billing information of a past order? Or perhaps having an empty list means that there is a bug in the system. We should catch that bug before we fill up the database with empty orders! No matter what’s the reason for an empty list, the above code will ignore it. We can fix it by investigating the orders parameter more carefully:
def process_orders(orders=None):
if orders is None:
# orders is None, return
return
elif orders == []:
# Process empty list of orders
...
elif len(orders) > 0:
# Process existing orders
...
The same applies to truthy values. If your code should work differently for True than for, let’s say, value 1 , we can’t use if variable . We should use == to compare the number ( if variable == 1 ) and is to compare to True ( if variable is True ). Sounds confusing? Let’s take a look at the difference between is and == .
is checks the identity, == checks the value #
The is operator compares the identity of objects. If two variables are identical, it means that they point to the same object (the same place in memory). They both have the same ID (that you can check with the id() function).
The == operator compares values. It checks if the value of one variable is equal to the value of some other variable.
Some objects in Python are unique, like None , True or False . Each time you assign a variable to True , it points to the same True object as other variables assigned to True . But each time you create a new list, Python creates a new object:
>>> a = True
>>> b = True
>>> a is b
True
# Variables that are identical are always also equal!
>>> a == b
True
# But
>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a is b
False # Those lists are two different objects
>>> a == b
True # Both lists are equal (contain the same elements)
It’s important to know the difference between is and == . If you think that they work the same, you might end up with weird bugs in your code:
a = 1
# This will print 'yes'
if a is 1:
print('yes')
b = 1000
# This won't!
if b is 1000:
print('yes')
In the above example, the first block of code will print «yes,» but the second won’t. That’s because Python performs some tiny optimizations and small integers share the same ID (they point to the same object). Each time you assign 1 to a new variable, it points to the same 1 object. But when you assign 1000 to a variable, it creates a new object. If we use b == 1000 , then everything will work as expected.
Conclusions #
- To check if a variable is equal to True/False (and you don’t have to distinguish between True / False and truthy / falsy values), use if variable or if not variable . It’s the simplest and fastest way to do this.
- If you want to check that a variable is explicitly True or False (and is not truthy/falsy), use is ( if variable is True ).
- If you want to check if a variable is equal to 0 or if a list is empty, use if variable == 0 or if variable == [] .
Don’t miss new articles
No spam, unsubscribe with one click.