|
2 | 2 |
|
3 | 3 | Hello reader, |
4 | 4 |
|
5 | | -This document will jumpstart your understanding of Python. It will cover all the foundational aspects of the programming language, and provide examples of how to use each of them in practice. Whenever you get stuck on the exercises in this book, feel free to come back to this section as well - after all, even the most experienced programmers have to review the basics sometimes! |
| 5 | +This document will jumpstart your understanding of Python. We will cover all the foundational aspects of the programming language, and provide you with examples of how to use each of them in practice. Whenever you get stuck on the exercises in this book, feel free to come back to this section as well - after all, even the most experienced programmers have to review the basics sometimes! |
6 | 6 |
|
7 | 7 | ## Table of Contents |
8 | | -**[TODO]** put in links |
9 | 8 |
|
10 | 9 | 1. [Data Types](#data-types) |
11 | | -2. [Control Flow]() |
12 | | -3. [Functions]() |
13 | | -4. [Container Types]() |
14 | | -5. [Credits](#credits) |
| 10 | +2. [Variables](#variables) |
| 11 | +3. [Control Flow](#control-flow) |
| 12 | +4. [Functions](#functions) |
| 13 | +5. [Container Types](#container-types) |
| 14 | +6. [Credits](#credits) |
15 | 15 |
|
16 | 16 | ## Data Types |
| 17 | +Programming languages give us an easy way to manipulate data in the computer - but first, the computer has to understand what kind of data we're dealing with! |
17 | 18 |
|
18 | | -### Math Operators |
| 19 | +Here are some examples of the kinds of data you can work with in the Python programming language: |
19 | 20 |
|
20 | | -From **Highest** to **Lowest** precedence: |
| 21 | +#### Table 1: Data Types in Python |
21 | 22 |
|
22 | | -| Operators | Operation | Example | |
| 23 | +| Data Type | Examples | |
| 24 | +| ---------------------- | ----------------------------------------- | |
| 25 | +| Integers | `-3, -2, -1, 0, 1, 2, 3` | |
| 26 | +| Floating-point numbers | `-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25` | |
| 27 | +| Strings | `'a', 'Hello World!', "C-3PO", "bbb"` | |
| 28 | +| Boolean | `True, False` |
| 29 | + |
| 30 | +Integers and floating-point numbers are also called *numeric types*. We shall cover these more in depth now. |
| 31 | + |
| 32 | +### Numeric Types |
| 33 | +Numbers are everywhere! In Python, we have 3 kinds of data types to represent numerical data: |
| 34 | + |
| 35 | +- `int` - whole numbers |
| 36 | +- `float` - floating-point (aka fractional) numbers |
| 37 | + |
| 38 | +Between the `int` and `float` types, Python 3 lets you store any kind of real number in a variable. |
| 39 | + |
| 40 | +**Note**: there is also a `complex` data type in Python - you may read about it in the [documentation](https://docs.python.org/3/library/functions.html?#complex). |
| 41 | + |
| 42 | +The numeric types are useful for when you are doing mathematical operations - which we will discuss next! |
| 43 | + |
| 44 | +#### Math Operations |
| 45 | + |
| 46 | +Python supports a lot of these! Table 2 describes which operator you can use for each of them, along with examples. |
| 47 | +##### Table 2: Mathematical Operators (for Each Operation) |
| 48 | + |
| 49 | +| Operator | Operation | Example | |
23 | 50 | | --------- | ---------------- | --------------- | |
24 | | -| ** | Exponent | `2 ** 3 = 8` | |
25 | | -| % | Modulus/Remainder | `22 % 8 = 6` | |
26 | | -| // | Integer division | `22 // 8 = 2` | |
27 | | -| / | Division | `22 / 8 = 2.75` | |
28 | | -| * | Multiplication | `3 * 3 = 9` | |
29 | | -| - | Subtraction | `5 - 2 = 3` | |
30 | | -| + | Addition | `2 + 2 = 4` | |
| 51 | +| ** | Exponent | `3 ** 3 = 27` | |
| 52 | +| % | Modulus/Remainder Division - *returns only the remainder* | `30 % 8 = 6` | |
| 53 | +| // | Integer division - *truncates any floating-point values in the quotient* | `30 // 8 = 3` | |
| 54 | +| / | Division - *always returns a `float`* | `30 / 8 = 3.75` | |
| 55 | +| * | Multiplication | `2 * 3 = 6` | |
| 56 | +| - | Subtraction | `7 - 2 = 5` | |
| 57 | +| + | Addition | `9 + 2 = 11` | |
31 | 58 |
|
32 | | -Examples of expressions in the interactive shell: |
| 59 | +**Note**: all the operators above will return: |
| 60 | +- a `float`, if the two operands are 1) both floating-point OR 2) they have different types |
| 61 | +- an `int`, if 1) both operands are integers AND 2) it is not the division (`/`) operator |
33 | 62 |
|
34 | | -```python |
35 | | -2 + 3 * 6 |
| 63 | +#### Order of Operations |
| 64 | +Python prioritzes some operations over others. This means that it follows a *precedence order* that decides which operation to compute first, when there are several of them together in a given expression. |
| 65 | + |
| 66 | +The operators in Table 2 are listed from **highest** to **lowest** precedence, for your reference. |
| 67 | + |
| 68 | +Here are some examples of how the order of operations can impact the result computed by Python code - feel free to run these in a Python shell to check the results (given in the inline comments). |
| 69 | + |
| 70 | +```python |
| 71 | +5 + 3 * 6 # result: 23 |
36 | 72 | ``` |
37 | 73 |
|
38 | 74 | ```python |
39 | | -(2 + 3) * 6 |
| 75 | +(5 + 3) * 6 # result: 48 |
40 | 76 | ``` |
41 | 77 |
|
42 | 78 | ```python |
43 | | -2 ** 8 |
| 79 | +2 ** 8 # result: 256 |
44 | 80 | ``` |
45 | 81 |
|
46 | 82 | ```python |
47 | | -23 // 7 |
| 83 | +23 // 7 # result: 3 |
48 | 84 | ``` |
49 | 85 |
|
50 | 86 | ```python |
51 | | -23 % 7 |
| 87 | +23 % 7 # result: 2 |
52 | 88 | ``` |
53 | 89 |
|
54 | 90 | ```python |
55 | | -(5 - 1) * ((7 + 1) / (3 - 1)) |
| 91 | + ((7 + 5) / (4 - 1)) * (5 + 1) # result: 24.0 |
56 | 92 | ``` |
57 | 93 |
|
58 | | -### Data Types |
| 94 | +The next data type we will cover are strings, which are also known as a *text sequence type*. |
59 | 95 |
|
60 | | -| Data Type | Examples | |
61 | | -| ---------------------- | ----------------------------------------- | |
62 | | -| Integers | `-2, -1, 0, 1, 2, 3, 4, 5` | |
63 | | -| Floating-point numbers | `-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25` | |
64 | | -| Strings | `'a', 'aa', 'aaa', 'Hello!', '11 cats'` | |
| 96 | +### Strings |
| 97 | +Strings in Python are used to represent any sequence of characters. Basically, anything that can be typed on a computer between a pair of quotes is a string! |
| 98 | +#### Common String Operations |
65 | 99 |
|
66 | | -### String Concatenation and Replication |
| 100 | +1. **String concatenation**: |
67 | 101 |
|
68 | | -String concatenation: |
| 102 | + *Concatenation* is when one string is added onto the end of another string. A quick and easy way to do this is by using the addition (`+`) operator, just like we did for numbers! |
69 | 103 |
|
70 | | -```python |
71 | | -'Alice' 'Bob' |
72 | | -``` |
| 104 | + For example, let's say we wanted a string that said `'Alice met Allison on Tuesday'` - then the code could look like the following: |
73 | 105 |
|
74 | | -Note: Avoid `+` operator for string concatenation. Prefer string formatting. |
| 106 | + ```python |
| 107 | + 'Alice met ' + 'Allison on Tuesday' |
| 108 | + ``` |
| 109 | + **Note**: although using addition works, it is far from perfect. In practice we prefer 1) *string formatting*, which will be discussed later in this book, or 2) the `str.join()` function, which you may read about in the [Python documentation](https://docs.python.org/3/library/stdtypes.html?#str.join). |
75 | 110 |
|
76 | | -String Replication: |
| 111 | +2. **String Replication**: |
77 | 112 |
|
78 | | -```python |
79 | | -'Alice' * 5 |
80 | | -``` |
| 113 | + *Replication* is when we repeat a given string over and over again in a new, longer `str` object. |
| 114 | + |
| 115 | + Incidently, Python makes this easier for us through the `*` operator. Now, can you guess what the output of the following code will be? |
81 | 116 |
|
82 | | -### Variables |
| 117 | + ```python |
| 118 | + 'Alice' * 5 |
| 119 | + ``` |
83 | 120 |
|
84 | | -You can name a variable anything as long as it obeys the following rules: |
| 121 | +3. **Displaying Messages using `print()`** |
| 122 | + You will most often see strings where a program needs to tell the user some kind of message - this is exactly what the `print()` function will do: |
85 | 123 |
|
86 | | -1. It can be only one word. |
87 | | -2. It can use only letters, numbers, and the underscore (`_`) character. |
88 | | -3. It can’t begin with a number. |
89 | | -4. Variable name starting with an underscore (`_`) are considered as "unuseful`. |
| 124 | + ```python |
| 125 | + print('Hello world!') |
| 126 | + ``` |
90 | 127 |
|
91 | | -Example: |
| 128 | +4. **Gathering User Responses using `input()`** |
92 | 129 |
|
93 | | -```python |
94 | | -spam = 'Hello' |
95 | | -``` |
| 130 | + Another common task is for a computer program to ask the user for their information - this can be done in Python via the `input()` function. |
96 | 131 |
|
97 | | -```python |
98 | | -_spam = 'Hello' |
99 | | -``` |
| 132 | + In the example below the user will first be prompted to enter their name, because that is what has been passed to the `input()` function. |
100 | 133 |
|
101 | | -`_spam` should not be used again in the code. |
| 134 | + ```python |
| 135 | + name = input('What is your name?') # ask for their name |
| 136 | + ``` |
| 137 | + The user's response is then stored in the variable called `name`. |
102 | 138 |
|
103 | | -### Comments |
| 139 | +5. **Measuring Length using `len()`** |
104 | 140 |
|
105 | | -Inline comment: |
| 141 | + We can also calculate valuates thenumber of characters in a string: |
106 | 142 |
|
107 | | -```python |
108 | | -# This is a comment |
109 | | -``` |
| 143 | + ```python |
| 144 | + len('hello') # result: 5 |
| 145 | + ``` |
| 146 | + Note that the `len()` function is also applicable to all of Python's "container" data types, which are used to store multiple pieces of data at the same time (like lists, sets, and dictionaries) - all of these will be covered below! |
110 | 147 |
|
111 | | -Multiline comment: |
| 148 | +**Common Mistakes**: |
112 | 149 |
|
113 | | -```Python |
114 | | -# This is a |
115 | | -# multiline comment |
116 | | -``` |
| 150 | +Strings have such a wide definition, that it is easy to make mistakes when working with them. Here are some things to watch out for: |
| 151 | +1. Not enclosing them in single quotes (e.g. `'Hello'`) or double quotes (e.g. `"World"`) |
| 152 | +2. Although Python treats single and double quotes the same, you *cannot* combine the two (e.g. do NOT do `"Hello, World!'`) |
| 153 | +#### Quotes in Strings |
| 154 | + |
| 155 | +This doesn't mean that you are not allowed to mix double quotes and single quotes. As long as you enclose each pair of quotes, they can in fact be very useful to use together - such as when a string includes a quote! |
117 | 156 |
|
118 | | -Code with a comment: |
| 157 | +For example, the following is how you should NOT include quotes in a string together: |
119 | 158 |
|
120 | 159 | ```python |
121 | | -a = 1 # initialization |
| 160 | +print("I said "hello."") # ERROR! |
122 | 161 | ``` |
| 162 | +In the above code snippet, the `'hello'` ends up not being enclosed by any pair of quotes. |
123 | 163 |
|
124 | | -Please note the two spaces in front of the comment. |
125 | | - |
126 | | -Function docstring: |
127 | | - |
| 164 | +So how to remedy this? One option is to enclose the whole string in a pair of *single quotes*, so we can let the *double quotes* in the sentence enclose the `'hello'` properly: |
128 | 165 | ```python |
129 | | -def foo(): |
130 | | - """ |
131 | | - This is a function docstring |
132 | | - You can also use: |
133 | | - ''' Function Docstring ''' |
134 | | - """ |
| 166 | +print('I said "hello."') # all good :) |
135 | 167 | ``` |
136 | 168 |
|
137 | | -### The print Function |
| 169 | +Next, let's take a look at the Boolean data type! |
| 170 | +### Boolean Types |
| 171 | +The Boolean data type, represented as `bool` in Python, needs no overthinking - it simply represents whether `True` or `False`. |
138 | 172 |
|
139 | | -```python |
140 | | -print('Hello world!') |
141 | | -``` |
| 173 | +As you might imagine, they are especially useful for writing code that answers yes/no questions - we will discuss this more in-depth when we talk about [Control Flow](#control-flow). |
142 | 174 |
|
143 | | -```python |
144 | | -a = 1 |
145 | | -print('Hello world!', a) |
146 | | -``` |
| 175 | +### The str, int, and float Functions |
| 176 | +Python's data types are not necessarily set in stone. In some scenarios (shown below) we can convert, or *cast*, a given value in one data type to another, by calling the desired data type like a function! More technically, this is also called *explicit type conversion*. |
147 | 177 |
|
148 | | -### The input Function |
| 178 | +Here are examples of when we can interchange values between the `int`, `float`, and `str` types: |
149 | 179 |
|
150 | | -Example Code: |
| 180 | +1. Integer to String or Float: |
151 | 181 |
|
152 | | -```python |
153 | | -myName = input('What is your name?') # ask for their name |
154 | | -print('It is good to meet you, {}'.format(myName)) |
155 | | -``` |
| 182 | + ```python |
| 183 | + str(29) |
| 184 | + ``` |
156 | 185 |
|
157 | | -### The len Function |
| 186 | + ```python |
| 187 | + print('I am {} years old.'.format(str(29))) |
| 188 | + ``` |
158 | 189 |
|
159 | | -Evaluates to the integer value of the number of characters in a string: |
| 190 | + ```python |
| 191 | + str(-3.14) |
| 192 | + ``` |
160 | 193 |
|
161 | | -```python |
162 | | -len('hello') |
163 | | -``` |
| 194 | +2. Float to Integer: |
164 | 195 |
|
165 | | -Note: test of emptiness of strings, lists, dictionary, etc, should **not** use len, but prefer direct |
166 | | -boolean evaluation. |
| 196 | + ```python |
| 197 | + int(7.7) |
| 198 | + ``` |
| 199 | + |
| 200 | + ```python |
| 201 | + int(7.7) + 1 |
| 202 | + ``` |
| 203 | +Additionally, if you are ever unsure about what the data type of a given value currently is, you can check using the built-in `type()` function: |
167 | 204 |
|
168 | 205 | ```python |
169 | | -a = [1, 2, 3] |
170 | | -if a: |
171 | | - print("the list is not empty!") |
| 206 | +type(555) # result: <class: 'int'> |
172 | 207 | ``` |
173 | 208 |
|
174 | | -### The str, int, and float Functions |
| 209 | +## Variables |
| 210 | +The data in our program can change not only in its **type**. In addition, it is even more common for our data to change in its **value**. A *variable* in programming is how we represent some piece of data whose value can be many different things. |
175 | 211 |
|
176 | | -Integer to String or Float: |
| 212 | +Now, from math class you might be used to variable names like `x`, `y`, `z`, etc. - but in programming, it is actually preferable to use much more descriptive names! |
177 | 213 |
|
178 | | -```python |
179 | | -str(29) |
180 | | -``` |
| 214 | +You can name a variable anything as long as it obeys the following rules: |
| 215 | + |
| 216 | +1. It can be only one word. |
| 217 | +2. It can use only letters, numbers, and the underscore (`_`) character. |
| 218 | +3. It can’t begin with a number. |
| 219 | +4. Variable name starting with an underscore (`_`) are considered as "unuseful`. |
| 220 | + |
| 221 | +Example 1: |
181 | 222 |
|
182 | 223 | ```python |
183 | | -print('I am {} years old.'.format(str(29))) |
| 224 | +spam = 'Hello' |
184 | 225 | ``` |
| 226 | +Example 2: |
185 | 227 |
|
186 | 228 | ```python |
187 | | -str(-3.14) |
| 229 | +_spam = 'Hello' |
188 | 230 | ``` |
189 | 231 |
|
190 | | -Float to Integer: |
| 232 | +Because of how `_spam` is named, we know it is not a variable we should use again in the code. |
191 | 233 |
|
192 | | -```python |
193 | | -int(7.7) |
194 | | -``` |
| 234 | +## Control Flow |
| 235 | + |
| 236 | +## Functions |
| 237 | + |
| 238 | +Function docstring: |
195 | 239 |
|
196 | 240 | ```python |
197 | | -int(7.7) + 1 |
| 241 | +def foo(): |
| 242 | + """ |
| 243 | + This is a function docstring |
| 244 | + You can also use: |
| 245 | + ''' Function Docstring ''' |
| 246 | + """ |
198 | 247 | ``` |
199 | 248 |
|
| 249 | +## Container Types |
| 250 | + |
200 | 251 | ## Credits |
201 | 252 |
|
202 | 253 | This section would not be possible if not for the following sources: |
|
0 commit comments