If you’re going to learn a new language today, Python is one of the options out there. Not only is it relatively easy to learn, but it has many practical uses in tech.
Whether you’re coming to Python from another language or learning it for the first time, it helps to start with some basic examples.
Strings
Proper Python string manipulation is a skill every programmer needs to learn. You’ll use strings whether you’re developing a website, making a game, or analyzing data, among other applications.
Let’s say you have two strings:
name = "Joel"
job = "Programmer"
And let’s say you want to concatenate (join together) the two strings into one. You might choose to do this:
title = name + " the " + job
print(title)
But there’s a better way to manipulate strings, resulting in more readable code. Prefer to use the format() method:
title = "{} the {}".format(name, job)
print(title)
The curly braces ({}) are placeholders for the variables passed into the format method in their respective order. The first curly brace is replaced by the name parameter, while the second brace gets replaced by the job parameter.
You can have as many curly braces and parameters as long as the count matches. And these parameters can be of any data type, so you can use an integer, for example.
String Joining
Another nifty Pythonic trick is the join() method, which combines a list of strings into one.
For example:
availability = ["Monday", "Wednesday", "Friday", "Saturday"]
result = " - ".join(availability)
print(result)
# Output: 'Monday - Wednesday - Friday - Saturday'
The separating string (” – “) only goes between items, so you won’t have an extraneous separator at the end.
Conditionals
Programming would be pointless without conditional statements. Fortunately, conditions in Python are clean and easy to wrap your head around.
Boolean Values
Like in other programming languages, comparison operators evaluate to a boolean result, either True or False.
Here are all the comparison operators in Python:
x = 10
print(x == 10)
print(x != 10)
print(x > 5)
print(x < 15)
print(x >= 10)
print(x <= 10)
The if and else statements
As with other programming languages, you can use the if/else statements to represent conditions in Python. You’ll use this a lot in real-world projects:
a = 3
b = 10
if a < b:
print(True)
else:
print(False)
While some other programming languages like JavaScript and C use else…if to pass in more conditions, Python uses elif:
a = 3
b = 10
if a > b:
print("One")
elif a == 3:
print("Two")
else:
print("Three")
The is and not Operators
The is operator is different from the == comparison operator in that the latter only checks if the values of a variable are equal.
If you want to check whether two variables point to the same object in memory, you’ll need to use the is operator:
a = [1,2,3]
b = [1,2,3]
c = a
print(a is b)
print(a is c)
print(a == c)
The expression a is c evaluates to True because c points to a in memory.
You can negate a boolean value by preceding it with the not operator:
a = [1,2,3]
b = [1,2,3]
if a is not b:
print("Not same")
The in Operator
The best way to check if a value exists within an iterable like a list or a dictionary is to use the in operator:
availability = ["Monday", "Tuesday", "Friday"]
request = "Saturday"
if request in availability:
print("Available!")
else:
print("Not available")
Complex Conditionals
You can combine multiple conditional statements using the and and or operators. The and operator evaluates to True if both sides are True, otherwise False.
The or operator evaluates to True if either side is True, otherwise False.
weather = "Sunny"
umbrella = weather == "Rain" or weather == "Sunny"
umbrella1 = weather == "Rain" and weather =="Snow"
print(umbrella)
print(umbrella1)
Loops
The most basic type of loop is Python’s while loop, which keeps repeating as long as a condition evaluates to True:
i = 0
while i < 10:
i = i + 1
print(i)
You can use the break keyword to exit a loop:
i = 0
while True:
i = i + 1
print(i)
You can use continue if you just want to skip the rest of the current loop and jump to the next iteration:
i = 0
while i < 10:
i = i + 1
if i == 4:
continue
print(i)
The for Loop
The more Pythonic approach is to use for loops. The for loop in Python is much like the foreach loop you’ll find in languages like Java or C#.
The for loop iterates over an iterable (like a list or dictionary) using the in operator:
weekdays = ["Monday", "Tuesday", "Wednesday"]
for day in weekdays:
print(day)
The for loop assigns each item in the list to the day variable and outputs each accordingly.
If you just want to run a loop a fixed number of times, you can use Python’s range() method:
for i in range(10):
print(i)
This will iterate from 0 to 9. You can also provide a starting value, so to iterate from 5 to 9:
for i in range(5, 10):
print(i)
If you want to count in intervals other than one by one, you can provide a third parameter.
The following loop is the same as the previous one, except it skips by two instead of one:
for i in range(5, 10, 2):
print(i)
If you’re coming from another language, you might notice that looping through an iterable in Python doesn’t give you the index of the items in the list.
But you can use the index to count items in an iterable with the enumerate() method:
weekdays = ["Monday", "Tuesday", "Friday"]
for i, day in enumerate(weekdays):
print("{} is weekday {}".format(day, i))
Dictionaries
The dictionary is one of the most important data types in Python. You’ll use them all the time. They’re fast and easy to use, keeping your code clean and readable.
A mastery of dictionaries is half the battle in learning Python. The good news is that you probably have prior knowledge of dictionaries. Other languages call this type an unordered_map or a HashSet.
Although they have different names, they refer to the same thing: an associative array of key-value pairs. You access the contents of a list via each item’s index, while you access a dictionary’s items via a key.
You can declare an empty dictionary using empty braces:
d = {}
And then assign values to it using square brackets surrounding the key:
d["key1"] = 10
d["key2"] = 25
print(d)
# Output: {'key1': 10, 'key2': 25}
The nice thing about a dictionary is that you can mix and match variable types. It doesn’t matter what you put in there.
To initialize a dictionary more easily, you can use this syntax:
myDictionary = {
"key1": 10,
"List": [1, 2, 3]
}
To access a dictionary value by key, simply reuse the bracket syntax:
print(myDictionary["key1"])
To iterate over the keys in a dictionary, use a for loop like so:
for key in myDictionary:
print(key)
To iterate both keys and values, use the items() method:
for key, values in myDictionary.items():
print(key, values)
You can also remove an item from a dictionary using the del operator:
del(myDictionary["List"])
print(myDictionary)
# Output: {'key1': 10}
Dictionaries have many uses. Here’s a simple example of a mapping between some US states and their capitals:
capitals = {
"Alabama": "Montgomery",
"Alaska": "Juneau",
"Arizona": "Phoenix",
}
Whenever you need the capital of a state, you can access it like so:
print(capitals["Alaska"])
Keep Learning Python: It’s Worth It!
These are just the basic aspects of Python that set it apart from most of the other languages out there. If you understand what we covered in this article, you’re well on mastering Python. Keep at it, and you’ll get there in no time.
If the examples challenge you to go further, some Python project ideas for beginners might be a solid starting point.