diff --git a/.gitignore b/.gitignore index 196ae35..17e9066 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ html/ # python cache files __pycache__/ + +.idea \ No newline at end of file diff --git a/README.md b/README.md index feef6cc..5ca5531 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Python programming tutorial +# Python programming tutorial @ PyCon X Beginner's Day This is a concise Python 3 programming tutorial for people who think that reading is boring. I try to show everything with simple code @@ -7,12 +7,13 @@ words. If you have never programmed before click [here](basics/what-is-programming.md) to find out what programming is like and get started. -This tutorial is aimed at people with no programming experience at all -or very little programming experience. If you have programmed a lot in +This tutorial is composed in a basic part, aimed at people with no programming +experience at all or very little programming experience and an advance one for people +who want to learn more about python. If you have programmed a lot in the past using some other language you may want to read [the official -tutorial](https://docs.python.org/3/tutorial/) instead. +tutorial](https://docs.python.org/3/tutorial/) also. -You can use Python 3.3 or any newer Python with this tutorial. **Don't +You can use Python 3.6 or any newer Python with this tutorial. **Don't use Python 2.** If you write a Python 2 program now someone will need to convert it to Python 3 later, so it's best to just write Python 3 to begin with. Python 3 code will work just fine in Python 4, so you don't @@ -47,10 +48,9 @@ to learn more about whatever you want after studying it. 15. [Writing a larger program](basics/larger-program.md) 16. [What is true?](basics/what-is-true.md) 17. [Files](basics/files.md) -18. [Modules](basics/modules.md) -19. [Exceptions](basics/exceptions.md) -20. [Classes](basics/classes.md) -21. [Docstrings](basics/docstrings.md) +18. [Docstrings](basics/docstrings.md) + + ### Advanced @@ -61,13 +61,18 @@ without these things. You can experient with these things freely, but please **don't use these techniques just because you know how to use them.** Prefer the simple -techniques from the Basics part instead when possible. Simple is better -than complex. +techniques from the Basics part instead when possible. REMEMBER: *Simple is better +than complex*. + +1. [Modules](advances/modules.md) +2. [Exceptions](advanced/exceptions.md) +3. [Classes](advanced/classes.md) +4. [NamedTuples](advanced/named_tuples.md) +5. [Handy data types](advanced/datatypes.md) +6. [Advanced stuff with functions](advanced/functions.md) +7. [Magic methods](advanced/magicmethods.md) +8. [Iterables, iterators and generators](advanced/iters.md) -1. [Handy data types](advanced/datatypes.md) -2. [Advanced stuff with functions](advanced/functions.md) -3. [Magic methods](advanced/magicmethods.md) -4. [Iterables, iterators and generators](advanced/iters.md) ### Other things this tutorial comes with @@ -79,51 +84,11 @@ than complex. ## Frequently asked questions -### How can I thank you for writing and sharing this tutorial? - -You can star this tutorial. Starring is free for you, but it tells me -and other people that you like this tutorial. - -Go [here](https://github.com/Akuli/python-tutorial) if you aren't here -already and click the "Star" button in the top right corner. You will be -asked to create a GitHub account if you don't already have one. - -### How can I read this tutorial without an Internet connection? -1. Go [here](https://github.com/Akuli/python-tutorial) if you aren't - here already. -2. Click the big green "Clone or download" button in the top right of - the page, then click "Download ZIP". +## Special thanks - ![Download ZIP](images/download-me.png) - -3. Extract the ZIP and open it. Unfortunately I don't have any more - specific instructions because how exactly this is done depends on - which operating system you run. -4. Run `make-html.py` and follow the instructions. - -If you have git and you know how to use it, you can also clone the -repository instead of downloading a zip and extracting it. An advantage -with doing it this way is that you don't need to download the whole -tutorial again to get the latest version of it, all you need to do is to -pull with git and run `make-html.py` again. - -## Authors - -I'm Akuli and I have written most of this tutorial, but these people -have helped me with it: -- [SpiritualForest](https://github.com/SpiritualForest): Lots of typing - error fixes. -- [theelous3](https://github.com/theelous3): Small improvements and fixes. +Thanks to Akuli who wrote the most of this tutorial *** -If you have trouble with this tutorial please [tell me about -it](./contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](./README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](./LICENSE). - [List of contents](./README.md#list-of-contents) diff --git a/advanced/README.md b/advanced/README.md index cfa964c..3974b2e 100644 --- a/advanced/README.md +++ b/advanced/README.md @@ -13,19 +13,16 @@ techniques just because you know how to use them.** Prefer the simple techniques from the Basics part instead when possible. Simple is better than complex. -1. [Handy data types](datatypes.md) -2. [Advanced stuff with functions](functions.md) -3. [Magic methods](magicmethods.md) -4. [Iterables, iterators and generators](iters.md) +1. [Modules](advances/modules.md) +2. [Exceptions](advanced/exceptions.md) +3. [Classes](advanced/classes.md) +4. [NamedTuples](advanced/named_tuples.md) +5. [Handy data types](advanced/datatypes.md) +6. [Advanced stuff with functions](advanced/functions.md) +7. [Magic methods](advanced/magicmethods.md) +8. [Iterables, iterators and generators](advanced/iters.md) *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [List of contents](../README.md#list-of-contents) diff --git a/advanced/answers.md b/advanced/answers.md index d6a4371..ac74541 100644 --- a/advanced/answers.md +++ b/advanced/answers.md @@ -1,12 +1,4 @@ *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). - [List of contents](../README.md#list-of-contents) diff --git a/basics/classes.md b/advanced/classes.md similarity index 96% rename from basics/classes.md rename to advanced/classes.md index 3c1f27d..90594f3 100644 --- a/basics/classes.md +++ b/advanced/classes.md @@ -416,13 +416,6 @@ print("You entered " + word + ".") *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). - -[Previous](exceptions.md) | [Next](docstrings.md) | +[Previous](exceptions.md) | [Next](named_tuples.md) | [List of contents](../README.md#basics) diff --git a/advanced/classes2.md b/advanced/classes2.md new file mode 100644 index 0000000..979a3e2 --- /dev/null +++ b/advanced/classes2.md @@ -0,0 +1,54 @@ +# Class Inheritance + +We demonstrate inheritance in a very simple example. We create a Person class with the two attributes "firstname" and "lastname". This class has only one method, the Name method, essentially a getter, but we don't have an attribute name. This method is a further example for a "getter", which creates an output by creating it from more than one private attribute. Name returns the concatenation of the first name and the last name of a person, separated by a space. It goes without saying that a useful person class would have additional attributes and further methods. + +This chapter of our tutorial is about inheritance, so we need a class, which inherits from Person. So far employees are Persons in companies, even though they may not be treated as such in some firms. If we created an Employee class without inheriting from Person, we would have to define all the attributes and methods in the Employee class again. This means we would create a design and maybe even a data redundancy. With this in mind, we have to let Employee inherit from Person. + +The syntax for a subclass definition looks like this: + + +```python +class DerivedClassName(BaseClassName): + pass +``` + +Of course, usually we will have an indented block with the class attributes and methods instead of merely a pass statement. The name BaseClassName must be defined in a scope containing the derived class definition. With all this said, we can implement our Person and Employee class: + +```python +class Person: + + def __init__(self, first, last): + self.firstname = first + self.lastname = last + + def Name(self): + return self.firstname + " " + self.lastname + +class Employee(Person): + + def __init__(self, first, last, staffnum): + Person.__init__(self,first, last) + self.staffnumber = staffnum + + def GetEmployee(self): + return self.Name() + ", " + self.staffnumber + +x = Person("Marge", "Simpson") +y = Employee("Homer", "Simpson", "1007") +``` + +Our program returns the following output: + +```bash +$ python person.py +Marge Simpson +Homer Simpson, 1007 +``` + +The `__init__` method of our Employee class explicitly invokes the `__init__method` of the Person class. We could have used super instead. `super().__init__(first, last)` is automatically replaced by a call to the superclasses method, in this case `__init__`: + +````python + def __init__(self, first, last, staffnum): + super().__init__(first, last) + self.staffnumber = staffnum +```` \ No newline at end of file diff --git a/advanced/datatypes.md b/advanced/datatypes.md index 1477564..068c86d 100644 --- a/advanced/datatypes.md +++ b/advanced/datatypes.md @@ -390,13 +390,6 @@ code on Python versions older than 3.5.** *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](../basics/docstrings.md) | [Next](functions.md) | [List of contents](../README.md#advanced) diff --git a/basics/exceptions.md b/advanced/exceptions.md similarity index 97% rename from basics/exceptions.md rename to advanced/exceptions.md index 946d4f1..9fc1d42 100644 --- a/basics/exceptions.md +++ b/advanced/exceptions.md @@ -458,13 +458,6 @@ except OSError: *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](modules.md) | [Next](classes.md) | [List of contents](../README.md#basics) diff --git a/advanced/functions.md b/advanced/functions.md index 6accb1e..09c7058 100644 --- a/advanced/functions.md +++ b/advanced/functions.md @@ -290,13 +290,6 @@ does, so using keyword-only arguments makes sense. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](datatypes.md) | [Next](magicmethods.md) | [List of contents](../README.md#advanced) diff --git a/advanced/iters.md b/advanced/iters.md index 58cebbc..445c7d8 100644 --- a/advanced/iters.md +++ b/advanced/iters.md @@ -445,13 +445,6 @@ does the same thing as our `count()`. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](magicmethods.md) | [Next](../README.md) | [List of contents](../README.md#advanced) diff --git a/advanced/magicmethods.md b/advanced/magicmethods.md index c7f6e28..79cf172 100644 --- a/advanced/magicmethods.md +++ b/advanced/magicmethods.md @@ -33,7 +33,6 @@ class doesn't define anything else. For example, if we don't define an attributes by default. We'll learn more about this when we'll talk about [inheritance](classes2.md). -**TODO:** write a `classes2.md`. ## Custom length @@ -221,6 +220,89 @@ methods in things that other people will import and use in their projects, but `__repr__` methods aren't worth it for simple scripts that are not meant to be imported. +## Exercise + +The class CardDeck below represents a pack +of cards. +Find out how to use magic methods so that the +following three standard functions work: +``` + >>> import random + >>> deck = CardDeck() + >>> len(deck) + 52 + >>> print(deck[0]) + 2♠ + >>> print(deck[-1]) + A♣ + >>> random.choice(deck) in list(deck) + True + >>> random.shuffle(deck) +``` +Tip: +If you have lines in the docstring (this string) that look like interactive +Python sessions, you can use the doctest module to run and test this code. +Try: python3 -m doctest -v magic_methods.py +See: https://docs.python.org/3/library/doctest.html + +Credit to Luciano Ramalho and his excellent book Fluent Python, from which +I stole this example. +""" + +```python +class CardDeck: + ranks = [str(n) for n in range(2, 11)] + ['J', 'Q', 'K', 'A'] + suits = '♠♡♢♣' + + def __init__(self): + self._cards = [ + rank + suit + for suit in self.suits + for rank in self.ranks + ] +``` + + +Bonus exercise: + +Polynomial class +Create a class that represents polynomials. You may need to stretch your memory back to high school maths! +A polynomial loks like + `2(xx) - x + 7` +And its essential features are the coefficients of each power of x +in this example, power-2=2, power-1=-1, power-0=7 +Credit to Moshe Goldstein + +``` +class Polynomial: + def __init__(self, coefficients): + pass # TODO + + def __str__(self): + pass # TODO + + def __add__(self, poly): + '''returns the result of adding poly from self''' + pass # TODO + + def __sub__(self, poly): + '''returns the result of subtracting poly from self''' + pass # TODO + + def __mul__(self, poly): + '''multiply two polynomials''' + pass # TODO + + def value(self, x): + '''returns the value of the polynomial at point x''' + pass # TODO + + def derivative(self): + '''returns the derivate of the polynomial''' + pass # TODO +``` + + ## Summary - Magic methods define what instances of a class can do and how, like @@ -235,13 +317,7 @@ are not meant to be imported. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](functions.md) | [Next](iters.md) | [List of contents](../README.md#advanced) diff --git a/basics/modules.md b/advanced/modules.md similarity index 97% rename from basics/modules.md rename to advanced/modules.md index 44cacba..da8eb5a 100644 --- a/basics/modules.md +++ b/advanced/modules.md @@ -487,17 +487,8 @@ section at the bottom. - Python comes with many modules, and we can install even more modules if we want to. -**TODO:** exercises - *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](files.md) | [Next](exceptions.md) | [List of contents](../README.md#basics) diff --git a/advanced/named_tuples.md b/advanced/named_tuples.md new file mode 100644 index 0000000..bd0c858 --- /dev/null +++ b/advanced/named_tuples.md @@ -0,0 +1,69 @@ +# Named Tuples + +When you need to represent a list of identical objects with different values, you start with a list of tuples. It’s an efficient way to hold a collection of related data. Tuples are like structures or records in other languages, but indexed with integers, like lists. You can build a list named people, where each element is a tuple of three elements: first name, last name, and zip code. To get the zip code for the first element, you can use people[0][2]. + +The problem comes when you want to read in a file where each line has 17 fields. It gets really hard to remember which index is for which field. At this point, many programmers create a class with read-only properties for this purpose, so they can say class.field (e.g., people[0].first_name, people[0].last_name, etc.). Such a class has no methods; it only exists to store the data. + +It’s overkill to use a class for this purpose. Python provides an elegant solution – named tuples. A named tuple is exactly like a normal tuple, except that the fields can also be accessed by .fieldname. Named tuples are still immutable, you can still index elements with integers, and you can iterate over the elements. With a named tuple, you can say record.first_name, record.last_name, as with a class, but without the extra code of a class. There’s no need to write all the property definitions. + +The `collections.namedtuple` function is a factory that produces subclasses of tuple +enhanced with field names and a class name — which helps debugging. + +NOTE: *Instances of a class that you build with namedtuple take exactly the +same amount of memory as tuples because the field names are stor‐ +ed in the class. They use less memory than a regular object because +they do store attributes in a per-instance `__dict__`* + +## Defining and using a named tuple type + +```python +>>> from collections import namedtuple +>>> City = namedtuple('City', 'name country population coordinates') (1) +>>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) (2) +tokyo +>>> City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722, 139.691667)) +>>> tokyo.population (3) +36.933 +>>> tokyo.coordinates +(35.689722, 139.691667) +>>> tokyo[1] +'JP' +``` + +- (1) Two parameters are required to create a named tuple: a class name and a list of +field names, which can be given as an iterable of strings or as a single spacedelimited string +- (2) Data must be passed as positional arguments to the constructor (in contrast, the +tuple constructor takes a single iterable). +- (3) You can access the fields by name or position. + +## Named tuple attributes and methods + +A named tuple type has a few attributes in addition to those inherited from tuple. +The following code shows the most useful: the _fields class attribute, the class method +`_make(iterable)` and the `_asdict()` instance method + +```python +>>> City._fields (1) +('name', 'country', 'population', 'coordinates') +>>> LatLong = namedtuple('LatLong', 'lat long') +>>> delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889)) +>>> delhi = City._make(delhi_data) (2) +>>> delhi._asdict() (3) +OrderedDict([('name', 'Delhi NCR'), ('country', 'IN'), ('population', +21.935), ('coordinates', LatLong(lat=28.613889, long=77.208889))]) +>>> for key, value in delhi._asdict().items(): + print(key + ':', value) +name: Delhi NCR +country: IN +population: 21.935 +coordinates: LatLong(lat=28.613889, long=77.208889) +``` + +- (1) `_fields` is a tuple with the field names of the class. +- (2) `_make()` lets you instantiate a named tuple from an iterable; City(*delhi_da +ta) would do the same. +- (3) `_asdict()` returns a collections.OrderedDict built from the named tuple +instance. That can be used to produce a nice display of city data. + +[Previous](exceptions.md) | [Next](datatypes.md) | +[List of contents](../README.md#basics) \ No newline at end of file diff --git a/basics/README.md b/basics/README.md index 24f8547..bd342c8 100644 --- a/basics/README.md +++ b/basics/README.md @@ -6,36 +6,26 @@ This section will get you started with using Python and you'll be able to learn more about whatever you want after studying it. -1. [What is programming?](what-is-programming.md) -2. [Installing Python](installing-python.md) -3. [Getting started with Python](getting-started.md) -4. [ThinkPython: The way of the program](the-way-of-the-program.md) -5. [Variables, Booleans and None](variables.md) -6. [Using functions](using-functions.md) -7. [Setting up an editor](editor-setup.md) -8. [If, else and elif](if.md) -9. [Handy stuff with strings](handy-stuff-strings.md) -10. [Lists and tuples](lists-and-tuples.md) -11. [Loops](loops.md) -12. [Trey Hunner: zip and enumerate](trey-hunner-zip-and-enumerate.md) -13. [Dictionaries](dicts.md) -14. [Defining functions](defining-functions.md) -15. [Writing a larger program](larger-program.md) -16. [What is true?](what-is-true.md) -17. [Files](files.md) -18. [Modules](modules.md) -19. [Exceptions](exceptions.md) -20. [Classes](classes.md) -21. [Docstrings](docstrings.md) +1. [What is programming?](basics/what-is-programming.md) +2. [Installing Python](basics/installing-python.md) +3. [Getting started with Python](basics/getting-started.md) +4. [ThinkPython: The way of the program](basics/the-way-of-the-program.md) +5. [Variables, Booleans and None](basics/variables.md) +6. [Using functions](basics/using-functions.md) +7. [Setting up an editor](basics/editor-setup.md) +8. [If, else and elif](basics/if.md) +9. [Handy stuff with strings](basics/handy-stuff-strings.md) +10. [Lists and tuples](basics/lists-and-tuples.md) +11. [Loops](basics/loops.md) +12. [Trey Hunner: zip and enumerate](basics/trey-hunner-zip-and-enumerate.md) +13. [Dictionaries](basics/dicts.md) +14. [Defining functions](basics/defining-functions.md) +15. [Writing a larger program](basics/larger-program.md) +16. [What is true?](basics/what-is-true.md) +17. [Files](basics/files.md) +18. [Docstrings](basics/docstrings.md) *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [List of contents](../README.md#list-of-contents) diff --git a/basics/answers.md b/basics/answers.md index de739c3..178cb60 100644 --- a/basics/answers.md +++ b/basics/answers.md @@ -1,446 +1,3 @@ # Answers -These are my answers for exercises in the chapters. If your solution -isn't exactly like mine but it works just fine it's ok, and you can -[ask me](../contact-me.md) why I didn't do it like you did it. - -## ThinkPython: The way of the program - -1. With +, the strings get added together, and with * we get an error. -2. With + we get an error, and with * the string is repeated multiple times. -3. Python calculates the result and echoes it. - -## If, else and elif - -1. Problems and solutions: - - - The first line should be `print("Hello!")` or `print('Hello!')`, - not `print(Hello!)`. `Hello!` is a piece of text, so we need to - tell Python that it's a string by putting quotes around it. - - The second line will create an error message that says that - there's no variable called `something`. But we are trying to - create it here, so we need `=` instead of `==`. `=` is - assigning, `==` is comparing. - - The last line should have a comma between the arguments, like - `print('You entered:', something)`. - -2. The broken code has mostly the same issues as exercise 1. Here are - the problems that excercise 1 doesn't have: - - - The if-elif-else has a blank line at a confusing place. Delete it. - - After deleting the code, it looks quite dense. Add a new blank - line before the `if`. - - The elif line is missing a `:` at the end. - - On the last line the comma is on the wrong side. `"bla bla,"` is - a string that **contains** a comma, but `"bla bla",` is a - string and a **separate** comma. In this exercise, the last - line should be `print("I don't know what", something, "means.")` - -3. We can simply ask the word with input and print `word * 1000`. - - ```python - word = input("Enter a word: ") - print(word * 1000) - ``` - -4. We can add a space to the word before we print it. - - ```python - word = input("Enter a word: ") - word += " " - print(word * 1000) - ``` - - We can also add the space right away on the first line: - - ```python - word = input("Enter a word: ") + " " - print(word * 1000) - ``` - - Of course, there are 999 spaces between 1000 words and this will - print 1000 spaces instead, so there will be a useless space at the - end, but it doesn't matter. If we really want to get rid of the - space, we can do something like this instead: - - ```python - no_space = input("Enter a word: ") - yes_space = no_space + " " - print(yes_space*999 + no_space) - ``` - -5. Like this: - - ```python - first = input("Enter a word: ") - second = input("Enter another word: ") - words = first + " " + second + " " - print(words * 1000) - ``` - -6. We can compare the word against an empty string (`""` or `''`) to - check if it's empty. In this example, the password is "seKr3t". - - ```python - word = input("Enter your password: ") - - if word == "seKr3t": - print("Welcome!") - elif word == "": - print("You didn't enter anything.") - else: - print("Access denied.") - ``` - - Again, this is not a good way to ask a real password from the user. - -## Handy stuff: Strings - -1. The program is not like you might expect it to be. It actually works - just fine if we run it, but there's a problem. The last line is - really long and it's hard to see what it does. - - The solution is string formatting. At the time of writing this, I - recommend replacing the last line with one of these: - - ```python - print("You entered %s, %s, %s and %s." % (word1, word2, word3, word4)) - print("You entered {}, {}, {} and {}.".format(word1, word2, word3, word4)) - ``` - - In the future when most people will have Python 3.6 or newer, you - can also use this: - - ```python - print(f"You entered {word1}, {word2}, {word3} and {word4}.") - ``` - -2. If we have a look at `help(str.upper)` it looks like this: - - S.upper() -> str - - Return a copy of S converted to uppercase. - - We have two problems. First of all, the broken code uses - `message.upper` instead of `message.upper()`. It also expects the - message to magically make itself uppercased, but strings can't be - changed in-place so it doesn't work. - - The solution is to do `message.upper()` and save the value we got - from that to a variable: - - ```python - message = input("What do you want me to say? ") - uppermessage = message.upper() - print(uppermessage, "!!!") - print(uppermessage, "!!!") - print(uppermessage, "!!!") - ``` - - Or we can reuse the same variable name: - - ```python - message = input("What do you want me to say? ") - message = message.upper() - print(message, "!!!") - print(message, "!!!") - print(message, "!!!") - ``` - - Or we can convert the message to uppercase right away on the first - line: - - ```python - message = input("What do you want me to say? ").upper() - print(message, "!!!") - print(message, "!!!") - print(message, "!!!") - ``` - -## Lists and tuples - -1. Look carefully. The `namelist` is written in `()` instead of `[]`, - so it's actually a tuple, not a list. Using confusing variable names - is of course a bad idea, but you shouldn't be surprised if someone - is doing that. Replace the `()` with `[]` and the code will work. - -2. When we run the program we get a weird error: - - Hello! - Enter your name: my name - Traceback (most recent call last): - File "program.py", line 3, in - print("Your name is " + name + ".") - TypeError: Can't convert 'tuple' object to str implicitly - - So Python is trying to convert a tuple to a string. But - `"Your name is "` and `"."` are strings, so maybe `name` is a - tuple? Let's change the last line to just `print(name)` so our - program looks like this: - - ```python - print("Hello!") - name = input("Enter your name: "), - print(name) - ``` - - Let's run it. - - Hello! - Enter your name: my name - ('my name',) - - `name` is indeed a tuple! The problem is the second line. Look - carefully, there's a comma after `input("Enter your name: ")`. - Python created a tuple automatically, but that's not what we - wanted. If we remove the comma, everything works just fine. - -3. Again, the code gives us a weird error message. - - Enter your name: my name - Traceback (most recent call last): - File "program.py", line 3, in - if input("Enter your name: ") in namelist: - TypeError: argument of type 'NoneType' is not iterable - - Now we need to remember that when the error messages talk about - `NoneType` [they always mean None](variables.md#none). So - `namelist` seems to be None. Let's make the program a bit simpler - for working on the namelist: - - ```python - namelist = ['wub_wub', 'RubyPinch', 'go|dfish', 'Nitori'] - namelist = namelist.extend('theelous3') - print(namelist) - ``` - - Now fixing the namelist is easier, so I'll just go through the - problems and solutions: - - - `namelist` is None. It should be `namelist.extend('theelous3')`, - not `namelist = namelist.extend('theelous3')`. See [this - thing](using-functions.md#return-values). - - Now the namelist is like `['wub_wub', ..., 't', 'h', 'e', 'e', ...]`. - Python treated `'theelous3'` like a list so it added each of its - characters to `namelist`. We can use `namelist.append('theelous3')` - or `namelist.extend(['theelous3'])` instead to solve this problem. - -## Loops - -1. The problem is that `things` is a string because we converted it to a - string with `str`, so the for loop loops over the characters `[`, - `1`, `,` and so on. Replace `str([1, 2, 3, 4, 5])` with - `[1, 2, 3, 4, 5]`. - -2. The code appends each list in `before` to `after`, so the `number` - variable actually pointed to a list like `[1, 2]`. An easy solution - is to just write two for loops inside each other: - - ```python - before = [[1, 2], [3, 4], [5, 6]] - after = [] - for sublist in before: - for number in sublist: - after.append(number) - print(after) - ``` - - Lists also have an extend method that appends each item from another - list, so we can also use that: - - ```python - before = [[1, 2], [3, 4], [5, 6]] - after = [] - for sublist in before: - after.extend(sublist) - print(after) - ``` - -3. The code has some empty lines in it, and they divide it nicely into - three parts. All of these parts have some problems, so I'll go - through them one by one. - - The first part makes a variable called `input`. The problem is that - now the rest of the program [can't use the input - function](using-functions.md#variables-names-and-builtin-things). It - doesn't really matter here because the rest of the program doesn't - use it anyway, but I still recommend using some other variable name, - like `inputlist`. - - The second part runs `numbers = []` three times. It was probably - meant to be ran once before the loop started, like this: - - ```python - numbers = [] - for string in inputlist: - numbers.append(int(string)) - ``` - - The third part calculates `result + n` but throws away the value. - It was probably supposed to do `result += n` instead. - -4. If you run this program you'll notice that nothing happened to the - numbers list. The reason is that the `number` variable only works - one way. It gets its values from the `numbers` list, but changing it - doesn't change the `numbers` list. In general, `thing = stuff` - changes the `thing` variable, and that's it. It doesn't change - anything else. - - An easy solution is to just create a new list: - - ```python - numbers = ['1', '2', '3'] - converted_numbers = [] - for number in numbers: - converted_numbers.append(int(number)) - print(converted_numbers) - ``` - -## Trey Hunner: zip and enumerate - -1. Read some lines with `input` into a list and then enumerate it. - - ```python - print("Enter something, and press Enter without typing anything", - "when you're done.") - - lines = [] - while True: - line = input('>') - if line == '': - break - lines.append(line) - - for index, line in enumerate(lines, start=1): - print("Line", index, "is:", line) - ``` - -2. Let's start by trying out `zip` with strings: - - ```python - >>> for pair in zip('ABC', 'abc'): - ... print(pair) - ... - ('A', 'a') - ('B', 'b') - ('C', 'c') - >>> - ``` - - Great, it works just like it works with lists. Now let's create - the letter printing program: - - ```python - uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' - lowercase = 'abcdefghijklmnopqrstuvwxyz' - - for upper, lower in zip(uppercase, lowercase): - print(upper, lower) - ``` - -3. This one is a bit more difficult than the other two because we - need to combine `zip` and `enumerate`. One way to do this is - to pass a `zip` result to `enumerate`, like this: - - ```python - uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' - lowercase = 'abcdefghijklmnopqrstuvwxyz' - - for index, letterpair in enumerate(zip(uppercase, lowercase), start=1): - upper, lower = letterpair - print(index, upper, lower) - ``` - - We can also save the zip result to a variable. I would - probably do this. - - ```python - uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' - lowercase = 'abcdefghijklmnopqrstuvwxyz' - - letterzip = zip(uppercase, lowercase) - for index, letterpair in enumerate(letterzip, start=1): - upper, lower = letterpair - print(index, upper, lower) - ``` - - Another alternative is to pass an `enumerate` result to `zip`. This is - a bit more complicated, so I wouldn't do it this way. - - ```python - uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' - lowercase = 'abcdefghijklmnopqrstuvwxyz' - - for upper, indexlowerpair in zip(uppercase, enumerate(lowercase, start=1)): - index, lower = indexlowerpair - print(index, upper, lower) - ``` - -## Defining functions - -1. The problem with the first example is that name is a local variable. - I explained how to fix this in [the output section](defining-functions.md#output): - - ```python - def ask_name(): - name = input("Enter your name: ") - return name - - print("Your name is", ask_name()) - ``` - -2. If you run the next example, you get something like this: - - - - The problem is that we print the actual `get_greeting` function, - but we need to **call** it like `get_greeting()`: - - ```python - def get_greeting(): - return "Hello World!" - - print(get_greeting()) - ``` - -3. See [the return or print section](defining-functions.md#return-or-print). - - The greet function prints a greeting. - - ```python - >>> greet("World") - Hello World - >>> - ``` - - But it also returns None because we don't tell it to return anything else. - - ```python - >>> return_value = greet("World") - Hello World - >>> print(return_value) - None - >>> - ``` - - This code from the exercise does the same thing as the code above - does, but without a temporary `return_value` variable: - - ```python - >>> print(greet("World")) - Hello World - None - >>> - ``` - -*** - -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). - [List of contents](../README.md#list-of-contents) diff --git a/basics/defining-functions.md b/basics/defining-functions.md index ebe9e12..661d951 100644 --- a/basics/defining-functions.md +++ b/basics/defining-functions.md @@ -572,13 +572,6 @@ Answers for the first, second and third exercise are *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](dicts.md) | [Next](larger-program.md) | [List of contents](../README.md#basics) diff --git a/basics/dicts.md b/basics/dicts.md index 9784c5d..880236c 100644 --- a/basics/dicts.md +++ b/basics/dicts.md @@ -323,14 +323,51 @@ Running the program might look like this: **TODO:** Exercises. *** +## Exercises -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). +Given the following dictionary: +``` +inventory = { + 'gold' : 500, + 'pouch' : ['flint', 'twine', 'gemstone'], + 'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'] +} +``` + +Try to do the followings: +1) Add a key to inventory called 'pocket'. +2) Set the value of 'pocket' to be a list consisting of the strings 'seashell', 'strange berry', and 'lint'. +3) .sort() the items in the list stored under the 'backpack' key. +4) Then .remove('dagger') from the list of items stored under the 'backpack' key. +5) Add 50 to the number stored under the 'gold' key + + +Create 2 new dictionaries called 'prices' and 'stock' using {} format with this values: + + --prices-- + "banana": 4, + "apple": 2, + "orange": 1.5, + "pear": 3 + --stock-- + "banana": 6, + "apple": 7, + "orange": 1, + "pear": 3 + +1) Loop through each key in prices. For each key, print out the key along with its price and stock information. + Print the answer in the following format: + + apple + price: 2 + stock: 0 + +2) Let's determine how much money you would make if you sold all of your food: + - Create a variable called total and set it to zero. + - Loop through the prices dictionaries. For each key in prices, multiply the number in prices by the number in + stock. Print that value into the console and then add it to total. + - Finally, outside your loop, print total. [Previous](trey-hunner-zip-and-enumerate.md) | [Next](defining-functions.md) | [List of contents](../README.md#basics) diff --git a/basics/docstrings.md b/basics/docstrings.md index bbebfa3..f5085c1 100644 --- a/basics/docstrings.md +++ b/basics/docstrings.md @@ -218,13 +218,6 @@ doing without having to read through all of the code. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). - -[Previous](classes.md) | [Next](../advanced/datatypes.md) | +[Previous](classes.md) | [Next](../advanced/modules.md) | [List of contents](../README.md#basics) diff --git a/basics/editor-setup.md b/basics/editor-setup.md index 4176cf4..81e6be7 100644 --- a/basics/editor-setup.md +++ b/basics/editor-setup.md @@ -1,4 +1,4 @@ -# Setting up an editor for programming +# Setting up an editor for programming (OPTIONAL) An editor is a program that lets us write longer programs than we can write on the `>>>` prompt. Then we can save the programs to files and @@ -22,38 +22,17 @@ The choice of an editor is a very personal thing. There are many editors, and most programmers have a favorite editor that they use for everything and recommend to everyone. -If you aren't sure about which editor you should use, I recommend -Porcupine. It's a simple editor I wrote in Python; it lets you edit -files and it doesn't have too many other featues. [Install it with these -instructions](https://github.com/Akuli/porcupine/wiki/Installing-and-Running-Porcupine), -and then [learn to use it by writing the classic Hello World -program](https://github.com/Akuli/porcupine/wiki/First-Program). Then -you can [skip the rest of this chapter](#editor-or--prompt). +Suggested editors: -Note that most other editors come with settings that are not suitable -for writing Python code. _**TODO:** add a link to the old editor setup -tutorial here._ +- [PyCharm](https://www.jetbrains.com/pycharm/) +- [Sublime Text](https://www.sublimetext.com/) +- [Atom](https://atom.io/) +- [Visual Studio Code](https://code.visualstudio.com/) +- [Vim](https://www.vim.org/) - for shell experts +- [emacs](https://www.gnu.org/software/emacs/) - for octopuses :laughing: -Most of these editors lack some important features, they have so many -features that confuse people or they aren't free. You can use these -editors if you like them, but **these editors are BAD for getting -started with programming**: - -- PyCharm -- IDLE -- Emacs -- Gedit -- Nano -- NetBeans -- Notepad -- Pluma -- Spyder -- Vim -- Wingware - -This list doesn't contain all bad editors, but these are editors that -people often try to use. If you know a bad editor and you think I should -mention it here, please [let me know](../contact-me.md). +This list doesn't contain all editors, but these are editors that +people often try to use. ## Editor or `>>>` prompt? @@ -77,13 +56,5 @@ echoes it back, but if you make a file that contains nothing but a *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). - [Previous](using-functions.md) | [Next](if.md) | [List of contents](../README.md#basics) diff --git a/basics/files.md b/basics/files.md index 82705d0..101b841 100644 --- a/basics/files.md +++ b/basics/files.md @@ -365,13 +365,6 @@ else: *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). - -[Previous](what-is-true.md) | [Next](modules.md) | +[Previous](what-is-true.md) | [Next](docstrings.md) | [List of contents](../README.md#basics) diff --git a/basics/getting-started.md b/basics/getting-started.md index facdccf..5bed79e 100644 --- a/basics/getting-started.md +++ b/basics/getting-started.md @@ -212,13 +212,7 @@ enough when you need to calculate something. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](installing-python.md) | [Next](the-way-of-the-program.md) | [List of contents](../README.md#basics) diff --git a/basics/handy-stuff-strings.md b/basics/handy-stuff-strings.md index be89c55..e3e450f 100644 --- a/basics/handy-stuff-strings.md +++ b/basics/handy-stuff-strings.md @@ -425,17 +425,9 @@ ValueError: could not convert string to float: 'hello' print(message, "!!!") ``` -The answers are [here](answers.md#handy-stuff-strings). *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](if.md) | [Next](lists-and-tuples.md) | [List of contents](../README.md#basics) diff --git a/basics/if.md b/basics/if.md index a1fed8e..866445c 100644 --- a/basics/if.md +++ b/basics/if.md @@ -312,17 +312,9 @@ you are asked to "fix code", feel free to add missing blank lines. the user entered the correct password, a wrong password, or nothing at all by pressing Enter without typing anything. -The answers are [here](answers.md#if-else-and-elif). *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](editor-setup.md) | [Next](handy-stuff-strings.md) | [List of contents](../README.md#basics) diff --git a/basics/installing-python.md b/basics/installing-python.md index cc693bf..9bdf905 100644 --- a/basics/installing-python.md +++ b/basics/installing-python.md @@ -1,11 +1,5 @@ # Installing Python -If you want to learn to program with Python using this tutorial, you -need to try out the code examples. You can use a website like -[repl.it](https://repl.it/languages/python3), but I highly recommend -installing Python. That way you don't need to open a web browser just -to write code, and you can work without an Internet connection. - It doesn't matter which operating system you use because Python runs great on Windows, Mac OSX, Linux and many other operating systems. However, installing and launching Python are done differently on @@ -31,18 +25,37 @@ Installing Python on Windows is a lot like installing any other program. ### Mac OSX At the time of writing this, Macs don't come with a Python 3 and you -need to install it yourself. It should be like installing any other -program, but unfortunately I don't have better instructions because I -don't have an up-to-date Mac and I have never installed Python on a Mac. -If you would like to write better instructions, [tell -me](../contact-me.md). +need to install it yourself. To install python on your Mac please follow the instruction +[here](https://docs.python-guide.org/starting/install3/osx/). ### Linux -You already have Python 3, **there's no need to install anything**. You -may also have Python 2, but don't try to remove it. Some of your -programs are probably written in Python 2, so removing Python 2 would -break them. +If you have a recent Linux distribution you already have Python 3, +**there's no need to install anything**. To check if Python 3 is already on your operating +system run: `python --version`. + +If you need to install python 3 please follow the istructions behind: + +#### Ubuntu/Debian + +``` +sudo apt-get update +sudo apt-get install python3.7 +``` + +If you’re using another version of Ubuntu (e.g. the latest LTS release), we recommend using the deadsnakes PPA to install Python 3.7: +``` +$ sudo apt-get install software-properties-common +$ sudo add-apt-repository ppa:deadsnakes/ppa +$ sudo apt-get update +$ sudo apt-get install python3.7 +``` + + +#### Fedora/CentOS +``` +sudo dnf install python3 +``` ## Running Python @@ -77,13 +90,6 @@ Now you should have Python installed, and you should be able run it. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](what-is-programming.md) | [Next](getting-started.md) | [List of contents](../README.md#basics) diff --git a/basics/larger-program.md b/basics/larger-program.md index f8f9bfa..43e7b37 100644 --- a/basics/larger-program.md +++ b/basics/larger-program.md @@ -212,10 +212,7 @@ if __name__ == '__main__': main() ``` -This is just the beginning. Now [you can](../LICENSE) take your word -asking program and make your own version of it that suits **your** -needs. Then you can share it with your friends so they will find it -useful as well. + ## Summary @@ -228,13 +225,6 @@ something else when it's imported. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](defining-functions.md) | [Next](what-is-true.md) | [List of contents](../README.md#basics) diff --git a/basics/lists-and-tuples.md b/basics/lists-and-tuples.md index 77ea0ca..de0a455 100644 --- a/basics/lists-and-tuples.md +++ b/basics/lists-and-tuples.md @@ -100,7 +100,8 @@ Lists have a few [useful methods](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists). Some of the most commonly used ones are append, extend and remove. `append` adds an item to the end of a list, `extend` adds -multiple items from another list and `remove` removes an item. +multiple items from another list and `remove` removes an item. +It can also be added with the method of `insert` ```python >>> names @@ -115,7 +116,9 @@ multiple items from another list and `remove` removes an item. >>> names.extend(['go|dfish', 'theelous3']) # wb guys >>> names ['wub_wub', 'RubyPinch', 'Nitori', 'Akuli', 'go|dfish', 'theelous3'] ->>> +>>> names.insert(len(names), "Aly") +>>> names +['wub_wub', 'RubyPinch', 'Nitori', 'Akuli', 'go|dfish', 'theelous3', 'Aly'] ``` Note that `remove` removes only the first match it finds. @@ -128,6 +131,26 @@ Note that `remove` removes only the first match it finds. >>> ``` +The method `pop` also works for delete elements of the list. + +```python +>>> names = ['theelous3', 'go|dfish', 'theelous3'] +>>> names.pop(1) +>>> names # the second item was removed +'go|dfish' +>>> names +['theelous3', 'theelous3'] + +>>> names = ['theelous3', 'go|dfish', 'theelous3'] +>>> names.pop() +theelous3' +>>> names +['theelous3', 'go|dfish'] + +>>> +``` + + If we need to remove all matching items we can use a simple while loop. We'll talk more about loops [in the next chapter](loops.md). @@ -230,6 +253,44 @@ like this: ![Different lists.](../images/differentlist.png) + +We can count the number of items that have a list. + +```python +>>> a = [1, 2, 3, 4, 2, 5, 2] +>>> a.count(2) +3 +>>> a.count(5) +1 +>>> a.count(9) +0 +>>> a = ['theelous3', 'wub_wub', 'RubyPinch', 'go|dfish', 'Nitori'] +>>> a.count('wub_wub') +1 +``` + + +We can sort the items that have a list + +```python +>>> a = [1, 2, 3, 4, 2, 5, 2] +>>> a.sort() +>>> a +[1, 2, 2, 2, 3, 4, 5] +>>> a.sort(reverse = True) +>>> a +[5, 4, 3, 2, 2, 2, 1] +>>> a = ['wub_wub', 'theelous3', 'RubyPinch', 'go|dfish', 'Nitori'] +>>> a.sort() +>>> a +['Nitori', 'RubyPinch', 'go|dfish', 'theelous3', 'wub_wub'] +>>> a.sort(reverse = True) +['wub_wub', 'theelous3', 'go|dfish', 'RubyPinch', 'Nitori'] +>>> +``` + + + ## Tuples Tuples are a lot like lists, but they're immutable so they @@ -274,6 +335,41 @@ but some people like to do it this way. >>> ``` + +You can have nested tuples. + +```python +>>> n = 1, 2, 3 +>>> n +(1, 2, 3) +>>> n[0] +1 +>>> l = 'a', 'b', 'c' +>>> l +('a', 'b', 'c') +>>> l[0] +'a' +>>> t = n, l +>>> t +((1, 2, 3), ('a', 'b', 'c')) #The tuples n and l are nested +>>> t[0] +(1, 2, 3) +>>> t[1] +('a', 'b', 'c') +>>> t[1][2] +'c' +>>> v = ([1, 2, 3], [3, 2, 1,[7, 8, 9]]) +>>> v +([1, 2, 3], [3, 2, 1, [7, 8, 9]]) +>>> v[1] +[3, 2, 1, [7, 8, 9]] +>>> v[1][3] +[7, 8, 9] +>>> v[1][3][0] +7 +``` + + Tuples don't have methods like append, extend and remove because they can't change themselves in-place. @@ -348,17 +444,8 @@ else: print("I don't know you.") ``` -The answers are [here](answers.md#lists-and-tuples). - *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](handy-stuff-strings.md) | [Next](loops.md) | [List of contents](../README.md#basics) diff --git a/basics/loops.md b/basics/loops.md index 57f6b50..8a0b0d4 100644 --- a/basics/loops.md +++ b/basics/loops.md @@ -133,6 +133,29 @@ immediately. >>> ``` +While with a condition + +```python +>>> cont = 10 +>>> while (cont >= 0): +... print(cont) +... cont -= 1 +... +10 +9 +8 +7 +6 +5 +4 +3 +2 +1 +0 +>>> +``` + + ## Until loops Python doesn't have until loops. If we need an until loop, we can use @@ -212,6 +235,7 @@ how about you >>> ``` + Without the comments, that's only two simple lines, and one variable. Much better than anything else we tried before. @@ -232,6 +256,7 @@ Here the `in` keyword is just a part of the for loop and it has a different meaning than it would have if we had `thing in stuff` without a `for`. Trying to do `for (thing in stuff):` creates an error. + Right now the while loop version might seem easier to understand for you, but later you'll realize that for loops are much easier to work with than while loops and index variables, especially in large projects. @@ -260,9 +285,30 @@ c >>> ``` +You can print the multiplication tables. + +```python +>>> table = 2 +>>> for i in range(1, 11): +... print(table,"x", i, "=",(table*i)) +... +2 x 1 = 2 +2 x 2 = 4 +2 x 3 = 6 +2 x 4 = 8 +2 x 5 = 10 +2 x 6 = 12 +2 x 7 = 14 +2 x 8 = 16 +2 x 9 = 18 +2 x 10 = 20 +>>> +``` + If we can for loop over something, then that something is **iterable**. Lists, tuples and strings are all iterable. + There's only one big limitation with for looping over lists. We shouldn't modify the list in the for loop. If we do, the results can be surprising: @@ -471,17 +517,9 @@ while True: print(numbers) ``` -The answers are [here](answers.md#loops). *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](lists-and-tuples.md) | [Next](trey-hunner-zip-and-enumerate.md) | [List of contents](../README.md#basics) diff --git a/basics/the-way-of-the-program.md b/basics/the-way-of-the-program.md index ebb44bc..6d7b2e8 100644 --- a/basics/the-way-of-the-program.md +++ b/basics/the-way-of-the-program.md @@ -38,13 +38,6 @@ learned everything. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](getting-started.md) | [Next](variables.md) | [List of contents](../README.md#basics) diff --git a/basics/trey-hunner-zip-and-enumerate.md b/basics/trey-hunner-zip-and-enumerate.md index 3a211de..d2f6f94 100644 --- a/basics/trey-hunner-zip-and-enumerate.md +++ b/basics/trey-hunner-zip-and-enumerate.md @@ -131,17 +131,9 @@ Read it now, then come back here and do the exercises. 26 Z z ``` -The answers are [here](answers.md). *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](loops.md) | [Next](dicts.md) | [List of contents](../README.md#basics) diff --git a/basics/using-functions.md b/basics/using-functions.md index 123910a..a058c76 100644 --- a/basics/using-functions.md +++ b/basics/using-functions.md @@ -214,6 +214,39 @@ color, so you don't need to worry about doing this accidentally. Exit out of Python and start it again, and `print("Hello World!")` should work normally. +## Exercises + + +- Write a Python function to find the Max of three numbers. + + +- Write a Python function to sum all the numbers in a given list. +Sample List : (8, 2, 3, 0, 7) +Expected Output : 20 + + +- Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. +Sample String : 'The quick Brow Fox' +Expected Output : +No. of Upper case characters : 3 +No. of Lower case Characters : 12 + + +- Write a function named right_justify that takes a string named s as a parameter and prints the string with enough l +eading spaces so that the last letter of the string is in column 70 of the display. + [] right_justify('allen') + [] allen + + +- Write a Python function to check whether a number is perfect or not. +According to Wikipedia : In number theory, a perfect number is a positive integer that is equal to the sum of its proper +positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot +sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors +(including itself). +Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. +Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. +The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128. + ## Summary - `function()` calls a function without any arguments, and @@ -228,13 +261,6 @@ should work normally. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](variables.md) | [Next](editor-setup.md) | [List of contents](../README.md#basics) diff --git a/basics/variables.md b/basics/variables.md index 4b9c25b..5d1406d 100644 --- a/basics/variables.md +++ b/basics/variables.md @@ -118,11 +118,40 @@ can also use `+=`, `-=`, `*=` and `/=` instead of `+`, `-`, `*` and `/`. The "advanced" `%=`, `//=` and `**=` also work. ```python +>>> a = 11 >>> a += 2 # a = a + 2 +>>> a +13 + +>>> a = 11 >>> a -= 2 # a = a - 2 +>>> a +9 + +a = 11 >>> a *= 2 # a = a * 2 +>>> a +22 + +>>> a = 11 >>> a /= 2 # a = a / 2 ->>> +>>> a +5.5 + +>>> a = 11 +>>> a %= 2 # a = a % 2 +>>> a +1 + +>>> a = 11 +>>> a //= 2 # a = a // 2 +>>> a +5 + +a = 11 +>>> a **= 2 # a = a ^ 2 +>>> a +121 ``` This is not limited to integers. @@ -136,6 +165,17 @@ This is not limited to integers. >>> ``` +But, you can only use `+=` and `*=`. Because of with the others operators +it causes a type error. + +```python +>>> a = 'hello' +>>> a -= 3 +TypeError: unsupported operand type(s) for -: 'str' and 'str' +>>> +``` + + Now we also understand why typing hello to the prompt didn't work in the beginning of this tutorial. But we can assign something to a variable called hello and then type hello: @@ -300,13 +340,6 @@ what you are doing. We'll learn more about it later. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](the-way-of-the-program.md) | [Next](using-functions.md) | [List of contents](../README.md#basics) diff --git a/basics/what-is-programming.md b/basics/what-is-programming.md index ce917a5..965f5da 100644 --- a/basics/what-is-programming.md +++ b/basics/what-is-programming.md @@ -157,13 +157,6 @@ if you don't understand the code. *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](../README.md) | [Next](installing-python.md) | [List of contents](../README.md#basics) diff --git a/basics/what-is-true.md b/basics/what-is-true.md index 495aea6..a7cd418 100644 --- a/basics/what-is-true.md +++ b/basics/what-is-true.md @@ -213,13 +213,6 @@ if value is None: ... # best *** -If you have trouble with this tutorial please [tell me about -it](../contact-me.md) and I'll make this tutorial better. If you -like this tutorial, please [give it a -star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial). - -You may use this tutorial freely at your own risk. See -[LICENSE](../LICENSE). [Previous](larger-program.md) | [Next](files.md) | [List of contents](../README.md#basics)