fix(curriculum): restructure python basics module (#64700)

Co-authored-by: majestic-owl448 <26656284+majestic-owl448@users.noreply.github.com>
This commit is contained in:
Dario
2025-12-19 18:23:26 +01:00
committed by GitHub
parent b8e09e3b9a
commit e2fe476686
28 changed files with 817 additions and 472 deletions
+29 -1
View File
@@ -6715,7 +6715,35 @@
"lecture-introduction-to-python": {
"title": "Introduction to Python",
"intro": [
"In these lessons, you will learn the fundamentals of Python. You'll learn about variables, data types, operators, control flow, functions, and more."
"In these lessons, you will learn what Python is, how to set up your development environment."
]
},
"lecture-understanding-variables-and-data-types": {
"title": "Understanding Variables and Data Types",
"intro": [
"In these lessons, you will learn about variables and data types in Python."
]
},
"lecture-introduction-to-python-strings": {
"title": "Introduction to Strings",
"intro": ["In these lessons, you will learn about strings in Python."]
},
"lecture-numbers-and-mathematical-operations": {
"title": "Numbers and Mathematical Operations",
"intro": [
"In these lessons, you will learn about numbers and mathematical operations in Python."
]
},
"lecture-booleans-and-conditionals": {
"title": "Booleans and Conditionals",
"intro": [
"In these lessons, you will learn about booleans and conditionals in Python."
]
},
"lecture-understanding-functions-and-scope": {
"title": "Understanding Functions and Scope",
"intro": [
"In these lessons, you will learn about functions and scope in Python."
]
},
"workshop-caesar-cipher": {
@@ -0,0 +1,9 @@
---
title: Introduction to the Booleans and Conditionals
block: lecture-booleans-and-conditionals
superBlock: python-v9
---
## Introduction to the Booleans and Conditionals
In these lessons, you will learn about booleans and conditionals in Python.
@@ -0,0 +1,9 @@
---
title: Introduction to the Introduction to Strings
block: lecture-introduction-to-python-strings
superBlock: python-v9
---
## Introduction to the Introduction to Strings
In these lessons, you will learn about strings in Python.
@@ -1,9 +1,9 @@
---
title: Introduction to Introduction to Python
block: lecture-introduction-to-python
superBlock: full-stack-developer
superBlock: python-v9
---
## Introduction to Introduction to Python
Learn about Introduction to Python in these lessons.
In these lessons, you will learn what Python is, how to set up your development environment.
@@ -0,0 +1,9 @@
---
title: Introduction to the Numbers and Mathematical Operations
block: lecture-numbers-and-mathematical-operations
superBlock: python-v9
---
## Introduction to the Numbers and Mathematical Operations
In these lessons, you will learn about numbers and mathematical operations in Python.
@@ -0,0 +1,9 @@
---
title: Introduction to the Understanding Functions and Scope
block: lecture-understanding-functions-and-scope
superBlock: python-v9
---
## Introduction to the Understanding Functions and Scope
In these lessons, you will learn about functions and scope in Python.
@@ -0,0 +1,9 @@
---
title: Introduction to the Understanding Variables and Data Types
block: lecture-understanding-variables-and-data-types
superBlock: python-v9
---
## Introduction to the Understanding Variables and Data Types
In these lessons, you will learn about variables and data types in Python.
@@ -42,17 +42,18 @@ In Python, the most basic conditional is the `if` statement. Here's the basic sy
```python
if condition:
# Code to execute if condition is True
pass # Code to execute if condition is True
```
* `if` statements start with the `if` keyword.
* `condition` is an expression that evaluates to `True` or `False`, followed by a colon (`:`).
* The indentation specifies the block of code within the body of the `if` statement.
* The body of the `if` statement constitutes a <dfn>code block</dfn>, which is a group of statements that belong together. In Python, the level of indentation is what defines a code block.
In the example above, the body of the `if` statement contains a `pass` statement. When a `pass` statement is executed, nothing happens. This is a special keyword that can be used as a placeholder for future code and it is useful when empty code blocks are not allowed.
And here's an example:
The code within the body of the `if` statement runs only when the condition evaluates to `True`. For example:
```python
age = 18
@@ -61,7 +62,22 @@ 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:
Notice the indentation before `print('You are an adult')`. 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.
The following code would raise an `IndentationError`, which is Python's way to signal that indentation is required at a certain point of the code:
```py
age = 18
if age >= 18:
print('You are an adult') # IndentationError: expected an indented block after 'if' statement on line 3
```
Though you can use any number spaces (as long as you are consistent) to determine each level of indentation, the Python style guide recommends using four spaces.
Blocks are also found in loops and functions, which you'll learn about in future lessons.
Going back to our example, if `age` is anything less than `18`, nothing is printed in the terminal:
```python
age = 12
@@ -74,9 +90,9 @@ But what if you also want to print something if `age` is less than `18`? That's
```python
if condition:
# Code to execute if condition is True
pass # Code to execute if condition is True
else:
# Code to execute if condition is False
pass # Code to execute if condition is False
```
For example:
@@ -96,11 +112,11 @@ Here's the syntax:
```python
if condition:
# Code to execute if condition is True
pass # Code to execute if condition is True
elif condition2:
# Code to execute if condition2 is True
pass # Code to execute if condition2 is True
else:
# Code to execute if all conditions are False
pass # Code to execute if all conditions are False
```
For example:
@@ -0,0 +1,214 @@
---
id: 69413cbce2d6c74f61d3f7e5
title: What Are Strings and What Is String Immutability?
challengeType: 19
dashedName: what-are-strings-and-what-is-string-immutability
---
# --description--
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!\""
```
Sometimes, you may need to check if a string contains one or more characters. For 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
```
Now, 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
```
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
```
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.
Strings are immutable data types in Python. This means that you can reassign a different string to a variable:
```python
greeting = 'hi'
greeting = 'hello'
print(greeting) # hello
```
But direct modification of a string isn't allowed:
```python
greeting = 'hi'
greeting[0] = 'H' # TypeError: 'str' object does not support item assignment
```
Examples of other immutable data types in Python are integer, float, boolean, tuple, and range. You'll get to know each of these types in upcoming lessons.
# --questions--
## --text--
How do you get the length of a string `s`?
## --answers--
`len(s)`
---
`s.length`
### --feedback--
Go back to the part of the lesson about getting the length of a string.
---
A string does not have a length.
### --feedback--
Go back to the part of the lesson about getting the length of a string.
---
`s.len()`
### --feedback--
Go back to the part of the lesson about getting the length of a string.
## --video-solution--
1
## --text--
How do you define a multiline string in Python?
## --answers--
Using parentheses `()` around the string.
### --feedback--
Python allows special quotes for multiline strings.
---
Using triple double quotes `"""` or triple single quotes `'''`.
---
Using a backslash `\` at the end of each line.
### --feedback--
Python allows special quotes for multiline strings.
---
Using square brackets `[]` to enclose the string.
### --feedback--
Python allows special quotes for multiline strings.
## --video-solution--
2
---
## --text--
What does it mean that a string is immutable?
## --answers--
A variable cannot be reassigned to a different string.
### --feedback--
Immutable refers to something that doesn't change.
---
Variable reassignment directly modifies the original string.
### --feedback--
Immutable refers to something that doesn't change.
---
A string cannot be directly modified by changing its individual characters.
---
String characters can be directly modified only under specific conditions.
### --feedback--
Immutable refers to something that doesn't change.
## --video-solution--
3
@@ -0,0 +1,181 @@
---
id: 69414623940154f209922619
title: What Are String Concatenation and String Interpolation?
challengeType: 19
dashedName: what-are-string-concatenation-and-string-interpolation
---
# --description--
When working with strings, combining different pieces of text together is a common operation you'll often find yourself dealing with.
In Python, you can 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, which returns the string representation of the given object without modifying the original object:
```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
```
The process of inserting variables and expressions into a string is called **string interpolation**. Python has a category of string called **f-strings** (short for formatted string literals), which allows you to handle interpolation 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
```
Note how you don't need to convert non-string types with the `str()` function. In the example above, the value of the `age`, `num1`, and `num2` variables is converted under the hood into a string during the interpolation process.
# --questions--
## --text--
How can you concatenate strings in Python?
## --answers--
By using the `+` operator.
---
By using the `*` operator for joining strings.
### --feedback--
There's a simple operator and a special string format for this.
---
By using the `&` operator to merge strings.
### --feedback--
There's a simple operator and a special string format for this.
---
By assigning multiple strings to a list and printing them together.
### --feedback--
There's a simple operator and a special string format for this.
## --video-solution--
1
## --text--
What does the `str()` function do?
## --answers--
It concatenates two strings together.
### --feedback--
Go back to the part of the lesson that talks about the `str()` function.
---
It returns a string version of the given object.
---
It extracts numeric characters from an alphanumeric sequence.
### --feedback--
Go back to the part of the lesson that talks about the `str()` function.
---
It replaces the provided characters within a string.
### --feedback--
Go back to the part of the lesson that talks about the `str()` function.
## --video-solution--
2
---
## --text--
What is string interpolation?
## --answers--
The process of parsing a string to extract specific portions.
### --feedback--
String interpolation allows you to substitute placeholders with specific values.
---
The process of splitting a string into substrings.
### --feedback--
String interpolation allows you to substitute placeholders with specific values.
---
The process of inserting variables and expressions into a string.
---
The process of joining two or more strings together.
### --feedback--
String interpolation allows you to substitute placeholders with specific values.
## --video-solution--
3
@@ -0,0 +1,197 @@
---
id: 694147fe940154f20992261b
title: What Is String Slicing and How Does It Work?
challengeType: 19
dashedName: what-is-string-slicing-and-how-does-it-work
---
# --description--
In a previous lesson, you learned how each character in a string can be indentified by its index (starting from zero), and accessed using the bracket notation:
```python
my_str = "Hello world"
print(my_str[0]) # H
print(my_str[6]) # w
print(my_str[-1]) # d
```
**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.
Note that slicing a string does not modify the original string:
```py
my_str = 'Hello world'
print(my_str[8:]) # rld
print(my_str) # Hello world
```
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
```
# --questions--
## --text--
How do you extract a specific portion of a string in Python?
## --answers--
Using parentheses with start and end positions.
### --feedback--
This operation relies on character positions and uses bracket notation.
---
Using curly braces with start and stop positions.
### --feedback--
This operation relies on character positions and uses bracket notation.
---
Using square brackets with start and stop positions.
---
Using angle brackets with start and stop positions.
### --feedback--
This operation relies on character positions and uses bracket notation.
## --video-solution--
3
## --text--
What is the outcome of `'Hello'[2:]`?
## --answers--
`llo`
---
`lo`
### --feedback--
Go back to the part of the lesson that talks about omitting start and stop indices.
---
`el`
### --feedback--
Go back to the part of the lesson that talks about omitting start and stop indices.
---
`l`
### --feedback--
Go back to the part of the lesson that talks about omitting start and stop indices.
## --video-solution--
1
## --text--
What is the purpose of the optional `step` parameter in string slicing?
## --answers--
It specifies if the sliced string should be changed in place or not.
### --feedback--
Go back to the part of the lesson that talks about the `step` parameter.
---
It specifies the increment between each character to extract.
---
It ensures that all characters are extracted.
### --feedback--
Go back to the part of the lesson that talks about the `step` parameter.
---
It specifies a maximum number of repeated characters to extract.
### --feedback--
Go back to the part of the lesson that talks about the `step` parameter.
## --video-solution--
2
@@ -1,310 +0,0 @@
---
id: 67fe859c1ab68734d7c666cb
title: How Do You Work With Strings?
challengeType: 19
dashedName: how-do-you-work-with-strings
---
# --description--
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--
How can you concatenate strings in Python?
## --answers--
By using the `+` operator or `f strings`.
---
By using the `*` operator for joining strings.
### --feedback--
There's a simple operator and a special string format for this.
---
By using the `&` operator to merge strings.
### --feedback--
There's a simple operator and a special string format for this.
---
By assigning multiple strings to a list and printing them together.
### --feedback--
There's a simple operator and a special string format for this.
## --video-solution--
1
## --text--
How do you define a multiline string in Python?
## --answers--
Using parentheses `()` around the string.
### --feedback--
Python allows special quotes for multiline strings.
---
Using triple double quotes `"""` or triple single quotes `'''`.
---
Using a backslash `\` at the end of each line.
### --feedback--
Python allows special quotes for multiline strings.
---
Using square brackets `[]` to enclose the string.
### --feedback--
Python allows special quotes for multiline strings.
## --video-solution--
2
---
## --text--
How do you extract a specific portion of a string in Python?
## --answers--
Using parentheses with start and end positions.
### --feedback--
This operation relies on character positions and uses bracket notation.
---
Using curly braces with start and stop positions.
### --feedback--
This operation relies on character positions and uses bracket notation.
---
Using square brackets with start and stop positions.
---
Using angle brackets with start and stop positions.
### --feedback--
This operation relies on character positions and uses bracket notation.
## --video-solution--
3
@@ -178,7 +178,9 @@ print('Integer Exponentiation:', exp_ints) # Integer Exponentiation: 95116601380
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 also provides built-in functions for converting either numeric data or strings into integers or floats.
The `float()` function returns a floating-point number constructed from the given number:
```python
my_int_1 = 56
@@ -188,7 +190,7 @@ 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:
The `int()` function returns an integer constructed from the given number:
```python
my_float = 12.92563
@@ -237,26 +239,6 @@ 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.
@@ -40,13 +40,7 @@ To run the function, you need to call it with its name followed by a pair of par
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 lessons.
Notice the indentation before `print('Hello World')`. As you may recall from previous lessons, Python relies on indentation to determine which groups of statements belong together. These groups of statements are called code blocks.
Here's another simple function that prints the sum of two numbers to the terminal:
@@ -55,13 +55,6 @@ my_float_var = 4.50
print('Float:', my_float_var) # Float: 4.5
```
- 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
@@ -101,7 +94,7 @@ print('Tuple:', my_tuple_var) # Tuple: (7, 5, 8)
```python
my_range_var = range(5)
print(my_range_var) # range(0, 5)
print('Range:', my_range_var) # Range: range(0, 5)
```
- List: An ordered collection of elements that supports different data types.
@@ -118,31 +111,6 @@ 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
@@ -157,42 +125,37 @@ And here's are all the data types covered in this lesson, along with their types
```python
my_integer_var = 10
print('Integer:', my_integer_var, '| Type:', type(my_integer_var)) # Integer: 10 | Type: <class 'int'>
print(type(my_integer_var)) # <class 'int'>
my_float_var = 4.50
print('Float:', my_float_var, '| Type:', type(my_float_var)) # Float: 4.5 | Type: <class 'float'>
my_complex_var = 3 + 4j
print('Complex:', my_complex_var, '| Type:', type(my_complex_var)) # Complex: (3+4j) | Type: <class 'complex'>
print(type(my_float_var)) # <class 'float'>
my_string_var = 'hello'
print('String:', my_string_var, '| Type:', type(my_string_var)) # String: hello | Type: <class 'str'>
print(type(my_string_var)) # <class 'str'>
my_boolean_var = True
print('Boolean:', my_boolean_var, '| Type:', type(my_boolean_var)) # Boolean: True | Type: <class 'bool'>
print(type(my_boolean_var)) # <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'>
print(type(my_set_var)) # <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'>
print(type(my_dictionary_var)) # <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'>
print(type(my_tuple_var)) # <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'>
print(type(my_range_var)) # <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'>
print(type(my_list)) # <class 'list'>
my_none_var = None
print('None:', my_none_var, '| Type:', type(my_none_var)) # None: None | Type: <class 'NoneType'>
print(type(my_none_var)) # <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:
The built-in `isinstance()` function lets you check if a variable matches a specific data type. It 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
@@ -201,34 +164,6 @@ 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--
@@ -0,0 +1,18 @@
{
"name": "Booleans and Conditionals",
"isUpcomingChange": false,
"dashedName": "lecture-booleans-and-conditionals",
"helpCategory": "Python",
"blockLayout": "challenge-list",
"challengeOrder": [
{
"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?"
}
],
"blockLabel": "lecture"
}
@@ -0,0 +1,26 @@
{
"name": "Introduction to Strings",
"isUpcomingChange": false,
"dashedName": "lecture-introduction-to-python-strings",
"helpCategory": "Python",
"blockLayout": "challenge-list",
"challengeOrder": [
{
"id": "69413cbce2d6c74f61d3f7e5",
"title": "What Are Strings and What Is String Immutability?"
},
{
"id": "69414623940154f209922619",
"title": "What Are String Concatenation and String Interpolation?"
},
{
"id": "694147fe940154f20992261b",
"title": "What Is String Slicing and How Does It Work?"
},
{
"id": "6839b2ddd01ef657b6bf3b76",
"title": "What Are Some Common String Methods?"
}
],
"blockLabel": "lecture"
}
@@ -12,50 +12,6 @@
{
"id": "67fe8567f141d632afaeb71b",
"title": "How Do You Install, Configure and Use Python in Your Local Environment?"
},
{
"id": "67fe8597975ea634042cad8f",
"title": "How Do You Declare Variables and What Are Naming Conventions to Name Variables?"
},
{
"id": "67fe8599c83979345ff9a91a",
"title": "How Does the Print Function Work?"
},
{
"id": "67fe859a00971c34a23abd43",
"title": "What Are Common Data Types in Python and How Do You Get the Type of a Variable?"
},
{
"id": "67fe859c1ab68734d7c666cb",
"title": "How Do You Work With Strings?"
},
{
"id": "6839b2ddd01ef657b6bf3b76",
"title": "What Are Some Common String Methods?"
},
{
"id": "67fe859e9d3b3635197781c8",
"title": "How Do You Work With Integers and Floating Point Numbers?"
},
{
"id": "6839b3295323f563efc68f5c",
"title": "How Do Augmented Assignments Work?"
},
{
"id": "67fe859f55cd33356e322fd3",
"title": "How Do Functions Work in Python?"
},
{
"id": "67fe85a1b634a335b18ae09a",
"title": "What Is Scope in Python and How Does It Work?"
},
{
"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"
@@ -0,0 +1,18 @@
{
"name": "Numbers and Mathematical Operations",
"isUpcomingChange": false,
"dashedName": "lecture-numbers-and-mathematical-operations",
"helpCategory": "Python",
"blockLayout": "challenge-list",
"challengeOrder": [
{
"id": "67fe859e9d3b3635197781c8",
"title": "How Do You Work With Integers and Floating Point Numbers?"
},
{
"id": "6839b3295323f563efc68f5c",
"title": "How Do Augmented Assignments Work?"
}
],
"blockLabel": "lecture"
}
@@ -0,0 +1,18 @@
{
"name": "Understanding Functions and Scope",
"isUpcomingChange": false,
"dashedName": "lecture-understanding-functions-and-scope",
"helpCategory": "Python",
"blockLayout": "challenge-list",
"challengeOrder": [
{
"id": "67fe859f55cd33356e322fd3",
"title": "How Do Functions Work in Python?"
},
{
"id": "67fe85a1b634a335b18ae09a",
"title": "What Is Scope in Python and How Does It Work?"
}
],
"blockLabel": "lecture"
}
@@ -0,0 +1,22 @@
{
"name": "Understanding Variables and Data Types",
"isUpcomingChange": false,
"dashedName": "lecture-understanding-variables-and-data-types",
"helpCategory": "Python",
"blockLayout": "challenge-list",
"challengeOrder": [
{
"id": "67fe8597975ea634042cad8f",
"title": "How Do You Declare Variables and What Are Naming Conventions to Name Variables?"
},
{
"id": "67fe8599c83979345ff9a91a",
"title": "How Does the Print Function Work?"
},
{
"id": "67fe859a00971c34a23abd43",
"title": "What Are Common Data Types in Python and How Do You Get the Type of a Variable?"
}
],
"blockLabel": "lecture"
}
@@ -7,6 +7,11 @@
"dashedName": "python-basics",
"blocks": [
"lecture-introduction-to-python",
"lecture-understanding-variables-and-data-types",
"lecture-introduction-to-python-strings",
"lecture-numbers-and-mathematical-operations",
"lecture-booleans-and-conditionals",
"lecture-understanding-functions-and-scope",
"workshop-caesar-cipher",
"lab-rpg-character",
"review-python-basics",