Useful Operators In python for beginners
Useful Operators
There are a few built-in functions and "operators" in Python that don't fit well into any category, so we will go over them in this lecture, let's begin!range
The range function allows you to quickly generate a list of integers, this comes in handy a lot, so take note of how to use it! There are 3 parameters you can pass, a start, a stop, and a step size. Let's see some examples:print(range(0, 10))
OUTPUT
range(0, 11)
Note that this is a generator function, so to actually get a list out of it, we need to cast it to a list with list(). What is a generator? It's a special type of function that will generate information and not need to save it to memory. We haven't talked about functions or generators yet, so just keep this in your notes, for now, we will discuss this in much more detail later on in your training!
# Notice how 11 is not included, up to but not including 11, just like slice notation!
print(list(range(0, 11))
OUTPUT
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(range(0, 12))
OUTPUT
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
# Third parameter is step size!
# step size just means how big of a jump/leap/step you
# take from the starting number to get to the next number.
print(list(range(0, 11, 2))
OUTPUT
[0, 2, 4, 6, 8, 10]
print(list(range(0, 101, 10))
OUTPUT
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
enumerate
enumerate is a very useful function to use for loops. Let's imagine the following situation:
index_count = 0
for letter in 'abcde':
print("At index {} the letter is {}".format(index_count,letter))
index_count += 1
OUTPUT
At index 0 the letter is a
At index 1 the letter is b
At index 2 the letter is c
At index 3 the letter is d
At index 4 the letter is e
Keeping track of how many loops you've gone through is so common, that enumerate was created so you don't need to worry about creating and updating this index_count or loop_count variable
# Notice the tuple unpacking!
for i,letter in enumerate('abcde'):
print("At index {} the letter is {}".format(i,letter))
OUTPUT
At index 0 the letter is a
At index 1 the letter is b
At index 2 the letter is c
At index 3 the letter is d
At index 4 the letter is e
Post a Comment
Post a Comment
if you have any doubts, please let me know