Learning Python: Week 1 - From Operators to Generators
This article was originally published on my personal blog.
Recently, I decided that I will start learning Python. I'm already familiar with the language, what can be done with it, and some of the syntaxes as well. However, I never took the time to properly learn it and create projects with it.
But why am I writing about it? Ever since I created my blog and started writing I've noticed how much writing has helped me learn more. When I write about something, I commit to completely understanding it and taking a deeper dive into it.
In this article, and (hopefully) the following ones as well, I'll share what I learned in Python within a week. Not only will this help me learn better, but I might learn from the readers as well if they point out anything wrong with what I've learned. This could help others who are interested in learning Python follow along this journey with me.
Quick Note
The learning progress of every person is different. What I learn within a week may be more or less than what you'd learn in a week. That's fine for both of us.
Also, I already have knowledge and experience in a lot of other programming languages, so in most of these articles I'll be pointing out things that might be new to me or different than other languages.
Where I Started
I wanted to find a good place to start learning Python starting from the basics. I didn't want to just find a tutorial and start programming. I wanted to take the time to learn more about it.
After looking through different websites and courses online that could help, I decided to learn from learpython.org. The topics seem to be divided up pretty well and each chapter had examples and an exercise at the end.
Up until the time I'm writing this I've finished until Generators.
What I Learned
Indentation
In all programming languages I've used, code blocks are usually wrapped with curly braces {
and }
. For example, this in JavaScript:
if (x > 1) {
console.log("x is not 0");
}
However, in Python, all code blocks are represented by just an indentation. So, if i were to write that same code block in Python it would be:
if x > 1:
print("x is not 0")
Simultaneous Assignment
The naming for this might be incorrect but that's what I'm calling it for now.
In Python, you can assign multiple variables simultaneously like this:
a,b = 1,2
This line of code will set a
to 1
and b
to 2
.
Operators
There are many operators that are common between Python and other languages. However, there were some that I haven't seen in other languages I know.
You can use **
to make a power relationship:
a = 2 ** 3 //8
You can use the multiply operator *
on strings to repeat them n
times:
a = "hello" * 3 //hellohellohello
You can also use the multiply operator *
on lists (which are basically arrays in Python) to repeat them as well:
a = [1,2,3] * 3 // [1,2,3,1,2,3,1,2,3]
String Formatting
To format strings and add variables inside strings, you can use the %
operator in the string followed by a letter depending on the type of the variable you're inserting in the string.
For example:
print("I am %d years old" % age)
%d
is used for integers, %s
for strings, %f
for float numbers, and %.nf
is a float number with n
places following the decimal.
Slicing Strings
The brackets []
are usually used with Arrays to refer to an item at a certain index. It's also used in some languages to access a character at a certain index in a string.
However, in Python, you can also use the brackets []
with strings to take substrings of them. If you use the notation [n:m]
it will take a slice of the string starting from the index n
till the index m
.
For example:
x = "My name is Shahed"
print(x[3:10]) //name is
You can also use the notation [n:m:x]
, where x
is the number of steps to take when moving from index n
till index m
. When you use the notation [n:m]
it sets x
to 1 by default. x
can also be a negative value if you want to slice the string in reverse.
Boolean Operators
Most languages use &&
to specify an "and" condition, and ||
to specify an "or" condition.
In Python, you use and
for "and" and or
for "or". This is part of what makes Python human-readable.
For example:
if x == 2 and y == 3:
print("x is 2 and y is 3")
Other operators are in
to check if an item is in an iterable object like a list, is
to check if 2 variables match in both value and reference, and not
to negate a boolean expression.
Else in Loops
else
is usually used with if conditions, where you perform an action if the condition is not true.
In Python, else
can be used with loops to perform an action when the condition of the loop fails.
For example:
for i in range(1,5):
print("i is less than 5")
else:
print("i is greater than 5")
If you use break
inside the loop, then the else
block won't be executed. If you use continue
inside the loop, the else
block will be executed.
init Function in Classes
In Python, the function __init__
in a class is the function that is first called when the class is created. It's the equivalent of the constructor
function in other languages.
Modules
Each Python file that you create can be used as a module in other Python files. This allows you to use the functions or variables that are in that module.
To import a module:
import user
Where user
is a file in the same directory with the name user.py
You can then access functions in that module using the .
notation:
user.create()
Alternatively, you can import the function directly:
from user import create
You can also import all objects in the module:
from user import *
You can then use the objects directly:
create()
In addition, you can import modules with aliases:
import user as my_user
Packages
Packages are directories that hold other packages and modules. Each package should include the file __init__.py
, even if it's empty. It's used to indicate that the current directory is a package.
Modules can be imported from inside that package. For example, if you create the directory blog
and it has the user
module inside it, you can import it like this:
import blog.user
Or alternatively:
from blog import user
By default, all modules inside a package can be imported. You can specify which modules can be accessed in a package by assigning the __all__
variable in __init__
:
__all__ = ["user"]
Numpy Arrays
Numpy arrays are like lists, but they are more fast and efficient. Using Numpy arrays you can easily perform a lot of tedious tasks.
For example, you can perform operations on all elements in a Numpy array:
np_array = np.array([1,2,3])
np_array = np_array * 2 //[2,4,6]
You can also use []
to take a subset of items in the Numpy array. For example:
np_array = np.array([1,2,3])
np_array[np_array > 1] //[2,3]
Where np_array > 1
will return a new Numpy array but instead of the original values it will be either True
or False
based on whether each element satisfies the condition or not. If you then pass it as an index to np_array
it will return a Numpy array with only the elements that test true for that condition.
Pandas DataFrame
DataFrames in Pandas allow you to store data in a table-like structure where there are columns and rows.
DataFrames can be created from dictionaries. They can also be created from CSV files.
You can access the data using a column name as an index:
dataframe["name"]
This will return the data as a Pandas Series. You can use double brackets to have it be returned as a DataFrame:
dataframe[["name"]]
You can also return multiple columns or indices:
dataframe[["name", "age"]]
Another way of getting a set of data from the DataFrame is using loc
and iloc
, where loc
accesses the data using a label index, while iloc
accesses the data using a numeric index. It's helpful if you have a specific row and column to access.
Generators
Generators are used to implement iterators. They are functions that use the keyword yield
to return an iterable set of items.
When you run an iteration over the generator function, the generator starts. Everytime the yield
keyword is reached, the value is returned as the value for the current iteration.
For example:
def age():
for i in range(5):
yield "I am %d years old" % i
for str in age():
print(str)
This will print:
I am 0 years old
I am 1 years old
I am 2 years old
I am 3 years old
I am 4 years old
Where Next?
There are still more chapters to go through in learnpython.org, however, I think I want to practice solving some problems as well.
A platform that I found good reviews for among Python learners and developers is CheckiO. So, I'll probably start learning through this platform while also continuing on with some of the other chapters.
If you have any ideas of how I should continue in my journey of learning Python or find anything wrong with this article, please let me know!