Python 101: Strings, Booleans, Operators, and Lists

Today in this lesson, you will learn about strings, bools, operators, lists, and tuples!

ยท

8 min read

Introduction

๐Ÿ‘‹ Hi, I'm Atom! Today you will learn about strings, boolean, operators, lists, and tuples! The longest topic today will be strings, as there's so much to learn about them. Some topics we will learn in a future lesson.

Strings

Strings in Python are surrounded by either single quotation marks, or double quotation marks.

Note: 'hello world' is the same as "hello world".

You can display a string inside the terminal using the print() function:

print("Hello World")
print("Hello World")

Assign Strings to Variables

Assigning a string to a variable is done with the variable name followed by an equal sign and quotations:

x = "Hello, world!"
print(a) # this would print "Hello, world!" into the terminal

Multiline Strings

We've already learned about Multiline Strings while we talked about commenting in the last lesson.

When multiline strings are assigned to a variable, then they are read by the interpreter. For example:

x = """This is a multiline string
It is read by the interpreter because
it is assigned towards a
variable."""
print(x)

Note: Multiline strings are the same with single quotes as it is with double quotes. Any string is the same with either single quotes or double quotes.

Indexing Strings

Like most programming languages, strings in Python are arrays of bytes which represent Unicode characters.

Since Python does not have a char (character) data type, a character is simply a string with a length of 1.

Square brackets can be used to access elements of the string. This is called "indexing." When you are indexing, the first position of the array is 0. For example, say we want to get the 1st letter of the word "lorem." We would need to index [0] to get the letter "l."

lorem = "Lorem ipsum"
print(lorem[0])

Similarly, if you would like to get the second character:

lorem = "Lorem ipsum"
print(lorem[1])

Looping Through Strings

Since strings are arrays, we can loop through the characters in a string using a for() loop.

for x in "lorem ipsum":
    print(x)

So, what does this code do? Essentially, for each character inside the string, it's representing it with an x. Each character it passes, it prints out x to the terminal.

Length of String

To get the length of a string, you can use the len() function. It returns the length of characters inside the string.

x = "Hello, world!"
print(len(x))

Check If String Contains Value

To check if a phrase, word, or character is present inside a string, we can use the keyword in.

This block of code prints whether the letter "d" contains in this string.

text = "abcdefg"
print("d" in text)

The in keyword returns a boolean value, which we will learn more about in a few sections. In short, boolean are values that are either True or False.

You can do the same to check if something is not present inside a string.

text = "abcdefg"
print("d" not in text)

This should return False.

Modifying Strings

Python has a set of built-in methods you can use to modify strings.

Uppercase

The upper() method returns the string, but in uppercase:

x = "Hello, world!"
print(x.upper())

This should return HELLO, WORLD!.

Lowercase

The lower() method returns the string, but lowercase:

x = "Hello, world!"
x = x.upper()
print(x.lower())

This should return hello, world!.

Remove Whitespace

What is whitespace? Whitespace is the space before and/or after the actual text, and very often you want to remove this space, as it's mostly unnecessary. Python has a built-in method to handle whitespace called strip().

x = " Hello, world! "
print(x.strip()) # --> "Hello, world!"

Replace String

In Python, you can replace a string with another string. You can do this using the replace() method:

x = "Hello, World!"
print(x.replace("H", "M")) # --> returns "Mello, World!"

The last method we will learn about is...

Split String

The split() method returns a list where the text between the specified separator becomes the list item. For example, if you split "Hello, World!", you should get a list similar to this: ['Hello', ' World!']

Here is an example using viable Python code:

x = "Hello, World!"
print(x.split(","))

This splits the string at the comma, turning the two split values and putting them as different values inside a list: ['Hello', ' World!']

Note: There is one more important topic, but it may be a little hard to grasp, so we'll hold it off for a future lesson. If you would like to go ahead and learn it yourself, be my guest. The topic is called "Escape Characters."

Booleans

What are booleans? Booleans are values which represent one of two values: True or False.

In programming, there are often times when you need to know if an expression is True or False. You can evaluate any expression in Python to get one of two answers, True or False. When you compare the two results, the expression is evaluated and Python returns the boolean answer:

print(10 > 9) # asking if 10 is greater than 9 --> True
print(10 == 9) # asking if 10 is equal to 9 --> False
print(10 < 9) # asking if 10 is less than 9 --> False

Evaluate Values and Variables

The bool() function allows you to evaluate any value, and give you True or False in return:

print(bool("hi")) # --> True
print(bool(15)) # --> True

This code basically checks to see if the value you entered is equal to itself.

Almost any value is evaluated to True if it contains some sort of content. Any string is True, unless it's empty. Any number is True, unless it's 0. Any list, tuple, set, and dictionary are True, unless they're empty. In fact, there are not many values that evaluate to False, except empty value, such as (), [], {}, "", the number 0, and the value None. Of course, the value False evaluates to False.

bool(False) # --> False
bool(None) # --> False
bool(0) # --> False
bool("") # --> False
bool(()) # --> False
bool([]) # --> False
bool({}) # --> False

Operators

In Python (and most other languages), operators are used to perform operations on variables and values. In the example below, we can use the + operator to add two values together:

print(10 + 15)

Python divides operators into the following groups:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Identity Operators
  • Membership Operators
  • Bitwise Operators

We will only be covering arithmetic operators and logical operators. Those are the main ones. After that, it's up to you if you would like to learn the rest on your own. For now, let's dive into operators!

Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations.

OperatorNameExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
**Exponentiationx ** y
//Floor divisionx // y

Comparison Operators

Comparison operators are used to compare two values.

OperatorNameExample
==Equalx == y
!=Not Equalx != y
>Greater Thanx > y
<Less Thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

Note: You do not need to memorize this. This table is only here for reference and information. You do not have to memorize it. When you are writing code, most of these automatically pop up in your head, and you will know to use it then.

Let's dive into the last topic for today...

Lists

Lists are very important. Because of this, I will release an entire mini-lesson revolving around lists and tuples. For now, let's learn just what a list is.

Lists are used to store multiple items in a single variable. There are 4 built-in data types in Python to store collections of data:

  • Lists (What we will learn now)
  • Tuples
  • Sets
  • Dictionaries

Lists are created using square brackets:

myList = ["apple", "banana", "orange"]
print(myList)

List Items

List items are ordered, interchangeable, and allow duplicate values. List items are indexed and the first term has indexed [0], the second term has indexed [1], and so on.

All list items can be any sort of data type: boolean, strings, integers, floats, etc.

Ordered Lists

Ordered lists are just lists that have a definite order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the order of the items will not change automatically.

List Length

To determine how many items a list has, you can use the same function we used to determine the length of a string; len().

myList = ["apple", "banana", "orange"]
print(len(myList))

Conclusion

Hello! Thank you for reading this lesson. I appreciate your support and will continue to make quality free Python 101 course lessons for everyone.

Plug: I am also currently working on a JavaScript course similar to this one called JavaScript 101. I am currently working on the curriculum for the JavaScript course and will advertise it in the next lesson.

Click here to view the complete Python 101 curriculum I will be following throughout the entirety of the course.

Homework

There is no homework for this lesson. There wasn't much we talked about today which could be applied in the real world. We talked about strings, booleans, operators, and were introduced to lists.

Note: I will be posting a complete mini-lesson regarding lists, tuples, and introducing you to sets.

Questions

If you have any questions, make sure to leave them in the comments below and I'll answer them as soon as possible!

Suggestions

Similar with the comments, leave the suggestions in the comments below and I'll look into them for sure!

Bye everyone and have a wonderful day!

ย