Conditional statements
If expr:
print("expr is true")
If expr:
print("It's true")
else:
print("its’s false")
Python provides the elif keyword to eliminate the need for nested if … else structure.
h = 5
if h > 5:
print("greater than 5")
elif h < 2:
print("less than 2")
else:
print("between 2 and 5.")
While loops
# While loop
While expr:
print("loop while expr is true")
# Do-while in python
While True:
If expr:
Break
Strings
- Immutable sequence of Unicode codepoints.
- Immutable mean when you construct a string you can't modify its content.
- Strings with Newlines
- Multiline strings
- """ this is
- Multiline string"""
- Escape sequences
- This is \nmultiline \nstring.
- len(s) gives number of codepoints(characters).
- The + operator can be used for string concatenation.
- >>> "This" + "is" + "a" + "string"
- Thisisastring
- Strings are immutable, so the += operator re-binds the reference to a new object.
- Use sparingly, concatenation with + or += can cause performance degradation.
- Call the join() method on the separator string.
- >>> Numbers = ';'.join([1, 2, 3, 4])
- '1;2;3;4'
- Use the split() to divide a string into a list.
- >>> Numbers.split(';')
- [1, 2, 3, 4]
- Without an argument, split() divides on whitespace.
- Join()-ing on an empty separator is an important and fast way of concatenating a collection of strings.
- The partition() method divides a string into three around a separator: prefix, separator, suffix.
- Tuple unpacking is useful to destructure the result.
Range
- Arithmetic progression of integers.
- Stop value is one-past-the-end.
- >>> range(5)
- range(0, 5)
- Ranges are 'half open'-start is include but stop is not.
- >>> for I in range(5)
- print(I)
- 0
- 1
- 2
- 3
- 4
- Stop value of a range used as start value of consecutive range.
- >>> list(range(5, 10))
- [5, 6, 7, 8, 9]
- >>> list(range(10, 15))
- [10, 11, 12, 13, 14]
- Optional third step value.
- >>> List(range(0, 10, 2))
- [0, 2, 4, 6, 8]
- Range(stop) range(10)
- Range(start:stop) range(0, 10)
- Range(start:stop:step) range(0, 10, 2)