Firstly, in python you cannot increment using the increment operator as in C++, or Java, e.x, x++ or --x. A for loop in Python works over an iterator (For example, List, String, etc.)
PYTHON FOR LOOPS:
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string`).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
will print:
apple
banana
cherry
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
PYTHON CONDITIONALS:
In python the keyword for false values is False, and that for true values is True
Like C++ or Java, you can use == to compare values. But unlike Java, where there is strict type-checking and the condition needs to be a Boolean Statement, in Python:
- Almost any value is evaluated to
True if it has some sort of content.
- Any string is
True, except empty strings.
- Any number is
True, except 0.
- Any
list, tuple, set, and dictionary are True`, except empty ones.
In fact, there are not many values that evaluates to False, except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to False.
The following will return False:
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
One more value, or object in this case, evaluates to False, and that is if you have an object that is made from a class with a __len__ function that returns 0orFalse`:
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))