An if statement looks like this:if expression:
statements
Notice the colon at the end of the expression in the if statement.
Python uses indentation (white space at the beginning of a line) to delimit blocks of code. Other languages, such as C, use curly braces to accomplish this, but in Python indentation is mandatory; programs won't work without it. As you can see, the statements in the if should be indented.
While
i = 1
while i <=5:
print(i)
i = i + 1
print("Finished!")
The infinite loop is a special kind of while loop; it never stops running. Its condition always remains True.
An example of an infinite loop:
while 1==1:
print("In the loop")
This program would indefinitely print "In the loop".
You can stop the program's execution by using the Ctrl-C shortcut or by closing the program.
Lists
An empty list is created with an empty pair of square brackets.
empty_list = []
print(empty_list)
Most of the time, a comma won't follow the last item in a list. However, it is perfectly valid to place one there, and it is encouraged in some cases.
List Operations
Lists can be added and multiplied in the same way as strings.
For example:
nums = [1, 2, 3]
print(nums + [4, 5, 6])
print(nums * 3)
Result:>>>
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>>
Lists and strings are similar in many ways - strings can be thought of as lists of characters that can't be changed.
To check if an item is in a list, the in operator can be used. It returns True if the item occurs one or more times in the list, and False if it doesn't.
words = ["spam", "egg", "spam", "sausage"]
print("spam" in words)
print("egg" in words)
print("tomato" in words)
The in operator is also used to determine whether or not a string is a substring of another string.
Range
The range function creates a sequential list of numbers.
The code below generates a list containing all of the integers, up to 10.
numbers = list(range(10))
print(numbers)
The call to list is necessary because range by itself creates a range object, and this must be converted to a list if you want to use it as one.
If range is called with one argument, it produces an object with values from 0 to that argument(excluding the argument).
If it is called with two arguments, it produces values from the first to the second.
For example:
numbers = list(range(3, 8))
print(numbers)
print(range(20) == range(0, 20))
Range
range can have a third argument, which determines the interval of the sequence produced. This third argument must be an integer.
numbers = list(range(5, 20, 2))
print(numbers)
Result:>>>
[5, 7, 9, 11, 13, 15, 17, 19]
>>>
Comments
Post a Comment