Skip to content

Commit ff9d9be

Browse files
Merge pull request #1 from Akuli/master
Pull request for update latest
2 parents 865f136 + 0f840ff commit ff9d9be

16 files changed

+278
-113
lines changed

LICENSE

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
The instructions and text in this tutorial (the "software") are licensed
22
under the zlib License.
33

4-
(C) 2016-2018 Akuli
4+
(C) 2016-2021 Akuli
55

66
This software is provided 'as-is', without any express or implied
77
warranty. In no event will the authors be held liable for any damages

README.md

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Python programming tutorial
1+
# Python programming tutorial for beginners
22

33
This is a concise Python 3 programming tutorial for people who think
44
that reading is boring. I try to show everything with simple code
@@ -12,14 +12,8 @@ or very little programming experience. If you have programmed a lot in
1212
the past using some other language you may want to read [the official
1313
tutorial](https://docs.python.org/3/tutorial/) instead.
1414

15-
You can use Python 3.3 or any newer Python with this tutorial. **Don't
16-
use Python 2.** If you write a Python 2 program now someone will need to
17-
convert it to Python 3 later, so it's best to just write Python 3 to
18-
begin with. Python 3 code will work just fine in Python 4, so you don't
19-
need to worry about that. Python 2 also has horrible
20-
[Unicode](http://www.unicode.org/standard/WhatIsUnicode.html) problems,
21-
so it's difficult to write Python 2 code that works correctly with
22-
non-English characters (like π and ♫).
15+
You can use Python 3.5 or any newer Python with this tutorial. **Don't
16+
use Python 2 because it's no longer supported.**
2317

2418
## List of contents
2519

@@ -59,7 +53,7 @@ section. Most of the techniques explained here are great when you're
5953
working on a large project, and your code would be really repetitive
6054
without these things.
6155

62-
You can experient with these things freely, but please **don't use these
56+
You can experiment with these things freely, but please **don't use these
6357
techniques just because you know how to use them.** Prefer the simple
6458
techniques from the Basics part instead when possible. Simple is better
6559
than complex.
@@ -110,11 +104,8 @@ pull with git and run `make-html.py` again.
110104

111105
## Authors
112106

113-
I'm Akuli and I have written most of this tutorial, but these people
114-
have helped me with it:
115-
- [SpiritualForest](https://github.com/SpiritualForest): Lots of typing
116-
error fixes.
117-
- [theelous3](https://github.com/theelous3): Small improvements and fixes.
107+
I'm Akuli and I have written most of this tutorial, but other people have helped me with it.
108+
See [github's contributors page](https://github.com/Akuli/python-tutorial/graphs/contributors) for details.
118109

119110
***
120111

advanced/datatypes.md

Lines changed: 12 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -316,68 +316,25 @@ TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
316316
>>>
317317
```
318318

319-
Dictionaries have an `update` method that adds everything from another
320-
dictionary into it. So we can merge dictionaries like this:
319+
Usually it's easiest to do this:
321320

322321
```python
323-
>>> merged = {}
324-
>>> merged.update({'a': 1, 'b': 2})
325-
>>> merged.update({'c': 3})
326-
>>> merged
327-
{'c': 3, 'b': 2, 'a': 1}
328-
>>>
329-
```
330-
331-
Or we can [write a function](../basics/defining-functions.md) like this:
332-
333-
```python
334-
>>> def merge_dicts(dictlist):
335-
... result = {}
336-
... for dictionary in dictlist:
337-
... result.update(dictionary)
338-
... return result
339-
...
340-
>>> merge_dicts([{'a': 1, 'b': 2}, {'c': 3}])
341-
{'c': 3, 'b': 2, 'a': 1}
342-
>>>
322+
>>> dict1 = {'a': 1, 'b': 2}
323+
>>> dict2 = {'c': 3}
324+
>>> {**dict1, **dict2}
325+
{'a': 1, 'b': 2, 'c': 3}
343326
```
344327

345-
Kind of like counting things, merging dictionaries is also a commonly
346-
needed thing and there's a class just for it in the `collections`
347-
module. It's called ChainMap:
328+
Dictionaries also have an `update` method that adds everything from another
329+
dictionary into it, and you can use that too. This was the most common way to
330+
do it before Python supported `{**dict1, **dict2}`.
348331

349332
```python
350-
>>> import collections
351-
>>> merged = collections.ChainMap({'a': 1, 'b': 2}, {'c': 3})
333+
>>> merged = {}
334+
>>> merged.update({'a': 1, 'b': 2})
335+
>>> merged.update({'c': 3})
352336
>>> merged
353-
ChainMap({'b': 2, 'a': 1}, {'c': 3})
354-
>>>
355-
```
356-
357-
Our `merged` is kind of like the Counter object we created earlier. It's
358-
not a dictionary, but it behaves like a dictionary.
359-
360-
```python
361-
>>> for key, value in merged.items():
362-
... print(key, value)
363-
...
364-
c 3
365-
b 2
366-
a 1
367-
>>> dict(merged)
368-
{'c': 3, 'b': 2, 'a': 1}
369-
>>>
370-
```
371-
372-
Starting with Python 3.5 it's possible to merge dictionaries like this.
373-
**Don't do this unless you are sure that no-one will need to run your
374-
code on Python versions older than 3.5.**
375-
376-
```python
377-
>>> first = {'a': 1, 'b': 2}
378-
>>> second = {'c': 3, 'd': 4}
379-
>>> {**first, **second}
380-
{'d': 4, 'c': 3, 'a': 1, 'b': 2}
337+
{'a': 1, 'b': 2, 'c': 3}
381338
>>>
382339
```
383340

basics/answers.md

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ isn't exactly like mine but it works just fine it's ok, and you can
9292
print("Access denied.")
9393
```
9494

95-
Again, this is not a good way to ask a real password from the user.
95+
Again, this is not a good way to ask a real password from the user.
9696

9797
## Handy stuff: Strings
9898

@@ -156,7 +156,15 @@ isn't exactly like mine but it works just fine it's ok, and you can
156156
print(message, "!!!")
157157
print(message, "!!!")
158158
```
159-
159+
3. In the code below, `palindrome_input[::-1]` is the string `palindrome_input` reversed.
160+
For example, if `palindrome_input` is `"hello"`, then `palindrome_input[::-1]` is `"olleh"`.
161+
```python
162+
palindrome_input = input("Enter a string: ")
163+
if palindrome_input == palindrome_input[::-1]:
164+
print("This string is a palindrome")
165+
else:
166+
print("This string is not a palindrome")
167+
```
160168
## Lists and tuples
161169

162170
1. Look carefully. The `namelist` is written in `()` instead of `[]`,
@@ -296,6 +304,36 @@ isn't exactly like mine but it works just fine it's ok, and you can
296304
print(converted_numbers)
297305
```
298306
307+
5. ``` python
308+
row_count = int(input("Type the number of rows needed:"))
309+
for column_count in range(1, row_count+1):
310+
# Print numbers from 1 to column_count
311+
for number in range(1, column_count+1):
312+
print(number, end=" ")
313+
print() # creates a new line for the next row
314+
```
315+
If the user enters 5, we want to do a row with 1 column, then 2 columns, and so on until 5 columns.
316+
That would be `for column_count in range(1, 6)`, because the end of the range is excluded.
317+
In general, we need to specify `row_count + 1` so that it actually ends at `row_count`.
318+
The second loop is similar.
319+
320+
Usually `print(number)` puts a newline character at the end of the line, so that the next print goes to the next line.
321+
To get all numbers on the same line, we use a space instead of a newline character,
322+
but we still need `print()` to add a newline character once we have printed the entire row.
323+
324+
325+
326+
6. ```python
327+
row_count=int(input("Type the number of rows needed:"))
328+
329+
for line_number in range(1, row_count+1):
330+
for number in range(line_number, row_count+1):
331+
print(number, end=' ')
332+
print()
333+
```
334+
Just like in the previous exercise, if the user enters 5, the first `for` loop gives the line numbers `1, 2, 3, 4, 5`.<br>
335+
For example, on line 2, we should print numbers from 2 to 5, as in `range(2, 6)`, or in general, `range(line_number, row_count+1)`.
336+
299337
## Trey Hunner: zip and enumerate
300338
301339
1. Read some lines with `input` into a list and then enumerate it.

basics/docstrings.md

Lines changed: 137 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ thing(stuff)
4444
```
4545

4646
That sucked! We have no idea about what it does based on this. All we
47-
know is that it takes a `thing` argument.
47+
know is that it takes a `stuff` argument.
4848

4949
This is when documentation strings or docstrings come in. All we need to
5050
do is to add a string to the beginning of our function and it will show
@@ -198,11 +198,143 @@ this thing out of it.
198198
You might be wondering what `__weakref__` is. You don't need to care
199199
about it, and I think it would be better if `help()` would hide it.
200200

201+
## Popular Docstring Formats
202+
203+
There are different styles for writing docstrings. If you are contributing to
204+
another Python project, make sure to use the same style as rest of that project
205+
is using.
206+
207+
If you are starting a new project, then you can use whichever style you
208+
want, but don't "reinvent the wheel"; use an existing style instead instead of
209+
making up your own. Here are some examples of popular docstring styles to choose
210+
from:
211+
212+
### Sphinx Style
213+
214+
[Sphinx](https://www.sphinx-doc.org/en/master/) is the Python documentation tool
215+
that [the official Python documentation](https://docs.python.org/3/) uses.
216+
By default, sphinx expects you to write docstrings like this:
217+
218+
```python
219+
class Vehicles:
220+
"""
221+
The Vehicles object contains lots of vehicles.
222+
:param arg: The arg is used for ...
223+
:type arg: str
224+
:ivar arg: This is where we store arg
225+
:vartype arg: str
226+
"""
227+
228+
def __init__(self, arg):
229+
self.arg = arg
230+
231+
def cars(self, distance, destination):
232+
"""We can't travel a certain distance in vehicles without fuels, so here's the fuels
233+
234+
:param distance: The amount of distance traveled
235+
:type amount: int
236+
:param bool destinationReached: Should the fuels be refilled to cover required distance?
237+
:raises: :class:`RuntimeError`: Out of fuel
238+
239+
:returns: A Car mileage
240+
:rtype: Cars
241+
"""
242+
...
243+
```
244+
245+
### Google Style
246+
247+
Google Style is meant to be easier to read and use without a tool like sphinx.
248+
Sphinx can be configured to use that with
249+
[sphinx.ext.napoleon](https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html).
250+
251+
```python
252+
class Vehicles:
253+
"""
254+
The Vehicles object contains lots of vehicles.
255+
256+
Args:
257+
arg (str): The arg is used for...
258+
259+
Attributes:
260+
arg (str): This is where we store arg.
261+
"""
262+
263+
def __init__(self, arg):
264+
self.arg = arg
265+
266+
def cars(self, distance, destination):
267+
"""We can't travel distance in vehicles without fuels, so here is the fuels
268+
269+
Args:
270+
distance (int): The amount of distance traveled
271+
destination (bool): Should the fuels refilled to cover the distance?
272+
273+
Raises:
274+
RuntimeError: Out of fuel
275+
276+
Returns:
277+
cars: A car mileage
278+
"""
279+
...
280+
281+
```
282+
283+
### Numpy Style
284+
285+
[Numpy](https://numpy.org/) is a large and popular Python library,
286+
and numpy developers have their own docstring style.
287+
288+
```python
289+
class Vehicles:
290+
"""
291+
The Vehicles object contains lots of vehicles.
292+
293+
Parameters
294+
----------
295+
arg : str
296+
The arg is used for ...
297+
*args
298+
The variable arguments are used for ...
299+
**kwargs
300+
The keyword arguments are used for ...
301+
302+
Attributes
303+
----------
304+
arg : str
305+
This is where we store arg.
306+
"""
307+
308+
def __init__(self, arg):
309+
self.arg = arg
310+
311+
def cars(self, distance, destination):
312+
"""We can't travel distance in vehicles without fuels, so here is the fuels
313+
314+
Parameters
315+
----------
316+
distance : int
317+
The amount of distance traveled
318+
destination : bool
319+
Should the fuels refilled to cover the distance?
320+
321+
Raises
322+
------
323+
RuntimeError
324+
Out of fuel
325+
326+
Returns
327+
-------
328+
cars
329+
A car mileage
330+
"""
331+
pass
332+
```
333+
201334
## When should we use docstrings?
202335

203-
Always use docstrings when writing code that other people will import.
204-
The `help()` function is awesome, so it's important to make sure it's
205-
actually helpful.
336+
I recommend using docstrings when writing code that other people will import.
337+
The `help()` function is awesome, so it's good to make sure it's actually helpful.
206338

207339
If your code is not meant to be imported, docstrings are usually a good
208340
idea anyway. Other people reading your code will understand what it's
@@ -214,7 +346,7 @@ doing without having to read through all of the code.
214346
- A `"""triple-quoted string"""` string in the beginning of a function,
215347
class or file is a docstring. It shows up in `help()`.
216348
- Docstrings are not comments.
217-
- Usually it's a good idea to add docstrings everywhere
349+
- Usually it's a good idea to add docstrings everywhere.
218350

219351
***
220352

basics/editor-setup.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
# Setting up an editor for programming
22

33
An editor is a program that lets us write longer programs than we can
4-
write on the `>>>` prompt. Then we can save the programs to files and
4+
write on the `>>>` prompt. With an editor we can save the programs to files and
55
run them as many times as we want without writing them again.
66

77
When programmers say "editor" they don't mean programs like Microsoft
88
Word or LibreOffice/OpenOffice Writer. These programs are for writing
99
text documents, not for programming. **Programming editors don't support
1010
things like bigger font sizes for titles or underlining bits of text**,
1111
but instead they have features that are actually useful for programming,
12-
like automatically displaying different things with different colors.
12+
like automatically displaying different things with different colors,
13+
but also highlighting mistakes in the code, and coloring syntax.
1314

1415
If you are on Windows or Mac OSX you have probably noticed that your
1516
Python came with an editor called IDLE. We are not going to use it

0 commit comments

Comments
 (0)