mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-28 18:26:54 +00:00
chore(curriculum): add introduction to python transcripts (#60729)
Co-authored-by: Dario-DC <105294544+Dario-DC@users.noreply.github.com> Co-authored-by: Ilenia <26656284+ilenia-magoni@users.noreply.github.com>
This commit is contained in:
@@ -3762,7 +3762,9 @@
|
||||
"vtpz": { "title": "302", "intro": [] },
|
||||
"lecture-introduction-to-python": {
|
||||
"title": "Introduction to Python",
|
||||
"intro": ["Learn about Introduction to Python in these lectures."]
|
||||
"intro": [
|
||||
"In these lecture videos, you will learn the fundamentals of Python. You'll learn about variables, data types, operators, control flow, functions, and more."
|
||||
]
|
||||
},
|
||||
"workshop-caesar-cipher": {
|
||||
"title": "Build a Caesar Cipher",
|
||||
|
||||
@@ -53,7 +53,11 @@
|
||||
{
|
||||
"id": "67fe85a3db9bad35f2b6a2bd",
|
||||
"title": "How Do Conditional Statements and Logical Operators Work?"
|
||||
},
|
||||
{
|
||||
"id": "68480f431e8568b2056b140b",
|
||||
"title": "What Are Truthy and Falsy Values, and How Do Boolean Operators and Short-Circuiting Work?"
|
||||
}
|
||||
],
|
||||
"helpCategory": "Python"
|
||||
}
|
||||
}
|
||||
|
||||
+26
-5
@@ -1,17 +1,38 @@
|
||||
---
|
||||
id: 67fe81c9c6fd3714343a45ad
|
||||
title: What Is Python and What Are Some Common Uses in the Industry?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: what-is-python-and-what-are-some-common-uses-in-the-industry
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
Python is a general-purpose programming language known for its simplicity and ease of use. This ease of use has made Python the most popular programming language in modern times. In 2024, Python officially surpassed JavaScript as the most popular language on GitHub.
|
||||
|
||||
Python is used in many fields like data science and machine learning, web development, scripting and automation, embedded systems, IoT, and much more.
|
||||
|
||||
Python is the main language that most data scientist and machine learning engineers currently use. Libraries like Pandas and Numpy make data analysis less tedious, while others like Tensorflow and Scikit make machine learning and working with AI models much more accessible.
|
||||
|
||||
In web development, Python frameworks like Django, FastAPI, and Flask let developers build scalable and secure backend systems with minimal effort. Many social media platforms like Instagram and Pinterest use Python on the backend.
|
||||
|
||||
Cybersecurity professionals and ethical hackers use Python to detect vulnerabilities like malware and other viruses, build automated security scans, and analyze threats.
|
||||
|
||||
Python runs well on microcomputers like the Raspberry Pi and MicroPython-compatible boards, so you can build all kinds of IoT projects like smart home devices, weather monitoring stations, and more.
|
||||
|
||||
Finally, one of Python's biggest strengths is automation. You can write simple scripts to help you with repetitive tasks like extracting data from spreadsheets, sending emails, and working with files on your local machine.
|
||||
|
||||
Libraries like Selenium and BeautifulSoup also make it easy to interact with websites, so you can scrape public data, automate tasks through a web UI, and even manage cloud deployments for your projects.
|
||||
|
||||
As you can see, Python is a very powerful language, and yet, it's easy to learn. From simple automation scripts to large-scale, industrial-level applications, you can use Python for just about anything.
|
||||
|
||||
Python is a great choice for anyone who wants to learn programming, regardless of what they choose to specialize in later.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
@@ -56,7 +77,7 @@ How is Python used in embedded systems and IoT?
|
||||
|
||||
## --answers--
|
||||
|
||||
It powers game engines fro VR development.
|
||||
It powers game engines for VR development.
|
||||
|
||||
### --feedback--
|
||||
|
||||
@@ -64,7 +85,7 @@ It helps build smart devices and automation systems.
|
||||
|
||||
---
|
||||
|
||||
It runs on microcomputers like Arduino and Raspberry Pi.
|
||||
It runs on microcomputers like Raspberry Pi and compatible boards.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+44
-6
@@ -1,17 +1,55 @@
|
||||
---
|
||||
id: 67fe8567f141d632afaeb71b
|
||||
title: How Do You Install, Configure and Use Python in Your Local Environment?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: how-do-you-install-configure-and-use-python-in-your-local-environment
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
In the last lecture, you learned what Python is and what you can do with it. Now, let's look into how you can set up Python on your local machine.
|
||||
|
||||
The best way to install Python on Windows and Mac is to download the installer from the official Python website. We'll also go over running Python on Linux later in this lecture.
|
||||
|
||||
Go to `https://www.python.org/` and hover over "Downloads". A modal will appear showing the current version of Python for your OS.
|
||||
|
||||
We'll go over how to install Python on a computer running macOS first:
|
||||
|
||||
- Click on the button showing the current version of Python (from the previous modal), and you'll start downloading a `.pkg` installation file automatically.
|
||||
- Once the `.pkg` installer is finished downloading, open it, then click "Continue" in the window that opens up.
|
||||
- Continue clicking the "Continue" button until you get to the "Installation Type" section. There, click the "Install" button.
|
||||
- Enter in your password if necessary, then start the installation.
|
||||
- After that, you should get a congratulations message saying that Python has been successfully installed.
|
||||
- Click the "Close" button, and you're done!
|
||||
|
||||
You can verify the installation by opening up your terminal and running `python --version` or `python3 --version`.
|
||||
|
||||
You can also open the Python interpreter by running `python` or `python3` in the terminal.
|
||||
|
||||
Note that, on some older macOS and Linux systems, `python` can be reserved for Python 2, while `python3` is for Python 3 specifically. If you run `python --version` and see a version of Python 2 like `Python 2.7.18`, then it's possible that your OS relies on some software that was written in the older version of Python. If that's the case, you should use `python3` to run your Python code going forward.
|
||||
|
||||
To install Python on Windows, follow these steps:
|
||||
|
||||
- Go to `https://www.python.org/`, and hover over “Downloads“. You should see a modal that says "Download for Windows" and a download button with the current version of Python.
|
||||
- Click on the version number, and you'll start downloading a Windows executable (`.exe`) file automatically.
|
||||
- Once you've finished downloading the Python installer for Windows, double-click on it, and follow the instructions.
|
||||
- When you see the option `Add python.exe to Path`, check that option, then click `Install Now`. Doing that will make things easier for you later.
|
||||
|
||||
|
||||
You can verify the installation by opening up a command line shell like PowerShell and running `python --version`. You can also open the Python interpreter by running `python`.
|
||||
|
||||
For Python on Linux, most major distros like Ubuntu, Debian, and Fedora come with Python.
|
||||
|
||||
Just open a terminal and run `python --version`, or `python3 --version`:
|
||||
|
||||
If either command doesn't show a version of Python, you can search for an installation package for your flavor of Linux at `https://www.python.org`, or search online for the recommended way to install Python for your distro.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
@@ -58,7 +96,7 @@ How can you get Python added to `path` automatically on Windows?
|
||||
|
||||
By installing Python.
|
||||
|
||||
### --feedback --
|
||||
### --feedback--
|
||||
|
||||
Review the last part of the lecture.
|
||||
|
||||
@@ -70,7 +108,7 @@ By checking the "add to path" checkbox during the installation process.
|
||||
|
||||
By checking the "use admin privileges" checkbox.
|
||||
|
||||
### --feedback --
|
||||
### --feedback--
|
||||
|
||||
Review the last part of the lecture.
|
||||
|
||||
@@ -78,7 +116,7 @@ Review the last part of the lecture.
|
||||
|
||||
By downloading Python from `python.org`.
|
||||
|
||||
### --feedback --
|
||||
### --feedback--
|
||||
|
||||
Review the last part of the lecture.
|
||||
|
||||
|
||||
+73
-3
@@ -1,18 +1,88 @@
|
||||
---
|
||||
id: 67fe8597975ea634042cad8f
|
||||
title: How Do You Declare Variables and What Are Naming Conventions to Name Variables?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: how-do-you-declare-variables-and-what-are-naming-conventions-to-name-variables
|
||||
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
In Python, variables are like a labelled box for storing and referencing data of different types. To declare variables in Python, you assign a value to an identifier with the assignment (`=`) operator. You don't need to use special keywords like `let` or `const` in JavaScript, or `char` in C#.
|
||||
|
||||
In Python, you just write the name of the variable on the left, followed by the assignment operator, and the value you want to assign the variable on the right. Here's an example of how to declare `name` and `age` variables:
|
||||
|
||||
```python
|
||||
name = 'John Doe'
|
||||
age = 25
|
||||
```
|
||||
|
||||
When naming variables in Python, there are some important rules you should keep in mind:
|
||||
|
||||
- Variable names can only start with a letter or an underscore (`_`), not a number.
|
||||
- Variable names can only contain alphanumeric characters (`a-z`, `A-Z`, `0-9`) and underscores (`_`).
|
||||
- Variable names are case-sensitive — `age`, `Age`, and `AGE` are all considered unique.
|
||||
- Variable names cannot be one of Python's reserved keywords such as `if`, `class`, or `def`.
|
||||
|
||||
|
||||
If you break any of those rules, your Python program will throw a `SyntaxError`:
|
||||
|
||||
```bash
|
||||
5variable_name = 5
|
||||
^
|
||||
SyntaxError: invalid syntax
|
||||
```
|
||||
|
||||
Now let's go over some common naming conventions for variables in Python.
|
||||
|
||||
First, variables names should be in lowercase, with separate words separated by an underscore. This is called snake case:
|
||||
|
||||
```python
|
||||
my_variable_name = 'freeCodeCamp'
|
||||
```
|
||||
|
||||
Next, you should use descriptive names for variables. For example, if you want to save a user's age as a variable, `user_age` is better than `age` or an abbreviation like `ua`:
|
||||
|
||||
```python
|
||||
user_age = 30
|
||||
```
|
||||
|
||||
This way, you can easily communicate the purpose of a variable to other team members (or to your future self) in a large codebase.
|
||||
|
||||
Another convention is to avoid using single-letter variable names. This is very common in Python, but should be avoided because variable names with a single letter communicate no purpose or meaning:
|
||||
|
||||
```python
|
||||
x = 56 # What do you mean by x?
|
||||
```
|
||||
|
||||
This is different if you are in a loop or something similar, as variable names like `i`, `j`, `k`, and so on are common and acceptable.
|
||||
|
||||
Also, the pound symbol (`#`) and the text that follows in the example above is called a comment. You might already be familiar with comments, so let's go over them quickly and explain how they work.
|
||||
|
||||
In Python, comments start with a pound symbol (`#`), and the language ignores everything after the `#` symbol on that line:
|
||||
|
||||
```python
|
||||
# This is a single-line comment
|
||||
```
|
||||
|
||||
Multi-line comments can be created by using consecutive single-line comments:
|
||||
|
||||
```python
|
||||
# This is a
|
||||
# multi-line
|
||||
# comment
|
||||
```
|
||||
|
||||
You can use comments to explain your code, leave reminders for yourself, or clarify why a line exists. Comments are especially helpful when you're learning or working in teams.
|
||||
|
||||
However, you shouldn't use comments to explain what your variable names mean. Instead, the names you choose for your variables should be descriptive and communicate what they're for, and follow the other naming rules mentioned earlier to prevent syntax errors.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
+125
-3
@@ -1,17 +1,139 @@
|
||||
---
|
||||
id: 67fe8599c83979345ff9a91a
|
||||
title: How Does the Print Function Work?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: how-does-the-print-function-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
Every programming language has some way to output data to the terminal with a built-in method, function, property, or keyword. In Python, you can use the `print` function to print data to the terminal. Let's take a closer look at the `print` function so you can start using it with confidence.
|
||||
|
||||
One of the first things you do when you're learning any programming language is to write a simple `Hello world!` program. You can do that really easily in Python with just the `print` function.
|
||||
|
||||
To do that, you just need to put the string `Hello world!` in between the opening and closing parentheses you use to call the `print` function:
|
||||
|
||||
```python
|
||||
print('Hello world!') # Hello world!
|
||||
```
|
||||
|
||||
You will learn more about strings and functions in Python in future lectures. For now, just consider strings as a sequence of characters surrounded by either single (`'`) or double (`"`) quotation marks.
|
||||
|
||||
There's a lot more to the `print` function than first meets the eye. There are four other arguments you can pass to it, so here's the full syntax of the function:
|
||||
|
||||
```python
|
||||
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
|
||||
```
|
||||
|
||||
Note that each of the arguments must be separated by a comma, otherwise you'll get a syntax error. Here are more details about each argument:
|
||||
|
||||
- `objects`: The data you want to print. The `*` sign means that you can print multiple things to the terminal by passing in multiple objects (in other words, strings, variables, numbers, and so on) separated by commas.
|
||||
- `sep=' '`: The separator between the objects. This defaults to a single space character (`' '`).
|
||||
- `end='\n'`: What to print at the end of the object. This defaults to a new line character (`'\n'`).
|
||||
- `file=sys.stdout`: Determines where to send the output. The default is the terminal, but it can be a file.
|
||||
- `flush=False`: Determines whether to show the output data right away. The default is `False`, which means Python may wait before displaying the output.
|
||||
|
||||
You might be wondering how the other arguments outside of `object` are useful. Let's take a look at some common use cases.
|
||||
|
||||
If you print multiple things at once, they're just separated by spaces by default. For example:
|
||||
|
||||
```python
|
||||
print('Footballers:', 'Ronaldo', 'Messi', 'Hazard', 'Kante', 'Okocha')
|
||||
|
||||
# Output: Footballers: Ronaldo Messi Hazard Kante Okocha
|
||||
```
|
||||
|
||||
But you can use another separator of your choice with the `sep` argument:
|
||||
|
||||
```python
|
||||
print('Footballers:', 'Ronaldo', 'Messi', 'Hazard', 'Kante', 'Okocha', sep=', ')
|
||||
|
||||
# Output: Footballers:, Ronaldo, Messi, Hazard, Kante, Okocha
|
||||
```
|
||||
|
||||
In this example, you passed a comma followed by a single space character to `sep`. But the comma in front of the first value, `Footballers:` doesn't make sense, right?
|
||||
|
||||
To get rid of that comma, you can move the space to the `Footballers:` string directly, and use a plus sign (`+`):
|
||||
|
||||
```python
|
||||
print('Footballers: ' + 'Ronaldo', 'Messi', 'Hazard', 'Kante', 'Okocha', sep=', ')
|
||||
|
||||
# Output: Footballers: Ronaldo, Messi, Hazard, Kante, Okocha
|
||||
```
|
||||
|
||||
This is called string concatenation, which is when you combine multiple strings into one. In this case, you're combing the strings `Footballers:` and `Ronaldo` first, resulting in `Footballers: Ronaldo`, before printing everything to the terminal.
|
||||
|
||||
You'll learn more about string concatenation in future lectures.
|
||||
|
||||
The `end` parameter lets you avoid a common issue with the `print` function, where it automatically prints a new line when you have multiple of it. Here's an example:
|
||||
|
||||
The `end` parameter lets you modify the ending of the output. By default, the end character is a newline character (`\n`), which is helpful in most cases.
|
||||
|
||||
But what if you call `print` multiple times in a row?:
|
||||
|
||||
```python
|
||||
print('Footballers:')
|
||||
print('Ronaldo')
|
||||
print('Messi')
|
||||
print('Hazard')
|
||||
print('Kante')
|
||||
print('Okocha')
|
||||
|
||||
#Output:
|
||||
# Footballers:
|
||||
# Ronaldo
|
||||
# Messi
|
||||
# Hazard
|
||||
# Kante
|
||||
# Okocha
|
||||
```
|
||||
|
||||
To avoid this common issue, you can specify a different value for the `end` argument:
|
||||
|
||||
```python
|
||||
print('Footballers:', end=' ')
|
||||
print('Ronaldo', end=', ')
|
||||
print('Messi', end=', ')
|
||||
print('Hazard', end=', ')
|
||||
print('Kante', end=', ')
|
||||
print('Okocha', end='.')
|
||||
|
||||
#Output: Footballers: Ronaldo, Messi, Hazard, Kante, Okocha.
|
||||
```
|
||||
|
||||
How cool is that?
|
||||
|
||||
Here's how you can use the `file` argument to write the output of the `print` function to a separate file:
|
||||
|
||||
```python
|
||||
with open('output.txt', 'w') as f:
|
||||
print('Hello world!', file=f)
|
||||
```
|
||||
|
||||
This will print the text `Hello world!` into a file named `output.txt`. If the file doesn't exist, it will be automatically created. You will learn more about how working with the filesystem in future lectures.
|
||||
|
||||
The last argument of the `print` function we showed in its basic syntax is `flush`. When set to `True`, it immediately shows what you want to print instead of waiting for a short time.
|
||||
|
||||
The last argument is `flush`. When this is set to `True`, whatever you're outputting is shown immediately rather than waiting for potential delays in the program's execution:
|
||||
|
||||
```python
|
||||
import time
|
||||
|
||||
print('Processing...', end=' ', flush=True)
|
||||
time.sleep(2)
|
||||
print('Done!')
|
||||
```
|
||||
|
||||
In this case, the `Processing…` text immediately appears in the terminal, then `time.sleep(2)` delays the `Done` text from appearing for 2 seconds. This makes `flush` a great tool for displaying progress bars and loading text.
|
||||
|
||||
And that's how the `print` function works!
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
+216
-7
@@ -1,18 +1,227 @@
|
||||
---
|
||||
id: 67fe859a00971c34a23abd43
|
||||
title: What Are Common Data Types in Python and How Do You Get the Type of a Variable?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: what-are-common-data-types-in-python-and-how-do-you-get-the-type-of-a-variable
|
||||
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
Python is a dynamically-typed language like JavaScript, meaning you don't need to explicitly declare types for variables. The language knows what data type a variable is based on what you assign to it.
|
||||
|
||||
Here are some examples:
|
||||
|
||||
```python
|
||||
name = 'John Doe' # Python knows this is a string
|
||||
age = 25 # Python knows this is an integer
|
||||
```
|
||||
|
||||
This is in contrast to some statically-typed languages like C#, Java, and C++, where you have to declare types with variables, like this:
|
||||
|
||||
```csharp
|
||||
string name = 'John Doe'
|
||||
int age = 25
|
||||
```
|
||||
|
||||
The dynamic-typing nature of Python makes coding really fast and more flexible, but it can lead to unexpected bugs because type errors are detected only when a program runs, not when the program compiles.
|
||||
|
||||
Here are the most common data types you'll use in Python:
|
||||
|
||||
- Integer: A whole number without decimals, for example, `10` or `-5`.
|
||||
|
||||
```python
|
||||
my_integer_var = 10
|
||||
print('Integer:', my_integer_var) # Integer: 10
|
||||
```
|
||||
|
||||
- Float: A number with a decimal point, like `4.41` or `-0.4`.
|
||||
|
||||
```python
|
||||
my_float_var = 4.50
|
||||
print('Float:', my_float_var) # Float 4.50
|
||||
```
|
||||
|
||||
- Complex: A number with a real and imaginary part, like `6 + 7j`.
|
||||
|
||||
```python
|
||||
my_complex_var = 3 + 4j
|
||||
print('Complex:', my_complex_var) # Complex: (3+4j)
|
||||
```
|
||||
|
||||
- String: A sequence of characters enclosed in single or double quotation marks like `'Hello world!'`.
|
||||
|
||||
```python
|
||||
my_string_var = 'hello'
|
||||
print('String:', my_string_var) # String: hello
|
||||
```
|
||||
|
||||
- Boolean: A true or false type, written as `True` or `False`.
|
||||
|
||||
```python
|
||||
my_boolean_var = True
|
||||
print('Boolean:', my_boolean_var) # Boolean: True
|
||||
```
|
||||
|
||||
- Set: An unordered collection of unique elements, like `{4, 2, 0}`.
|
||||
|
||||
```python
|
||||
my_set_var = {7, 5, 8}
|
||||
print('Set:', my_set_var) # Set: {7, 5, 8}
|
||||
```
|
||||
|
||||
- Dictionary: A collection of key-value pairs enclosed in curly braces, like `{'name': 'John Doe', 'age': 28}`.
|
||||
|
||||
```python
|
||||
my_dictionary_var = {'name': 'Alice', 'age': 25}
|
||||
print('Dictionary:', my_dictionary_var) # Dictionary: {'name': 'Alice', 'age': 25}
|
||||
```
|
||||
|
||||
- Tuple: An immutable ordered collection, enclosed in brackets, like `(7, 8, 4)`.
|
||||
|
||||
```python
|
||||
my_tuple_var = (7, 5, 8)
|
||||
print('Tuple:', my_tuple_var) # Tuple: (7, 5, 8)
|
||||
```
|
||||
|
||||
- Range: A sequence of numbers, often used in loops, for example, `range(5)`.
|
||||
|
||||
```python
|
||||
my_range_var = range(5)
|
||||
print(my_range_var) # range(0, 5)
|
||||
```
|
||||
|
||||
- List: An ordered collection of elements that supports different data types.
|
||||
|
||||
```python
|
||||
my_list = [22, 'Hello world', 3.14, True]
|
||||
print(my_list) # [22, 'Hello world', 3.14, True]
|
||||
```
|
||||
|
||||
- None: A special value that represents the absence of a value.
|
||||
|
||||
```python
|
||||
my_none_var = None
|
||||
print('None:', my_none_var) # None: None
|
||||
```
|
||||
|
||||
Many other programming languages group data types broadly as either primitive or reference types. Primitive types are simple and immutable, meaning they can't be changed once declared. Reference types can hold multiple values, and are either mutable or immutable. But Python doesn't draw a hard line between those two groups. Instead, all data gets treated as objects, and some objects are immutable while others are mutable.
|
||||
|
||||
Immutable data types can't be modified or altered once they're declared. You can point their variables at something new, which is called reassignment, but you can't change the original object itself by adding, removing, or replacing any of its elements. Examples of immutable data types in Python are string, integer, float, boolean, tuple, and range.
|
||||
|
||||
Here's an example showing that, while you can reassign a different string to a variable, direct modification of a string isn't allowed because strings are immutable:
|
||||
|
||||
```python
|
||||
greeting = 'hi'
|
||||
greeting = 'hello'
|
||||
print(greeting) # hello
|
||||
|
||||
greeting[0] = 'H' # TypeError: 'str' object does not support item assignment
|
||||
```
|
||||
|
||||
On the other hand, you can change mutable types without giving them a new name. You can add, remove, or update items right where they live. Examples are a list and a dictionary.
|
||||
|
||||
Here's an example of updating an element in a list:
|
||||
|
||||
```python
|
||||
nums = [1, 2, 3]
|
||||
nums[0] = 4
|
||||
|
||||
print(nums) # [4, 2, 3]
|
||||
```
|
||||
|
||||
To get the data type of a variable, you can use the `type()` function:
|
||||
|
||||
```python
|
||||
my_var_1 = 'Hello world'
|
||||
my_var_2 = 21
|
||||
|
||||
print(type(my_var_1)) # <class 'str'>
|
||||
print(type (my_var_2)) # <class 'int'>
|
||||
```
|
||||
|
||||
And here's are all the data types covered in this lecture, along with their types in the terminal:
|
||||
|
||||
```python
|
||||
my_integer_var = 10
|
||||
print('Integer:', my_integer_var, '| Type:', type(my_integer_var)) # Integer: 10 | Type: <class 'int'>
|
||||
|
||||
my_float_var = 4.50
|
||||
print('Float:', my_float_var, '| Type:', type(my_float_var)) # Float: 4.50 | Type: <class 'float'>
|
||||
|
||||
my_complex_var = 3 + 4j
|
||||
print('Complex:', my_complex_var, '| Type:', type(my_complex_var)) # Complex: (3+4j) | Type: <class 'complex'>
|
||||
|
||||
my_string_var = 'hello'
|
||||
print('String:', my_string_var, '| Type:', type(my_string_var)) # String: hello | Type: <class 'str'>
|
||||
|
||||
my_boolean_var = True
|
||||
print('Boolean:', my_boolean_var, '| Type:', type(my_boolean_var)) # Boolean: True | Type: <class 'bool'>
|
||||
|
||||
my_set_var = {7, 5, 8}
|
||||
print('Set:', my_set_var, '| Type:', type(my_set_var)) # Set: {7, 5, 8} | Type: <class 'set'>
|
||||
|
||||
my_dictionary_var = {'name': 'Alice', 'age': 25}
|
||||
print('Dictionary:', my_dictionary_var, '| Type:', type(my_dictionary_var)) # Dictionary: {'name': 'Alice', 'age': 25} | Type: <class 'dict'>
|
||||
|
||||
my_tuple_var = (7, 5, 8)
|
||||
print('Tuple:', my_tuple_var, '| Type:', type(my_tuple_var)) # Tuple: (7, 5, 8) | Type: <class 'tuple'>
|
||||
|
||||
my_range_var = range(5)
|
||||
print('Range:', list(my_range_var), '| Type:', type(my_range_var)) # Range: [0, 1, 2, 3, 4] | Type: <class 'range'>
|
||||
|
||||
my_list = [22, 'Hello world', 3.14, True]
|
||||
print('List:', list(my_list), '| Type:', type(my_list)) # List: [22, 'Hello world', 3.14, True] | Type: <class 'list'>
|
||||
|
||||
my_none_var = None
|
||||
print('None:', my_none_var, '| Type:', type(my_none_var)) # None: None | Type: <class 'NoneType'>
|
||||
```
|
||||
|
||||
Another way to check the type of a variable is to use the built-in `isinstance()` function, which checks if a variable matches a specific data type.
|
||||
|
||||
`isinstance()` takes in an object and the type you want to check it against, then returns a boolean. Here are some examples:
|
||||
|
||||
```python
|
||||
isinstance('Hello world', str) # True
|
||||
isinstance(True, bool) # True
|
||||
isinstance(42, int) # True
|
||||
isinstance('John Doe', int) # False
|
||||
```
|
||||
|
||||
Although Python is dynamically typed, you can still add type hints. These are optional signals that tell other developers what the data type of a variable or function is expected to be. Here's a quick example for variable types:
|
||||
|
||||
```python
|
||||
user_name: str = 'John Doe'
|
||||
user_age: int = 24
|
||||
```
|
||||
|
||||
Here's another example showing hints for function parameters and a return type:
|
||||
|
||||
```python
|
||||
def greet(name: str, age: int) -> str:
|
||||
return f'Hello, {name}, age {age}.'
|
||||
```
|
||||
|
||||
And here's a combination of the two:
|
||||
|
||||
```python
|
||||
def greet(name: str, age: int) -> str:
|
||||
return f'Hello, {name}, age {age}.'
|
||||
|
||||
user_name: str = 'John Doe'
|
||||
user_age: int = 24
|
||||
|
||||
print(greet(user_name, user_age)) # Hello, John Doe, age 24.
|
||||
```
|
||||
|
||||
Note that, unlike TypeScript which enforces types at compile time, Python just uses these hints for static analysis, documentation, and editor support, **not** for enforcing types during runtime. This can help developers catch bugs early and improve code readability, especially in large projects.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
@@ -23,7 +232,7 @@ What does it mean that Python is dynamically typed?
|
||||
|
||||
You must manually specify the data type of every variable.
|
||||
|
||||
### --feedback --
|
||||
### --feedback--
|
||||
|
||||
Think about how Python figures out the data type for you.
|
||||
|
||||
@@ -61,7 +270,7 @@ Integers can store both positive and negative numbers, while floats can only sto
|
||||
|
||||
### --feedback--
|
||||
|
||||
One has decimals, the other doesn’t.
|
||||
One has decimals, the other doesn't.
|
||||
|
||||
---
|
||||
|
||||
@@ -73,7 +282,7 @@ Floats take up less memory than integers in Python.
|
||||
|
||||
### --feedback--
|
||||
|
||||
One has decimals, the other doesn’t.
|
||||
One has decimals, the other doesn't.
|
||||
|
||||
---
|
||||
|
||||
@@ -82,7 +291,7 @@ Integers can only store numbers up to 1000, while floats have no limit.
|
||||
|
||||
### --feedback--
|
||||
|
||||
One has decimals, the other doesn’t.
|
||||
One has decimals, the other doesn't.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
|
||||
+198
-7
@@ -1,18 +1,209 @@
|
||||
---
|
||||
id: 67fe859c1ab68734d7c666cb
|
||||
title: How Do You Work With Strings?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: how-do-you-work-with-strings
|
||||
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
A string is a sequence of characters surrounded by either single or double quotation marks. In some programming languages, characters surrounded by single quotes are treated differently than characters surrounded by double quotes, but in Python, they're treated equally. So, you can use either when working with strings. Here are some examples of strings:
|
||||
|
||||
```python
|
||||
my_str_1 = 'Hello'
|
||||
my_str_2 = "World"
|
||||
```
|
||||
|
||||
If you need a multi-line string, you can use triple double quotes or single quotes:
|
||||
|
||||
```python
|
||||
my_str_3 = """Multiline
|
||||
string"""
|
||||
my_str_4 = '''Another
|
||||
multiline
|
||||
string'''
|
||||
```
|
||||
|
||||
If your string contains either single or double quotation marks, then you have two options:
|
||||
|
||||
- Use the opposite kind of quotes. That is, if your string contains single quotes, use double quotes to wrap the string, and vice versa:
|
||||
|
||||
|
||||
```python
|
||||
msg = "It's a sunny day"
|
||||
quote = 'She said, "Hello World!"'
|
||||
```
|
||||
|
||||
- Escape the single or double quotation mark in the string with a backslash (`\`). With this method, you can use either single or double quotation marks to wrap the string itself:
|
||||
|
||||
|
||||
```python
|
||||
msg = 'It\'s a sunny day'
|
||||
quote = "She said, \"Hello!\""
|
||||
```
|
||||
|
||||
You can also combine multiple strings together with the plus (`+`) operator. This process is called string concatenation. Here's how to concatenate two strings with the plus operator:
|
||||
|
||||
```python
|
||||
my_str_1 = 'Hello'
|
||||
my_str_2 = "World"
|
||||
|
||||
str_plus_str = my_str_1 + ' ' + my_str_2
|
||||
print(str_plus_str) # Hello World
|
||||
```
|
||||
|
||||
But note that this only works with strings. If you try to concatenate a string with a number, you'll get a `TypeError`:
|
||||
|
||||
```python
|
||||
name = 'John Doe'
|
||||
age = 26
|
||||
|
||||
name_and_age = name + age
|
||||
print(name_and_age) # TypeError: can only concatenate str (not "int") to str
|
||||
```
|
||||
|
||||
This happens because Python does not automatically convert other data types like integers into strings when you concatenate them. Python requires all elements to be strings before it can concatenate them. To fix that, you can convert the number into a string with the built-in `str()` function:
|
||||
|
||||
```python
|
||||
name = 'John Doe'
|
||||
age = 26
|
||||
|
||||
name_and_age = name + str(age)
|
||||
print(name_and_age) # John Doe26
|
||||
```
|
||||
|
||||
You can also use the augmented assignment operator for concatenation. This is represented by a plus and equals sign (`+=`), and performs both concatenation and assignment in one step. Here's it in action:
|
||||
|
||||
```py
|
||||
name = 'John Doe'
|
||||
age = 26
|
||||
|
||||
name_and_age = name # Start with the name
|
||||
name_and_age += str(age) # Append the age as string
|
||||
|
||||
print(name_and_age) # John Doe26
|
||||
```
|
||||
|
||||
Apart from regular strings, Python also has a category of string called **f-strings**, which is short for formatted string literals. It allows you to handle interpolation and also do some concatenation with a compact and readable syntax.
|
||||
|
||||
F-strings start with `f` (either lowercase or uppercase) before the quotes, and allow you to embed variables or expressions inside replacement fields indicated by curly braces (`{}`). Here's an example:
|
||||
|
||||
```python
|
||||
name = 'John Doe'
|
||||
age = 26
|
||||
name_and_age = f'My name is {name} and I am {age} years old'
|
||||
print(name_and_age) # My name is John Doe and I am 26 years old
|
||||
|
||||
num1 = 5
|
||||
num2 = 10
|
||||
print(f'The sum of {num1} and {num2} is {num1 + num2}') # The sum of 5 and 10 is 15
|
||||
```
|
||||
|
||||
Now that you've learned about string concatenation and f-strings, let's look at how you can get the length of a string and work with the individual characters in a string, a process called **indexing**. To get the length of a string, you can use the built-in `len()` function. Here's an example:
|
||||
|
||||
```python
|
||||
my_str = 'Hello world'
|
||||
print(len(my_str)) # 11
|
||||
```
|
||||
|
||||
Now onto indexing. Each character in a string has a position called an index. The index is zero-based, meaning that the index of the first character of a string is `0`, the index of the second character is `1`, and so on. To access a character by its index, you use square brackets (`[]`) with the index of the character you want to access inside. Here are some examples:
|
||||
|
||||
```python
|
||||
my_str = "Hello world"
|
||||
|
||||
print(my_str[0]) # H
|
||||
print(my_str[6]) # w
|
||||
```
|
||||
|
||||
Negative indexing is also allowed, so you can get the last character of any string with `-1`, the second-to-last character with `-2`, and so on:
|
||||
|
||||
```python
|
||||
my_str = 'Hello world'
|
||||
print(my_str[-1]) # d
|
||||
print(my_str[-2]) # l
|
||||
```
|
||||
|
||||
Now that you're familiar with indexing, let's take things a bit further with **string slicing**. String slicing lets you extract a portion of a string or work with only a specific part of it. Here's the basic syntax:
|
||||
|
||||
```python
|
||||
string[start:stop]
|
||||
```
|
||||
|
||||
If you want to extract characters from a certain index to another, you just separate the `start` and `stop` indices with a colon:
|
||||
|
||||
```python
|
||||
my_str = 'Hello world'
|
||||
print(my_str[1:4]) # ell
|
||||
```
|
||||
|
||||
Note that the `stop` index is non-inclusive, so `[1:4]` just extracted the characters from index `1`, and up to, but not including, the character at index `4`.
|
||||
|
||||
You can also omit the `start` and `stop` indices, and Python will default to `0` or the end of the string, respectively. For example, here's what happens if you omit the `start` index:
|
||||
|
||||
```python
|
||||
my_str = 'Hello world'
|
||||
print(my_str[:7]) # Hello w
|
||||
```
|
||||
|
||||
This extracts everything from index `0` up to (but not including), the character at index `7`. And here's what happens if you omit the `stop` index:
|
||||
|
||||
```python
|
||||
my_str = 'Hello world'
|
||||
print(my_str[8:]) # rld
|
||||
```
|
||||
|
||||
This extracts everything from the character at index `8` until the end of the string.
|
||||
|
||||
You can also omit both the `start` and `stop` indices, which will extract the whole string:
|
||||
|
||||
```python
|
||||
my_str = 'Hello world'
|
||||
print(my_str[:]) # Hello world
|
||||
```
|
||||
|
||||
Apart from the `start` and `stop` indices, there's also an optional step parameter, which is used to specify the increment between each index in the slice.
|
||||
|
||||
Here's the syntax for that:
|
||||
|
||||
```python
|
||||
string[start:stop:step]
|
||||
```
|
||||
|
||||
In the example below, the slicing starts at index `0`, stops before `11`, and extracts every second character:
|
||||
|
||||
```python
|
||||
my_str = 'Hello world'
|
||||
print(my_str[0:11:2]) # Hlowrd
|
||||
```
|
||||
|
||||
A helpful trick you can do with the `step` parameter is to reverse a string by setting step to `-1`, and leaving `start` and `stop` blank:
|
||||
|
||||
```python
|
||||
my_str = 'Hello world'
|
||||
print(my_str[::-1]) # dlrow olleH
|
||||
```
|
||||
|
||||
It can also be helpful to check if a character or set of characters exist in a string before slicing it. To do that, Python provides the `in` operator, which returns a boolean that specifies whether the character or characters exist in the string or not.
|
||||
|
||||
Here are some examples:
|
||||
|
||||
```python
|
||||
my_str = 'Hello world'
|
||||
|
||||
print('Hello' in my_str) # True
|
||||
print('hey' in my_str) # False
|
||||
print('hi' in my_str) # False
|
||||
print('e' in my_str) # True
|
||||
print('f' in my_str) # False
|
||||
```
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
@@ -57,7 +248,7 @@ How do you define a multiline string in Python?
|
||||
|
||||
## --answers--
|
||||
|
||||
Use parentheses `()` around the string.
|
||||
Using parentheses `()` around the string.
|
||||
|
||||
### --feedback--
|
||||
|
||||
@@ -65,11 +256,11 @@ Python allows special quotes for multiline strings.
|
||||
|
||||
---
|
||||
|
||||
Use triple double quotes `"""` or triple single quotes `'''`.
|
||||
Using triple double quotes `"""` or triple single quotes `'''`.
|
||||
|
||||
---
|
||||
|
||||
Use a backslash `\` at the end of each line.
|
||||
Using a backslash `\` at the end of each line.
|
||||
|
||||
### --feedback--
|
||||
|
||||
@@ -77,7 +268,7 @@ Python allows special quotes for multiline strings.
|
||||
|
||||
---
|
||||
|
||||
Use square brackets `[]` to enclose the string.
|
||||
Using square brackets `[]` to enclose the string.
|
||||
|
||||
### --feedback--
|
||||
|
||||
|
||||
+265
-3
@@ -1,18 +1,280 @@
|
||||
---
|
||||
id: 67fe859e9d3b3635197781c8
|
||||
title: How Do You Work With Integers and Floating Point Numbers?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: how-do-you-work-with-integers-and-floating-point-numbers
|
||||
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
Integers and floats are the primary numeric data types in Python. With them, you can store numeric data and perform mathematical operations.
|
||||
|
||||
Let's look at what integers and floats are, how to perform arithmetic calculations with them, and at several methods Python provides for working with both.
|
||||
|
||||
Integers are whole numbers without decimal points, either positive or negative:
|
||||
|
||||
```python
|
||||
my_int_1 = 56
|
||||
my_int_2 = -4
|
||||
|
||||
print(type(my_int_1)) # <class 'int'>
|
||||
print(type(my_int_2)) # <class 'int'>
|
||||
```
|
||||
|
||||
Here's how to perform an addition operation with integers:
|
||||
|
||||
```python
|
||||
my_int_1 = 56
|
||||
my_int_2 = 12
|
||||
|
||||
sum_ints = my_int_1 + my_int_2
|
||||
print('Integer Addition:', sum_ints) # Integer Addition: 68
|
||||
```
|
||||
|
||||
Here's how to perform a subtraction with integers:
|
||||
|
||||
```python
|
||||
my_int_1 = 56
|
||||
my_int_2 = 12
|
||||
|
||||
# Subtraction
|
||||
diff_ints = my_int_1 - my_int_2
|
||||
print('Integer Subtraction:', diff_ints) # Integer Subtraction: 44
|
||||
```
|
||||
|
||||
Here's how to perform a multiplication operation with integers:
|
||||
|
||||
```python
|
||||
my_int_1 = 12
|
||||
my_int_2 = 4
|
||||
|
||||
# Multiplication
|
||||
product_ints = my_int_1 * my_int_2
|
||||
print('Integer Multiplication:', product_ints) # Integer Multiplication: 48
|
||||
```
|
||||
|
||||
And here's how to perform a division operation with integers:
|
||||
|
||||
```python
|
||||
my_int_1 = 56
|
||||
my_int_2 = 12
|
||||
|
||||
# Division
|
||||
div_ints = my_int_1 / my_int_2
|
||||
print('Integer Division:', div_ints) # Integer Division: 4.666666666666667
|
||||
```
|
||||
|
||||
Floats are positive or negative numbers with decimal points, like `3.14`, `-0.5`, or `0.0`.
|
||||
|
||||
```python
|
||||
my_float_1 = -12.0
|
||||
my_float_2 = 4.9
|
||||
|
||||
print(type(my_float_1)) # <class 'float'>
|
||||
print(type(my_float_2)) # <class 'float'>
|
||||
```
|
||||
|
||||
Here's an addition operation with floats:
|
||||
|
||||
```python
|
||||
my_float_1 = 5.4
|
||||
my_float_2 = 12.0
|
||||
|
||||
float_addition = my_float_1 + my_float_2
|
||||
print('Float Addition:', float_addition) # Float Addition: 17.4
|
||||
```
|
||||
|
||||
Here's a subtraction operation with floats:
|
||||
|
||||
```python
|
||||
my_float_1 = 5.4
|
||||
my_float_2 = 12.0
|
||||
|
||||
float_subtraction = my_float_2 - my_float_1
|
||||
print('Float Subtraction:', float_subtraction) # Float Subtraction: 6.6
|
||||
```
|
||||
|
||||
Here's a multiplication operation with floats:
|
||||
|
||||
```python
|
||||
my_float_1 = 5.4
|
||||
my_float_2 = 12.0
|
||||
|
||||
float_multiplication = my_float_2 * my_float_1
|
||||
print('Float Multiplication:', float_multiplication) # Float Multiplication: 64.80000000000001
|
||||
```
|
||||
|
||||
And here's a division operation with floats:
|
||||
|
||||
```python
|
||||
my_float_1 = 5.4
|
||||
my_float_2 = 12.0
|
||||
|
||||
float_division = my_float_2 / my_float_1
|
||||
print('Float Division:', float_division) # Float Division: 2.222222222222222
|
||||
```
|
||||
|
||||
If you add an integer and a float, the result is automatically converted to a float:
|
||||
|
||||
```python
|
||||
my_int = 56
|
||||
my_float = 5.4
|
||||
|
||||
sum_int_and_float = my_int + my_float
|
||||
|
||||
print(sum_int_and_float) # 61.4
|
||||
print(type(sum_int_and_float)) # <class 'float'>
|
||||
```
|
||||
|
||||
This is true for other basic arithmetic operations, too, like subtraction, multiplication, and division. If you mix integers and floats, Python will return a float as the result.
|
||||
|
||||
You can also perform more complex arithmetic calculations such as getting the remainder of two numbers with the modulo operator, floor division, and exponentiation with both integers and floats.
|
||||
|
||||
The modulo operator (`%`) returns the remainder when the value on the left is divided by the value on the right:
|
||||
|
||||
```python
|
||||
my_int_1 = 56
|
||||
my_int_2 = 12
|
||||
|
||||
my_float_1 = 5.4
|
||||
my_float_2 = 12.0
|
||||
|
||||
mod_ints = my_int_1 % my_int_2
|
||||
mod_floats = my_float_2 % my_float_1
|
||||
|
||||
print('Integer Modulus:', mod_ints) # Integer Modulus: 8
|
||||
print('Float Modulus:', mod_floats) # Float Modulus: 1.1999999999999993
|
||||
```
|
||||
|
||||
Floor division divides two numbers and rounds down the result to the nearest whole number. This is done with the double forward slash operator (`//`):
|
||||
|
||||
```python
|
||||
my_int_1 = 56
|
||||
my_int_2 = 12
|
||||
|
||||
my_float_1 = 5.4
|
||||
my_float_2 = 12.0
|
||||
|
||||
floor_div_ints = my_int_1 // my_int_2
|
||||
floor_div_floats = my_float_2 // my_float_1
|
||||
|
||||
print('Integer Floor Division:', floor_div_ints) # Integer Floor Division: 4
|
||||
print('Float Floor Division:', floor_div_floats) # Float Floor Division: 2.0
|
||||
```
|
||||
|
||||
Exponentiation raises a number to the power of another, and is done with the double asterisk operator (`**`):
|
||||
|
||||
```python
|
||||
my_int_1 = 56
|
||||
my_int_2 = 12
|
||||
|
||||
my_float_1 = 5.4
|
||||
my_float_2 = 12.0
|
||||
|
||||
exp_ints = my_int_1 ** my_int_2
|
||||
exp_floats = my_float_1 ** my_float_2
|
||||
|
||||
print('Integer Exponentiation:', exp_ints) # Integer Exponentiation: 951166013805414055936
|
||||
print('Float Exponentiation:', exp_floats) # Float Exponentiation: 614787626.1765089
|
||||
```
|
||||
|
||||
Python also provides built-in functions for converting either numeric data or strings into integers or floats. You can use the `float()` function to convert an integer into a float by adding a decimal point of `0` to the integer:
|
||||
|
||||
```python
|
||||
my_int_1 = 56
|
||||
my_float_1 = float(my_int_1)
|
||||
|
||||
print(my_float_1) # 56.0
|
||||
print(type(my_float_1)) # <class 'float'>
|
||||
```
|
||||
|
||||
And you can use the `int()` function to convert a float into an integer, which removes the decimal point and everything after it from the float you pass it:
|
||||
|
||||
```python
|
||||
my_float = 12.92563
|
||||
my_int = int(my_float)
|
||||
|
||||
print(my_int) # 12
|
||||
print(type(my_int)) # <class 'int'>
|
||||
```
|
||||
|
||||
Also, you can use the same built-in functions to convert a string into either a float or integer:
|
||||
|
||||
```python
|
||||
my_str_int = '45'
|
||||
my_str_float = '7.8'
|
||||
|
||||
converted_int = int(my_str_int)
|
||||
converted_float = float(my_str_float)
|
||||
|
||||
print(converted_int, type(converted_int)) # 45 <class 'int'>
|
||||
print(converted_float, type(converted_float)) # 7.8 <class 'float'>
|
||||
```
|
||||
|
||||
Here are some other methods Python provides for working with integers and floats.
|
||||
|
||||
- `round()`: Rounds a number to the specified number of decimal places. By default this function rounds to the nearest integer, and returns a whole number with no decimal places:
|
||||
|
||||
|
||||
```python
|
||||
my_int_1 = 4.798
|
||||
my_int_2 = 4.253
|
||||
|
||||
rounded_int_1 = round(my_int_1)
|
||||
rounded_int_2 = round(my_int_2, 1)
|
||||
|
||||
print(rounded_int_1) # 5
|
||||
print(rounded_int_2) # 4.3
|
||||
```
|
||||
|
||||
- `abs()`: returns the absolute value of a number,
|
||||
|
||||
|
||||
```python
|
||||
num = -15
|
||||
|
||||
absolute_value = abs(num)
|
||||
print(absolute_value) # 15
|
||||
```
|
||||
|
||||
- `bin()`: converts an integer to its binary representation as a string.
|
||||
|
||||
- `oct()`: converts an integer to its octal representation as a string.
|
||||
|
||||
- `hex()`: converts an integer to its hexadecimal representation as a string.
|
||||
|
||||
|
||||
```python
|
||||
my_int = 56
|
||||
|
||||
binary_representation = bin(my_int)
|
||||
print(binary_representation) # 0b111000
|
||||
|
||||
octal_representation = oct(my_int)
|
||||
print(octal_representation) # 0o70
|
||||
|
||||
hex_representation = hex(my_int)
|
||||
print(hex_representation) # 0x38
|
||||
```
|
||||
|
||||
- `pow()`: raises a number to the power of another or performs modular exponentiation.
|
||||
|
||||
|
||||
```python
|
||||
result_1 = pow(2, 3) # Equivalent to 2 ** 3
|
||||
print(result_1) # 8
|
||||
|
||||
result_2 = pow(2, 3, 5) # (2 ** 3) % 5
|
||||
print(result_2) # 3
|
||||
```
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
+129
-4
@@ -1,17 +1,142 @@
|
||||
---
|
||||
id: 67fe859f55cd33356e322fd3
|
||||
title: How Do Functions Work in Python?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: how-do-functions-work-in-python
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
Functions are reusable pieces of code that run when you call them. Many programming languages come with built-in functions that make it easier to get started. Python is no exception, and we've already covered some built-in functions like `print()` in previous lectures.
|
||||
|
||||
Another helpful built-in function is `input()`, which lets you prompt the user for input:
|
||||
|
||||
```python
|
||||
name = input('What is your name?') # User types "Kolade" and presses Enter
|
||||
print('Hello', name) # Output: Hello Kolade
|
||||
```
|
||||
|
||||
On the other hand, `int()` converts a number, boolean, and a numeric string into an integer:
|
||||
|
||||
```python
|
||||
print(int(3.14)) # 3
|
||||
print(int('42')) # 42
|
||||
print(int(True)) # 1
|
||||
print(int(False)) # 0
|
||||
```
|
||||
|
||||
You can also write your own custom functions. To do that, you use the `def` keyword, followed by the name you want to give your function, a pair of parentheses, and a colon. Then on a new line, you write the code your function should run. The code the function runs is also referred to as the function's body.
|
||||
|
||||
Here's an example of a custom function named `hello` that prints the string `Hello World` to the terminal:
|
||||
|
||||
```python
|
||||
def hello():
|
||||
print('Hello World')
|
||||
```
|
||||
|
||||
To run the function, you need to call it with its name followed by a pair of parentheses:
|
||||
|
||||
```python
|
||||
hello() # Hello World
|
||||
```
|
||||
|
||||
Notice the indentation before `print('Hello World')`. The level of indentation defines a "code block" in Python, which is a group of statements that belong together.
|
||||
|
||||
While other programming languages use characters like curly braces to define code blocks, and just use indentation for readability, in Python, code blocks are determined by indentation.
|
||||
|
||||
Though you can use either two or four spaces to determine each level of indentation, the Python style guide recommends using four spaces.
|
||||
|
||||
Blocks are also found in loops and conditionals, which you'll learn about in future lectures.
|
||||
|
||||
Here's another simple function that prints the sum of two numbers to the terminal:
|
||||
|
||||
```python
|
||||
def calculate_sum(a, b):
|
||||
print(a + b)
|
||||
```
|
||||
|
||||
You can see that our function, `calculate_sum`, has `a` and `b` in its parentheses, separated by a comma. Those are called parameters. Think of parameters as placeholder variables that act as "slots" for the values you pass into functions when you call them.
|
||||
|
||||
To use the parameters, you have to pass in "arguments". Arguments are the values you pass to a function when you call it.
|
||||
|
||||
Here's how to call the `calculate_sum` function to sum together the numbers `3` and `1`:
|
||||
|
||||
```python
|
||||
calculate_sum(3, 1) # 4
|
||||
```
|
||||
|
||||
If you call the function without the correct number of arguments, you'll get a `TypeError`:
|
||||
|
||||
```python
|
||||
calculate_sum()
|
||||
|
||||
# TypeError: calculate_sum() missing 2 required positional arguments: 'a' and 'b'
|
||||
```
|
||||
|
||||
Functions also use a special `return` keyword to exit the function and return a value. If you don't explicitly use `return`, Python will return `None` by default.
|
||||
|
||||
Here's an example:
|
||||
|
||||
```python
|
||||
def calculate_sum(a, b):
|
||||
print(a + b)
|
||||
|
||||
my_sum = calculate_sum(3, 1) # 4
|
||||
print(my_sum) # None
|
||||
```
|
||||
|
||||
You can see that the `calculate_sum` function prints the sum of `a` and `b`, but it doesn't return anything explicitly. So when we assign its result to `my_sum`, the value is actually `None`. To fix that, you can use the `return` keyword to send back the result:
|
||||
|
||||
```python
|
||||
def calculate_sum(a, b):
|
||||
return a + b
|
||||
|
||||
my_sum = calculate_sum(3, 1)
|
||||
print(my_sum) # 4
|
||||
```
|
||||
|
||||
Now, `calculate_sum` returns the sum of `a` and `b`, which gets stored in `my_sum`.
|
||||
|
||||
Decorators are a special kind of function in Python. They are like wrappers for other functions, so they take another function as an argument. With decorators, you get to add extra functionality to a function without modifying its original code. Here's an example of how to use a decorator:
|
||||
|
||||
```python
|
||||
def say_hello():
|
||||
name = input('What is your name? ')
|
||||
return 'Hello ' + name
|
||||
|
||||
def uppercase_decorator(func):
|
||||
def wrapper():
|
||||
original_func = func()
|
||||
modified_func = original_func.upper()
|
||||
return modified_func
|
||||
return wrapper
|
||||
|
||||
say_hello_res = uppercase_decorator(say_hello)
|
||||
|
||||
print(say_hello_res())
|
||||
```
|
||||
|
||||
In this code:
|
||||
|
||||
- We are getting a user input and storing it in a `name` variable.
|
||||
|
||||
- The function `say_hello` returns `Hello`, and the `name`.
|
||||
|
||||
- The decorator, `uppercase_decorator` takes a function, calls it, then turns its return value to uppercase, and returns the original function.
|
||||
|
||||
- The `uppercase_decorator` function is then called with the original `say_hello` function and saved in `say_hello_res`.
|
||||
|
||||
- `say_hello_res` is then called and printed in one line.
|
||||
|
||||
|
||||
That's how decorators are typically used.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
@@ -92,7 +217,7 @@ What is the purpose of decorators in Python?
|
||||
|
||||
## --answers--
|
||||
|
||||
They modify a function’s original code directly to add extra functionality.
|
||||
They modify a function's original code directly to add extra functionality.
|
||||
|
||||
### --feedback--
|
||||
|
||||
|
||||
+147
-3
@@ -1,17 +1,161 @@
|
||||
---
|
||||
id: 67fe85a1b634a335b18ae09a
|
||||
title: What Is Scope in Python and How Does It Work?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: what-is-scope-in-python-and-how-does-it-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
In Python, scope determines the point at which you can access a variable. It's what controls the lifetime of a variable and how it is resolved in different parts of the code.
|
||||
|
||||
To correctly determine scope, Python follows the **LEGB** rule, which stands for the following:
|
||||
|
||||
- **Local scope (L)**: Variables defined in functions or classes.
|
||||
|
||||
- **Enclosing scope (E)**: Variables defined in enclosing or nested functions.
|
||||
|
||||
- **Global scope (G):** Variables defined at the top level of the module or file.
|
||||
|
||||
- **Built-in scope (B)**: Reserved names in Python for predefined functions, modules, keywords, and objects.
|
||||
|
||||
Python uses the LEGB rule to resolve the scope of the variables in your program. We'll dive into each of these rules so you get a better understanding of the process.
|
||||
|
||||
**Local scope** means that a variable declared inside a function or class can only be accessed within that function or class.
|
||||
|
||||
Here's an example:
|
||||
|
||||
```python
|
||||
def my_func():
|
||||
my_var = 10
|
||||
print(my_var)
|
||||
```
|
||||
|
||||
In this case, the `my_func` function has its own scope which cannot be accessed from outside the function. Calling `my_func` will output `10`, but printing `my_var` outside the function will lead to a `NameError`:
|
||||
|
||||
```python
|
||||
def my_func():
|
||||
my_var = 10 # Locally scoped to my_func
|
||||
print(my_var)
|
||||
|
||||
my_func() # 10
|
||||
|
||||
print(my_var) # NameError: name 'my_var' is not defined
|
||||
```
|
||||
|
||||
**Enclosing scope** means that a function that's nested inside another function can access the variables of the function it's nested within.
|
||||
|
||||
For example:
|
||||
|
||||
```python
|
||||
def outer_func():
|
||||
msg = 'Hello there!'
|
||||
|
||||
def inner_func():
|
||||
print(msg)
|
||||
|
||||
inner_func()
|
||||
|
||||
outer_func() # Hello there!
|
||||
```
|
||||
|
||||
In this example, the inner function, `inner_func`, can freely access the `msg` variable defined in the outer function, `outer_func`. However, note that outer functions cannot access variables defined within any nested functions:
|
||||
|
||||
```python
|
||||
def outer_func():
|
||||
msg = 'Hello there!'
|
||||
print(res)
|
||||
|
||||
def inner_func():
|
||||
res = 'How are you?'
|
||||
print(msg)
|
||||
|
||||
inner_func()
|
||||
|
||||
outer_func() # NameError: name 'res' is not defined
|
||||
```
|
||||
|
||||
That's because `res` is locally scoped to `inner_func`. Also, notice that `outer_func` tries to print `res` before `inner_func` is called.
|
||||
|
||||
One solution is to initialize `res` as an empty string in the enclosing scope, which is within `outer_func`. Then within `inner_func`, make `res` a non-local variable with the `nonlocal` keyword:
|
||||
|
||||
```python
|
||||
def outer_func():
|
||||
msg = 'Hello there!'
|
||||
res = "" # Declare res in the enclosing scope
|
||||
|
||||
def inner_func():
|
||||
nonlocal res # Allow modification of an enclosing variable
|
||||
res = 'How are you?'
|
||||
print(msg) # Accessing msg from outer_func()
|
||||
|
||||
inner_func()
|
||||
print(res) # Now res is accessible and modified
|
||||
|
||||
outer_func()
|
||||
|
||||
# Output:
|
||||
# Hello there!
|
||||
# How are you?
|
||||
```
|
||||
|
||||
**Global scope** refers to variables that are declared outside any functions or classes which can be accessed from anywhere in the program. Here, `my_var` can be accessed anywhere, even inside a function it's not defined in:
|
||||
|
||||
```python
|
||||
my_var = 100
|
||||
|
||||
def show_var():
|
||||
print(my_var)
|
||||
|
||||
show_var() # 100
|
||||
print(my_var) # 100
|
||||
```
|
||||
|
||||
And if you want to make a locally scoped variable defined inside a function globally accessible, you can use the `global` keyword:
|
||||
|
||||
```python
|
||||
my_var_1 = 7
|
||||
|
||||
def show_vars():
|
||||
global my_var_2
|
||||
my_var_2 = 10
|
||||
print(my_var_1)
|
||||
print(my_var_2)
|
||||
|
||||
show_vars() # 7 10
|
||||
|
||||
# my_var_2 is now a global variable and can be accessed anywhere in the program
|
||||
print(my_var_2) # 10
|
||||
```
|
||||
|
||||
You can also use the `global` keyword to modify a global variable:
|
||||
|
||||
```python
|
||||
my_var = 10 # A global variable
|
||||
|
||||
def change_var():
|
||||
global my_var # Allows modification of a global variable
|
||||
my_var = 20
|
||||
|
||||
change_var()
|
||||
|
||||
print(my_var) # my_var is now modified globally to 20
|
||||
```
|
||||
|
||||
Finally, **built-in scope** refers to all of Python's built-in functions, modules, and keywords, and are available anywhere in your program:
|
||||
|
||||
```python
|
||||
print(str(45)) # '45'
|
||||
print(type(3.14)) # <class 'float'>
|
||||
print(isinstance(3, str)) # False
|
||||
```
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
+175
-33
@@ -1,30 +1,161 @@
|
||||
---
|
||||
id: 67fe85a3db9bad35f2b6a2bd
|
||||
title: How Do Conditional Statements and Logical Operators Work?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: how-do-conditional-statements-and-logical-operators-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
Conditional statements, or conditionals, let you control the flow of your program based on whether certain conditions are true or false.
|
||||
|
||||
But before we get into all that, let's go over the basic building blocks of conditional statements, starting with comparison operators. Comparison operators are operators that let you compare two or more values, and return a boolean value.
|
||||
|
||||
In a previous lecture, you learned that booleans are one of the data types in Python, and can only be `True` or `False`.
|
||||
|
||||
Here's a table with the comparison operators in Python:
|
||||
|
||||
| Operator | Name | Description |
|
||||
| --- | --- | --- |
|
||||
| `==` | Equal | Checks if two values are equal |
|
||||
| `!=` | Not equal | Checks if two values are not equal |
|
||||
| `>` | Greater than | Checks if the value on the left is greater than the value on the right |
|
||||
| `<` | Less than | Checks if the value on the left is less than the value on the right |
|
||||
| `>=` | Greater than or equal | Checks if the value on the left is greater than or equal to the value on the right |
|
||||
| `<=` | Less than or equal | Checks if the value on the left is less than or equal to the value on the right |
|
||||
|
||||
Here are some of those expressions that evaluate to `True` or `False`:
|
||||
|
||||
```python
|
||||
print(3 > 4) # False
|
||||
print(3 < 4) # True
|
||||
print(3 == 4) # False
|
||||
print(4 == 4) # True
|
||||
print(3 != 4) # True
|
||||
print(3 >= 4) # False
|
||||
print(3 <= 4) # True
|
||||
```
|
||||
|
||||
These operators can be used in conditionals to compare values and run certain code based on whether the conditional evaluates to `True` or `False`.
|
||||
|
||||
In Python, the most basic conditional is the `if` statement. Here's the basic syntax:
|
||||
|
||||
```python
|
||||
if condition:
|
||||
# Code to execute if condition is True
|
||||
```
|
||||
|
||||
* `if` statements start with the `if` keyword.
|
||||
|
||||
* `condition` is an expression that evaluates to `True` of `False`, followed by a colon (`:`).
|
||||
|
||||
* The indentation specifies the block of code within the body of the `if` statement.
|
||||
|
||||
|
||||
And here's an example:
|
||||
|
||||
```python
|
||||
age = 18
|
||||
|
||||
if age >= 18:
|
||||
print('You are an adult') # You are an adult
|
||||
```
|
||||
|
||||
But if `age` is anything less than `18`, nothing is printed in the terminal:
|
||||
|
||||
```python
|
||||
age = 12
|
||||
|
||||
if age >= 18:
|
||||
print('You are an adult') # Nothing shows up in the terminal
|
||||
```
|
||||
|
||||
But what if you also want to print something if `age` is less than `18`? That's where the `else` clause comes in. The `else` clause runs when the `if` condition is false. Here's the syntax for an `if…else` statement:
|
||||
|
||||
```python
|
||||
if condition:
|
||||
# Code to execute if condition is True
|
||||
else:
|
||||
# Code to execute if condition is False
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
```python
|
||||
age = 12
|
||||
|
||||
if age >= 18:
|
||||
print('You are an adult')
|
||||
else:
|
||||
print('You are not an adult yet') # You are not an adult yet
|
||||
```
|
||||
|
||||
There might be situations in which you want to account for multiple conditions. To do that, Python lets you extend your if statement with the `elif` (else if) keyword.
|
||||
|
||||
Here's the syntax:
|
||||
|
||||
```python
|
||||
if condition:
|
||||
# Code to execute if condition is True
|
||||
elif condition2:
|
||||
# Code to execute if condition2 is True
|
||||
else:
|
||||
# Code to execute if all conditions are False
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
```python
|
||||
age = 12
|
||||
|
||||
if age >= 18:
|
||||
print('You are an adult')
|
||||
elif age >= 13:
|
||||
print('You are a teenager')
|
||||
else:
|
||||
print('You are a child') # You are a child
|
||||
```
|
||||
|
||||
Note that you can use as many `elif` statements as you want:
|
||||
|
||||
```python
|
||||
age = 2
|
||||
|
||||
if age >= 65:
|
||||
print('You are a senior citizen')
|
||||
elif age >= 30:
|
||||
print('You are an adult in your prime')
|
||||
elif age >= 18:
|
||||
print('You are a young adult')
|
||||
elif age >= 13:
|
||||
print('You are a teenager')
|
||||
elif age >= 3:
|
||||
print('You are a young child')
|
||||
else:
|
||||
print('You are a toddler or an infant') # You are a toddler or an infant
|
||||
```
|
||||
|
||||
Now that you understand how comparison operators and conditional statements work in Python, you can start writing programs that make decisions based on logic and input. Whether you’re comparing values or branching through multiple conditions, these tools are the foundation to writing flexible, responsive code.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
What do logical operators do?
|
||||
What do comparison operators do?
|
||||
|
||||
## --answers--
|
||||
|
||||
Perform mathematical calculations with boolean values.
|
||||
Perform mathematical calculations with boolean values
|
||||
|
||||
### --feedback--
|
||||
|
||||
They help create more complex decision-making logic by working with multiple conditions.
|
||||
These operators check things like equality or which value is greater, and the result is either `True` or `False`.
|
||||
|
||||
---
|
||||
|
||||
@@ -32,11 +163,11 @@ Convert strings to boolean values.
|
||||
|
||||
### --feedback--
|
||||
|
||||
They help create more complex decision-making logic by working with multiple conditions.
|
||||
These operators check things like equality or which value is greater, and the result is either `True` or `False`.
|
||||
|
||||
---
|
||||
|
||||
Combine multiple conditions within conditional statements.
|
||||
Compare two values and return a boolean value.
|
||||
|
||||
---
|
||||
|
||||
@@ -44,7 +175,7 @@ Create loops and iterations.
|
||||
|
||||
### --feedback--
|
||||
|
||||
They help create more complex decision-making logic by working with multiple conditions.
|
||||
These operators check things like equality or which value is greater, and the result is either `True` or `False`.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
@@ -52,72 +183,83 @@ They help create more complex decision-making logic by working with multiple con
|
||||
|
||||
## --text--
|
||||
|
||||
What is the primary purpose of comparison operators in programming?
|
||||
What will be the result for the following code?
|
||||
|
||||
```python
|
||||
age = 12
|
||||
|
||||
if age >= 18:
|
||||
print('You are an adult')
|
||||
elif age >= 13:
|
||||
print('You are a teenager')
|
||||
else:
|
||||
print('You are a child')
|
||||
```
|
||||
|
||||
## --answers--
|
||||
|
||||
To modify variable values.
|
||||
`You are an adult` will be printed to the console.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how they evaluate relationships between values.
|
||||
Review the last part of the lecture for the correct answer.
|
||||
|
||||
---
|
||||
|
||||
To return `True` or `False` based on value comparisons.
|
||||
|
||||
---
|
||||
|
||||
To concatenate strings together.
|
||||
`You are a teenager` will be printed to the console.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how they evaluate relationships between values.
|
||||
Review the last part of the lecture for the correct answer.
|
||||
|
||||
---
|
||||
|
||||
To perform mathematical calculations.
|
||||
`You are a child` will be printed to the console.
|
||||
|
||||
---
|
||||
|
||||
An error will be printed to the console.
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about how they evaluate relationships between values.
|
||||
Review the last part of the lecture for the correct answer.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
3
|
||||
|
||||
## --text--
|
||||
|
||||
What happens when Python evaluates the expression `x or y`?
|
||||
What will the expression `3 >= 4` evaluate to?
|
||||
|
||||
## --answers--
|
||||
|
||||
It returns True only if both `x` and `y` are `True`
|
||||
`True`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about "short-circuiting" and when Python might not need to check the second value.
|
||||
3 is not greater than or equal to 4.
|
||||
|
||||
---
|
||||
|
||||
It returns `True` if at least one condition is `True` and may skip evaluating `y`
|
||||
|
||||
---
|
||||
|
||||
It always evaluates both `x` and `y` regardless of their values
|
||||
`SyntaxError`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about "short-circuiting" and when Python might not need to check the second value.
|
||||
3 is not greater than or equal to 4.
|
||||
|
||||
---
|
||||
|
||||
It returns `False` if either `x` or `y` is `False`
|
||||
`None`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about "short-circuiting" and when Python might not need to check the second value.
|
||||
3 is not greater than or equal to 4.
|
||||
|
||||
---
|
||||
|
||||
`False`
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
4
|
||||
|
||||
+184
-3
@@ -1,14 +1,159 @@
|
||||
---
|
||||
id: 6839b2ddd01ef657b6bf3b76
|
||||
title: What Are Some Common String Methods?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: what-are-some-common-string-methods
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
Python provides a number of built-in methods that make working with strings a breeze. They include, but are not limited to, the following:
|
||||
|
||||
- `upper()`: Returns a new string with all characters converted to uppercase.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
uppercase_my_str = my_str.upper()
|
||||
print(uppercase_my_str) # HELLO WORLD
|
||||
```
|
||||
|
||||
- `lower()`: Returns a new string with all characters converted to lowercase.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'Hello World'
|
||||
|
||||
lowercase_my_str = my_str.lower()
|
||||
print(lowercase_my_str) # hello world
|
||||
```
|
||||
|
||||
- `strip()`: Returns a new string with the specified leading and trailing characters removed. If no argument is passed it removes leading and trailing whitespace.
|
||||
|
||||
|
||||
```python
|
||||
my_str = ' hello world '
|
||||
|
||||
trimmed_my_str = my_str.strip()
|
||||
print(trimmed_my_str) # "hello world"
|
||||
```
|
||||
|
||||
- `replace(old, new)`: Returns a new string with all occurrences of `old` replaced by `new`.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
replaced_my_str = my_str.replace('hello', 'hi')
|
||||
print(replaced_my_str) # hi world
|
||||
```
|
||||
|
||||
- `split(separator)`: Splits a string on a specified separator into a list of strings. If no separator is specified, it splits on whitespace.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
split_words = my_str.split()
|
||||
print(split_words) # ['hello', 'world']
|
||||
```
|
||||
|
||||
- `join(iterable)`: Joins elements of an iterable into a string with a separator.
|
||||
|
||||
|
||||
```python
|
||||
my_list = ['hello', 'world']
|
||||
|
||||
joined_my_str = ' '.join(my_list)
|
||||
print(joined_my_str) # hello world
|
||||
```
|
||||
|
||||
- `startswith(prefix)`: Returns a boolean indicating if a string starts with the specified prefix.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
starts_with_hello = my_str.startswith('hello')
|
||||
print(starts_with_hello) # True
|
||||
```
|
||||
|
||||
- `endswith(suffix)`: Returns a boolean indicating if a string ends with the specified suffix.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
ends_with_world = my_str.endswith('world')
|
||||
print(ends_with_world) # True
|
||||
```
|
||||
|
||||
- `find(substring)`: Returns the index of the first occurrence of `substring`, or `-1` if it doesn't find one.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
world_index = my_str.find('world')
|
||||
print(world_index) # 6
|
||||
```
|
||||
|
||||
- `count(substring)`: Returns the number of times a substring appears in a string.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
o_count = my_str.count('o')
|
||||
print(o_count) # 2
|
||||
```
|
||||
|
||||
- `capitalize()`: Returns a new string with the first character capitalized and the other characters lowercased.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
capitalized_my_str = my_str.capitalize()
|
||||
print(capitalized_my_str) # Hello world
|
||||
```
|
||||
|
||||
- `isupper()`: Returns `True` if all letters in the string are uppercase and `False` if not.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
is_all_upper = my_str.isupper()
|
||||
print(is_all_upper) # False
|
||||
```
|
||||
|
||||
- `islower()`: Returns `True` if all letters in the string are lowercase and `False` if not.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
is_all_lower = my_str.islower()
|
||||
print(is_all_lower) # True
|
||||
```
|
||||
|
||||
- `title()`: Returns a new string with the first letter of each word capitalized.
|
||||
|
||||
|
||||
```python
|
||||
my_str = 'hello world'
|
||||
|
||||
title_case_my_str = my_str.title()
|
||||
print(title_case_my_str) # Hello World
|
||||
```
|
||||
|
||||
# --questions--
|
||||
|
||||
@@ -50,6 +195,42 @@ These methods return `True` or `False` based on letter case.
|
||||
|
||||
## --text--
|
||||
|
||||
How can you replace all occurrences of one or more parts of a string with another string?
|
||||
|
||||
## --answers--
|
||||
|
||||
Using the `change()` method with two arguments.
|
||||
|
||||
### --feedback--
|
||||
|
||||
The method takes two arguments - what to find and what to replace it with.
|
||||
|
||||
---
|
||||
|
||||
Using the `replace()` method with old and new text.
|
||||
|
||||
---
|
||||
|
||||
Using the `modify()` function with replacement rules.
|
||||
|
||||
### --feedback--
|
||||
|
||||
The method takes two arguments - what to find and what to replace it with.
|
||||
|
||||
---
|
||||
|
||||
Using the `update()` method with a mapping dictionary.
|
||||
|
||||
### --feedback--
|
||||
|
||||
The method takes two arguments - what to find and what to replace it with.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
|
||||
## --text--
|
||||
|
||||
What does the `upper()` method do?
|
||||
|
||||
## --answers--
|
||||
|
||||
+156
-3
@@ -1,14 +1,167 @@
|
||||
---
|
||||
id: 6839b3295323f563efc68f5c
|
||||
title: How Do Augmented Assignments Work?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: how-do-augmented-assignments-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video or read the transcript and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
Augmented assignment combines a binary operation with an assignment in one step. It takes a variable, applies an operation to it with another value, and stores the result back into the same variable.
|
||||
|
||||
If you're familiar with a language like JavaScript, you've probably heard of the addition assignment operator (`+=`) or subtraction assignment (`-=`), and others. Those exist in Python, too. The only difference is that they're referred to as **augmented assignments**.
|
||||
|
||||
The basic syntax of an augmented assignment looks like this:
|
||||
|
||||
```python
|
||||
variable <operator>= value
|
||||
```
|
||||
|
||||
Which is a more efficient way of doing this:
|
||||
|
||||
```python
|
||||
variable = variable <operator> value
|
||||
```
|
||||
|
||||
For example, here's an example of using augmented assignment to add `5` to an existing variable:
|
||||
|
||||
```python
|
||||
my_var = 10
|
||||
my_var += 5
|
||||
|
||||
print(my_var) # 15
|
||||
```
|
||||
|
||||
And here is the same thing, but without augmented assignment:
|
||||
|
||||
```python
|
||||
my_var = 10
|
||||
my_var = my_var + 5
|
||||
|
||||
print(my_var) # 15
|
||||
```
|
||||
|
||||
The advantage of augmented assignment is that it provides a concise and readable way to update a variable value without repeating the variable name. In turn, this reduces redundancy and potential errors that might arise from a typo or something similar.
|
||||
|
||||
Every operator can use an augmented assignment. We've looked at the addition assignment operator (`+=`), so let's look at others.
|
||||
|
||||
- The subtraction assignment operator (`-=`) subtracts the right operand from the left variable and stores the difference in the left variable:
|
||||
|
||||
```python
|
||||
count = 14
|
||||
count -= 3
|
||||
|
||||
print(count) # 11
|
||||
```
|
||||
|
||||
- The multiplication assignment operator (`*=`) multiplies the left variable by the right operand and stores the product back in the left variable:
|
||||
|
||||
|
||||
```python
|
||||
product = 65
|
||||
product *= 7
|
||||
|
||||
print(product) # 455
|
||||
```
|
||||
|
||||
- The division assignment operator (`/=`) divides the left variable by the right and stores the result back in the left variable:
|
||||
|
||||
|
||||
```python
|
||||
price = 100
|
||||
price /= 4
|
||||
|
||||
print(price) # 25.0
|
||||
```
|
||||
|
||||
- The floor division operator (`//=`) floor‑divides the left variable by the right and stores the result back in the left variable:
|
||||
|
||||
|
||||
```python
|
||||
total_pages = 23
|
||||
total_pages //= 5
|
||||
|
||||
print(total_pages) # 4
|
||||
```
|
||||
|
||||
- The modulus assignment operator (`%=`) computes the remainder of the left variable divided by the right and stores it back in the left variable:
|
||||
|
||||
|
||||
```python
|
||||
bits = 35
|
||||
bits %= 2
|
||||
|
||||
print(bits) # 1
|
||||
```
|
||||
|
||||
- The exponentiation assignment operator (`**=`) raises the left variable to the power of the right and stores the result back in the left variable:
|
||||
|
||||
|
||||
```python
|
||||
power = 2
|
||||
power **= 3
|
||||
|
||||
print(power) # 8
|
||||
```
|
||||
|
||||
There are other augmented assignment operators too, like those for bitwise operators. They include `&=`, `^=`, `>>=`, and `<<=`.
|
||||
|
||||
You can use some augmented assignment operators with strings, too. For example, the addition assignment operator makes it easy to concatenate strings:
|
||||
|
||||
```python
|
||||
greet = 'Hello'
|
||||
greet += ' World'
|
||||
|
||||
print(greet) # Hello World
|
||||
```
|
||||
|
||||
And the multiplication assignment operator can be used to repeat a string:
|
||||
|
||||
```python
|
||||
greet = 'Hello'
|
||||
greet *= 3
|
||||
|
||||
print(greet) # HelloHelloHello
|
||||
```
|
||||
|
||||
Other augmented assignments throw a `TypeError` when you use them with strings:
|
||||
|
||||
```python
|
||||
greet = 'Hello'
|
||||
greet -= ' World'
|
||||
|
||||
print(greet) # TypeError: unsupported operand type(s) for -=: 'str' and 'str'
|
||||
|
||||
|
||||
greet = 'Hello'
|
||||
greet /= 'World'
|
||||
|
||||
print(greet) # TypeError: unsupported operand type(s) for /=: 'str' and 'str'
|
||||
```
|
||||
|
||||
If you're wondering if increment and decrement operators (`++` and `--`) work in Python, they don't. That's because Python deliberately avoids C-style increment and decrement shortcuts in order to keep the language clear and explicit.
|
||||
|
||||
Instead of `x++`, you can simply write `x += 1`, which makes it obvious that you're incrementing the value of `x` by `1`.
|
||||
|
||||
Writing `++x` in Python just applies the unary plus twice, and increment anything:
|
||||
|
||||
```python
|
||||
my_var = 5
|
||||
|
||||
print(+my_var) # 5
|
||||
print(++my_var) # 5
|
||||
print(+++my_var) # 5
|
||||
|
||||
my_var += 1
|
||||
|
||||
print(my_var) # 6
|
||||
```
|
||||
|
||||
# --questions--
|
||||
|
||||
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
---
|
||||
id: 68480f431e8568b2056b140b
|
||||
title: What Are Truthy and Falsy Values, and How Do Boolean Operators and Short-Circuiting Work?
|
||||
# change back to 11 when video is updated
|
||||
challengeType: 19
|
||||
# videoId: new-id-goes-here-when-ready
|
||||
dashedName: what-are-truthy-and-falsy-values-and-how-do-boolean-operators-and-short-circuiting-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
# --transcript--
|
||||
|
||||
In the previous lecture, you learned how to use comparison operators and conditional statements to control the flow of your programs.
|
||||
|
||||
While those are very powerful, you will often run into situations where you need to compare multiple values at once. This can lead to nested conditional statements, for example:
|
||||
|
||||
```python
|
||||
is_citizen = True
|
||||
age = 25
|
||||
|
||||
if is_citizen:
|
||||
if age >= 18:
|
||||
print('You are eligible to vote') # You are eligible to vote
|
||||
else:
|
||||
print('You are not eligible to vote')
|
||||
```
|
||||
|
||||
The above example will first check if `is_citizen` is `True`. If so, it will then go to the nested `if` statement and check if `age` is greater than or equal to `18`. Since `age` is greater than or equal to `18`, the message printed to the terminal will be `You are eligible to vote`. If `is_citizen` were `False`, then the message printed to the terminal would have been `You are not eligible to vote`.
|
||||
|
||||
If you are working with more complex conditional statements, then you can use Python’s `and`, `or`, and `not` operators.
|
||||
|
||||
But before we dive into those operators, let’s take a look at what truthy and falsy values are.
|
||||
|
||||
In Python, every value has an inherent boolean value, or a built-in sense of whether it should be treated as `True` or `False` in a logical context. Many values are considered **truthy**, that is, they evaluate to `True` in a logical context. Others are **falsy**, meaning they evaluate to `False`.
|
||||
|
||||
Here are a few falsy values:
|
||||
|
||||
- `None`
|
||||
- `False`
|
||||
- Integer `0`
|
||||
- Float `0.0`
|
||||
- Empty strings `""`
|
||||
|
||||
Other values like non-zero numbers, and non-empty strings are truthy.
|
||||
|
||||
If you want to check whether a value is truthy or falsy, you can use the built-in `bool()` function. It explicitly converts a value to its boolean equivalent and returns `True` for truthy values and `False` for falsy values. Here are a few examples:
|
||||
|
||||
```py
|
||||
print(bool(False)) # False
|
||||
print(bool(0)) # False
|
||||
print(bool('')) # False
|
||||
|
||||
print(bool(True)) # True
|
||||
print(bool(1)) # True
|
||||
print(bool('Hello')) # True
|
||||
```
|
||||
|
||||
Now that you understand truthy and falsy values, we can take a look at Boolean operators, which are also known as logical operators or Boolean operations. These are special operators that allow you to combine multiple expressions to create more complex decision-making logic in your code.
|
||||
|
||||
There are three Boolean operators in Python: `and`, `or`, and `not`.
|
||||
|
||||
Let’s first take a look at the `and` operator.
|
||||
|
||||
The `and` operator takes two operands and returns the first operand if it is falsy, otherwise, it returns the second operand. Both operands must be truthy for an expression to result in a truthy value.
|
||||
|
||||
Here is an example:
|
||||
|
||||
```python
|
||||
is_citizen = True
|
||||
age = 25
|
||||
|
||||
print(is_citizen and age) # 25
|
||||
```
|
||||
|
||||
In the above example, the number 25 is printed to the terminal because the `and` operator will evaluate the second operand if the first operand is `True`. The `and` operator is known as a short-circuit operator. Short-circuiting means Python checks values from left to right and stops as soon as it determines the final result.
|
||||
|
||||
You'll often use `and` within `if` statements to check if multiple conditions are met. Here’s how you can refactor the earlier example to uses the `and` operator instead of nested `if` statements:
|
||||
|
||||
```python
|
||||
is_citizen = True
|
||||
age = 25
|
||||
|
||||
if is_citizen and age >= 18:
|
||||
print('You are eligible to vote') # You are eligible to vote
|
||||
else:
|
||||
print('You are not eligible to vote')
|
||||
```
|
||||
|
||||
In the example above, `is_citizen` is `True`, and `age >= 18` evaluates to `True`. Since both operands of the `and` operator are truthy, the condition `is_citizen and age >= 18` evaluates to `True`, and the `print` call in the `if` block is executed.
|
||||
|
||||
Now let's take a look at the `or` operator. This operator returns the first operand if it is truthy, otherwise, it returns the second operand. An `or` expression results in a truthy value if at least one operand is truthy. The `or` operator is also known as a short-circuit operator. Here is an example:
|
||||
|
||||
```python
|
||||
age = 19
|
||||
is_employed = False
|
||||
|
||||
print(age or is_employed) # 19
|
||||
```
|
||||
|
||||
The following code will print the number 19 because the first operand `age` is `True`.
|
||||
|
||||
If you need to check if one or more expressions is `True`, then you can use the `or` operator in a conditional like this:
|
||||
|
||||
```python
|
||||
age = 19
|
||||
is_student = True
|
||||
|
||||
if age < 18 or is_student:
|
||||
print('You are eligible for a student discount') # You are eligible for a student discount
|
||||
else:
|
||||
print('You are not eligible for a student discount')
|
||||
```
|
||||
|
||||
In this case, `age < 18` is `False`, but `is_student` is `True`. Since at least one condition is true, the entire `or` expression evaluates to `True`, and the discount message in the `if` block is printed.
|
||||
|
||||
The last operator we will look at is the `not` operator which takes a single operand and inverts its boolean value. It converts truthy values to `False` and falsy values to `True`. Unlike the previous operators we looked at, `not` always returns `True` or `False`.
|
||||
|
||||
Here are a few examples:
|
||||
|
||||
```python
|
||||
print(not '') # True, because empty string is falsy
|
||||
print(not 'Hello') # False, because non-empty string is truthy
|
||||
print(not 0) # True, because 0 is falsy
|
||||
print(not 1) # False, because 1 is truthy
|
||||
print(not False) # True, because False is falsy
|
||||
print(not True) # False, because True is truthy
|
||||
```
|
||||
|
||||
It is common to use the `not` operator in conditionals to check if something is not `True` or `False`, like this:
|
||||
|
||||
```python
|
||||
is_admin = False
|
||||
|
||||
if not is_admin:
|
||||
print('Access denied for non-administrators.') # Access denied for non-administrators.
|
||||
else:
|
||||
print('Welcome, Administrator!')
|
||||
```
|
||||
|
||||
Since `is_admin` is `False`, then `not is_admin` is saying not `False` which is `True`. So the message `Access denied for non-administrators.` will be printed.
|
||||
|
||||
Now that you understand truthy and falsy values, the `and`, `or`, and `not` operators, and short-circuiting work, you can write more flexible and readable conditional logic.
|
||||
|
||||
# --questions--
|
||||
|
||||
## --text--
|
||||
|
||||
What will the following code output?
|
||||
|
||||
```python
|
||||
age = 20
|
||||
has_ticket = True
|
||||
|
||||
if age >= 18 and has_ticket:
|
||||
print("You can watch the movie.")
|
||||
else:
|
||||
print("You can't watch the movie.")
|
||||
```
|
||||
|
||||
## --answers--
|
||||
|
||||
`You can watch the movie.`
|
||||
|
||||
---
|
||||
|
||||
`SyntaxError`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Remember what happens when both conditions are `True`.
|
||||
|
||||
---
|
||||
|
||||
`TypeError`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Remember what happens when both conditions are `True`.
|
||||
|
||||
---
|
||||
|
||||
`You can't watch the movie.`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Remember what happens when both conditions are `True`.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
1
|
||||
|
||||
## --text--
|
||||
|
||||
Which of the following is NOT considered a falsy value in Python?
|
||||
|
||||
## --answers--
|
||||
|
||||
`""`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Remember that non-empty strings are considered truthy.
|
||||
|
||||
---
|
||||
|
||||
`0.0`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Remember that non-empty strings are considered truthy.
|
||||
|
||||
---
|
||||
|
||||
`"False"`
|
||||
|
||||
---
|
||||
|
||||
`0`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Remember that non-empty strings are considered truthy.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
3
|
||||
|
||||
## --text--
|
||||
|
||||
What happens when Python evaluates the expression `x or y`?
|
||||
|
||||
## --answers--
|
||||
|
||||
It returns `x` only if both `x` and `y` evaluate to `True`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about "short-circuiting" and when Python might not need to check the second value.
|
||||
|
||||
---
|
||||
|
||||
It returns `x` if it evaluates to `True`, and skips evaluating `y`
|
||||
|
||||
---
|
||||
|
||||
It always evaluates both `x` and `y` regardless of their values
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about "short-circuiting" and when Python might not need to check the second value.
|
||||
|
||||
---
|
||||
|
||||
It returns `False` if either `x` or `y` is `False`
|
||||
|
||||
### --feedback--
|
||||
|
||||
Think about "short-circuiting" and when Python might not need to check the second value.
|
||||
|
||||
## --video-solution--
|
||||
|
||||
2
|
||||
Reference in New Issue
Block a user