├── .gitignore ├── README.md ├── chapter_01 └── hello_world.py ├── chapter_02 ├── eight.py ├── famous_quote.py ├── famous_quote2.py ├── favourite_number.py ├── name_case.py ├── personal_message.py ├── simple_message.py ├── simple_messages.py └── stripping_names.py ├── chapter_03 ├── changing_guest_list.py ├── dinner_guests.py ├── every_funtion.py ├── greetings.py ├── guest_list.py ├── more_guests.py ├── names.py ├── own_list.py ├── seeing_the_world.py └── shrinking_guest_list.py ├── chapter_04 ├── animals.py ├── buffet.py ├── counting_million.py ├── counting_twenty.py ├── cube_comprehension.py ├── cubes.py ├── many_pizzas.py ├── more_loops.py ├── multiple_three.py ├── odd_numbers.py ├── pizza.py ├── slices.py └── sum_million.py ├── chapter_05 ├── alien_colour.py ├── alien_colour2.py ├── alien_colour3.py ├── conditional_tests.py ├── fruits.py ├── greeting.py ├── ordinals.py ├── stages_of_life.py └── valid_username.py ├── chapter_06 ├── cities.py ├── favorite_number.py ├── glossary.py ├── people.py ├── person.py ├── pets.py ├── places.py ├── polling.py └── rivers.py ├── chapter_07 ├── deli.py ├── infinity.py ├── multiple.py ├── pastrami.py ├── pizza.py ├── rental.py ├── restaurant.py ├── tickets.py └── vacation.py ├── chapter_08 ├── album.py ├── car.py ├── cars.py ├── cities.py ├── favourite_book.py ├── great.py ├── imports.py ├── magicians.py ├── message.py ├── sandwiches.py ├── shirt.py ├── user_album.py └── user_profile.py ├── chapter_09 ├── admin.py ├── admin_module.py ├── battery_upgrade.py ├── dice.py ├── ice_cream.py ├── login.py ├── mult_module.py ├── ordered.py ├── privilege_module.py ├── restaurant.py ├── restaurant_module.py ├── served.py ├── user.py └── user_module.py ├── chapter_10 ├── addititon.py ├── cat_dog.py ├── common.py ├── fav_number.py ├── guest.py ├── guest_book.py ├── learning.py ├── learning_language.py ├── pets │ └── dog.txt ├── poll.py └── text │ ├── cat.txt │ ├── fav_num.json │ ├── frankenstein.txt │ ├── guest.txt │ ├── guest_book.txt │ └── learning_python.txt ├── chapter_11 ├── city_country.py ├── employee.py ├── test_city_country.py └── test_employee.py ├── chapter_18 ├── meal_planner │ ├── Pipfile │ ├── Pipfile.lock │ ├── manage.py │ ├── meal_planner │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ └── meal_plans │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── models.py │ │ ├── templates │ │ └── meal_plans │ │ │ └── index.html │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py └── pizzeria │ ├── Pipfile │ ├── Pipfile.lock │ ├── manage.py │ ├── pizzas │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── templates │ │ └── pizzas │ │ │ ├── base.html │ │ │ ├── index.html │ │ │ ├── pizza_id.html │ │ │ └── pizzas.html │ ├── tests.py │ ├── urls.py │ └── views.py │ └── pizzeria │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── learning_log ├── Pipfile ├── Pipfile.lock ├── learning_log ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py ├── learning_logs ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_entry.py │ └── __init__.py ├── models.py ├── templates │ └── learning_logs │ │ ├── base.html │ │ ├── edit_entry.html │ │ ├── index.html │ │ ├── new_entry.html │ │ ├── new_topic.html │ │ ├── topic.html │ │ └── topics.html ├── tests.py ├── urls.py └── views.py └── manage.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # .idea 7 | .idea/ 8 | 9 | # C extensions 10 | *.so 11 | 12 | migrations 13 | 14 | # Distribution / packaging 15 | .Python 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # pyenv 81 | .python-version 82 | 83 | # celery beat schedule file 84 | celerybeat-schedule 85 | 86 | # SageMath parsed files 87 | *.sage.py 88 | 89 | # Environments 90 | .env 91 | .venv 92 | env/ 93 | venv/ 94 | ENV/ 95 | env.bak/ 96 | venv.bak/ 97 | 98 | # Spyder project settings 99 | .spyderproject 100 | .spyproject 101 | 102 | # Rope project settings 103 | .ropeproject 104 | 105 | # mkdocs documentation 106 | /site 107 | 108 | # mypy 109 | .mypy_cache/ 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Crash Course 2 | 3 | This project contains my solutions for the problems in the book. 4 | Note that I am not following the tasks 1:1 so the end result might look different than 5 | intended. 6 | I may also use concepts which are introduced later in the book. 7 | -------------------------------------------------------------------------------- /chapter_01/hello_world.py: -------------------------------------------------------------------------------- 1 | print("Hello Python world!") -------------------------------------------------------------------------------- /chapter_02/eight.py: -------------------------------------------------------------------------------- 1 | import math 2 | print(-12987591743205843270582345+12987591743205843270582353) 3 | print(123487321487120487032184-123487321487120487032176) 4 | #round() rounds error down to 8 5 | print(round(2.3166627555607697e-08*345324324,0)) 6 | #math.pi being used to represent the constant pi=3.1415... 7 | print(25.132741228718345/math.pi) -------------------------------------------------------------------------------- /chapter_02/famous_quote.py: -------------------------------------------------------------------------------- 1 | quote = '''\ 2 | Ford Prefect once said:" The Guide says there is an 3 | art to flying or rather a knack. The knack lies in 4 | learning how to throw yourself at the ground and miss."''' 5 | 6 | print(quote) 7 | 8 | -------------------------------------------------------------------------------- /chapter_02/famous_quote2.py: -------------------------------------------------------------------------------- 1 | famous_device = "The guide" 2 | print(famous_device + ' once said: "Don\'t panic"') -------------------------------------------------------------------------------- /chapter_02/favourite_number.py: -------------------------------------------------------------------------------- 1 | favourite_number = 7 2 | #uses String concatenation and casting to print string 3 | print("My favourite number is: " +str(favourite_number)) -------------------------------------------------------------------------------- /chapter_02/name_case.py: -------------------------------------------------------------------------------- 1 | name = "brian" 2 | print(name.lower()) 3 | print(name.upper()) 4 | print(name.title()) -------------------------------------------------------------------------------- /chapter_02/personal_message.py: -------------------------------------------------------------------------------- 1 | print("What is your name?") 2 | name = "Arthur" 3 | print("It is " + name + " King of the Britons!") 4 | -------------------------------------------------------------------------------- /chapter_02/simple_message.py: -------------------------------------------------------------------------------- 1 | message = "Nobody expects the Spanish Inquisition!" 2 | print(message) 3 | -------------------------------------------------------------------------------- /chapter_02/simple_messages.py: -------------------------------------------------------------------------------- 1 | message = "Black Knight: Tis but a scratch." 2 | print(message) 3 | 4 | message = "King Arthur: A scratch? Your arm's off!" 5 | print(message) 6 | -------------------------------------------------------------------------------- /chapter_02/stripping_names.py: -------------------------------------------------------------------------------- 1 | name = "\t Arthur Dent \n" 2 | print(name.lstrip()) 3 | print(name.rstrip()) 4 | print(name.strip()) -------------------------------------------------------------------------------- /chapter_03/changing_guest_list.py: -------------------------------------------------------------------------------- 1 | def print_invitation(guest_list): 2 | for guest in guest_list: 3 | print("Hello " +guest+ ". I would like to invite you to dinner.") 4 | 5 | guest_list = ['Artistotle','Sartre','Epictetus'] 6 | print_invitation(guest_list) 7 | print("Oh no! Epictetus was enslaved by the Epaphroditus. He can't come to diner!") 8 | guest_list.remove('Epictetus') 9 | guest_list.append('Senecea') 10 | print_invitation(guest_list) 11 | 12 | #Alternate/ "simpler" version 13 | #print("Hello " + guest_list[0] +". I would like to invite you to dinner.") 14 | #print("Hello " + guest_list[1] +". I would like to invite you to dinner.") 15 | #print("Hello " + guest_list[2] +". I would like to invite you to dinner.") 16 | #print("Oh no! Epictetus was enslaved by the Epaphroditus. He can't come to diner!") 17 | #guest_list[2] = 'Seneca' 18 | #print("Hello " + guest_list[0] +". I would like to invite you to dinner.") 19 | #print("Hello " + guest_list[1] +". I would like to invite you to dinner.") 20 | #print("Hello " + guest_list[2] +". I would like to invite you to dinner.") -------------------------------------------------------------------------------- /chapter_03/dinner_guests.py: -------------------------------------------------------------------------------- 1 | def p(guest): 2 | print("Hello " +guest+ ". I would like to invite you to dinner.") 3 | def sorry(guest): 4 | print("Sorry "+guest+ ". Sadly you can't come since we won't have enough room for all of you.") 5 | 6 | guest_list = ['Aristotle','Sartre','Epictetus'] 7 | list(map(p,guest_list)) 8 | print(len(guest_list)) 9 | print("Oh no! Epictetus was enslaved by the Epaphroditus. He can't come to diner!") 10 | guest_list.remove('Epictetus') 11 | guest_list.append('Senecea') 12 | list(map(p,guest_list)) 13 | print(len(guest_list)) 14 | print("Ordered a bigger table! More guests!") 15 | guest_list.insert(0,'Kant') 16 | guest_list.insert(2,'Gautama') 17 | guest_list.append('Confucius') 18 | list(map(p,guest_list)) 19 | print(len(guest_list)) 20 | print("Oh no! The table won't arrive in time!") 21 | white_list = ['Aristotle','Confucius'] 22 | 23 | #Side effects and parenthesis almost as bad as in lisp... 24 | print(len(list(map(p,filter(lambda guest: guest in white_list,guest_list))))) 25 | print(len(list(map(sorry,filter(lambda guest: guest not in white_list,guest_list))))) 26 | print(guest_list.clear()) 27 | #Does the same thing just with list comprehension 28 | #list(map(p,[guest for guest in guest_list if guest in white_list])) 29 | #list(map(p,[guest for guest in guest_list if guest not in white_list])) -------------------------------------------------------------------------------- /chapter_03/every_funtion.py: -------------------------------------------------------------------------------- 1 | nice_traits = """adaptable 2 | adventurous 3 | affable 4 | affectionate 5 | agreeable 6 | ambitious 7 | amiable 8 | amicable 9 | amusing 10 | brave 11 | bright 12 | broad-minded 13 | calm 14 | careful 15 | charming 16 | communicative 17 | compassionate 18 | conscientious 19 | considerate 20 | convivial 21 | courageous 22 | courteous 23 | creative 24 | decisive 25 | determined 26 | diligent 27 | diplomatic 28 | discreet 29 | dynamic 30 | easygoing 31 | emotional 32 | energetic 33 | enthusiastic 34 | exuberant 35 | fair-minded 36 | faithful 37 | fearless 38 | forceful 39 | frank 40 | friendly 41 | funny 42 | generous 43 | gentle 44 | good 45 | gregarious 46 | hard-working 47 | helpful 48 | honest 49 | humorous 50 | imaginative 51 | impartial 52 | independent 53 | intellectual 54 | intelligent 55 | intuitive 56 | inventive 57 | kind 58 | loving 59 | loyal 60 | modest 61 | neat 62 | nice 63 | optimistic 64 | passionate 65 | patient 66 | persistent 67 | pioneering 68 | philosophical 69 | placid 70 | plucky 71 | polite 72 | powerful 73 | practical 74 | pro-active 75 | quick-witted 76 | quiet 77 | rational 78 | reliable 79 | reserved 80 | resourceful 81 | romantic 82 | self-confident 83 | self-disciplined 84 | sensible 85 | sensitive 86 | shy 87 | sincere 88 | sociable 89 | straightforward 90 | sympathetic 91 | thoughtful 92 | tidy 93 | tough 94 | unassuming 95 | understanding 96 | versatile 97 | warmhearted 98 | willing 99 | witty""".split() 100 | sorted(nice_traits,reverse = True) 101 | nice_traits.remove("tidy") 102 | nice_traits.append("tidy") 103 | nice_traits.sort() 104 | trait = nice_traits.pop() 105 | nice_traits.append(trait) 106 | len(nice_traits) 107 | trait = nice_traits[42] 108 | nice_traits.remove(trait) 109 | nice_traits.insert(42,trait) 110 | del nice_traits[:] 111 | print(nice_traits) -------------------------------------------------------------------------------- /chapter_03/greetings.py: -------------------------------------------------------------------------------- 1 | #This solution takes concepts, which are introduced later in the book and uses them. 2 | #For a solution for an exercise similiar to this, look at own_list.py 3 | friends = """Coral Alfaro 4 | Phillip Ryan 5 | Alfred Odling 6 | Cohan Gardner 7 | Bradley Fisher 8 | Jenny Marshall 9 | Meredith Connolly 10 | Cassia Simons 11 | Maegan Terrell 12 | Fox Branch 13 | Nichola Hale 14 | Saskia Allison 15 | Calista Brennan 16 | Petra Naylor 17 | Anita Lane 18 | Patrik Guy 19 | Lillia Salgado 20 | Hadiya Mcbride 21 | Ashton Mcdonnell 22 | Rex Chambers 23 | Sama Rios 24 | Jarrad Sweet 25 | Jokubas Davenport 26 | Kathy Cooke 27 | Alison Duke 28 | Aneesa Garner 29 | Dalia Bartlett 30 | Yisroel Griffiths 31 | Yara Redfern 32 | Wiktoria Kearney 33 | Alex Cooley 34 | Sylvie Todd 35 | Eren Moon 36 | Aya Pitt 37 | Lynda Banks 38 | Lola Lucas 39 | Eve Shah 40 | """.split() 41 | for i in range(int(len(friends)/2)): 42 | print("Hello " + friends[2*i] + " " + friends[2*i+1]+ "! How are you?") -------------------------------------------------------------------------------- /chapter_03/guest_list.py: -------------------------------------------------------------------------------- 1 | guest_list = ['Artistotle','Sartre','Epictetus'] 2 | for guest in guest_list: 3 | print("Hello " +guest+ ". I would like to invite you to dinner.") 4 | 5 | #Alternate/ "simpler" version 6 | #print("Hello " + guest_list[0] +". I would like to invite you to dinner.") 7 | #print("Hello " + guest_list[1] +". I would like to invite you to dinner.") 8 | #print("Hello " + guest_list[2] +". I would like to invite you to dinner.") -------------------------------------------------------------------------------- /chapter_03/more_guests.py: -------------------------------------------------------------------------------- 1 | def print_invitation(guest_list): 2 | for guest in guest_list: 3 | print("Hello " +guest+ ". I would like to invite you to dinner.") 4 | 5 | guest_list = ['Artistotle','Sartre','Epictetus'] 6 | print_invitation(guest_list) 7 | print("Oh no! Epictetus was enslaved by the Epaphroditus. He can't come to diner!") 8 | guest_list.remove('Epictetus') 9 | guest_list.append('Senecea') 10 | print_invitation(guest_list) 11 | print("Found a bigger table! More guests!") 12 | guest_list.insert(0,'Kant') 13 | guest_list.insert(2,'Gautama') 14 | guest_list.append('Confucius') 15 | print_invitation(guest_list) 16 | 17 | #Alternate/ "simpler" version 18 | # Same as in previous changing_guest_list.py, but with more print statements -------------------------------------------------------------------------------- /chapter_03/names.py: -------------------------------------------------------------------------------- 1 | #This solution takes concepts, which are introduced later in the book and uses them. 2 | #For a solution for an exercise similiar to this, look at own_list.py 3 | friends = """Coral Alfaro 4 | Phillip Ryan 5 | Alfred Odling 6 | Cohan Gardner 7 | Bradley Fisher 8 | Jenny Marshall 9 | Meredith Connolly 10 | Cassia Simons 11 | Maegan Terrell 12 | Fox Branch 13 | Nichola Hale 14 | Saskia Allison 15 | Calista Brennan 16 | Petra Naylor 17 | Anita Lane 18 | Patrik Guy 19 | Lillia Salgado 20 | Hadiya Mcbride 21 | Ashton Mcdonnell 22 | Rex Chambers 23 | Sama Rios 24 | Jarrad Sweet 25 | Jokubas Davenport 26 | Kathy Cooke 27 | Alison Duke 28 | Aneesa Garner 29 | Dalia Bartlett 30 | Yisroel Griffiths 31 | Yara Redfern 32 | Wiktoria Kearney 33 | Alex Cooley 34 | Sylvie Todd 35 | Eren Moon 36 | Aya Pitt 37 | Lynda Banks 38 | Lola Lucas 39 | Eve Shah 40 | """.split() 41 | for i in range(int(len(friends)/2)): 42 | print(friends[2*i] +" "+ friends[2*i+1]) -------------------------------------------------------------------------------- /chapter_03/own_list.py: -------------------------------------------------------------------------------- 1 | transportation = ['car','train','bike'] 2 | print("If it's hot and sunny, I like to ride the " + transportation[2] +".") 3 | print("If I need to transport something heavy and big I use the" + transportation[0]+".") 4 | print("Using the " +transportation[1]+ " instead of the " +transportation[0] + " saves the environment.") -------------------------------------------------------------------------------- /chapter_03/seeing_the_world.py: -------------------------------------------------------------------------------- 1 | nice_places = ["NYC","Seattle","London","Berlin","Rome","Shanghai"] 2 | print(nice_places) 3 | print(sorted(nice_places)) 4 | print(nice_places) 5 | print(sorted(nice_places,reverse=True)) 6 | print(nice_places) 7 | nice_places.reverse() 8 | print(nice_places) 9 | nice_places.reverse() 10 | print(nice_places) 11 | nice_places.sort() 12 | print(nice_places) 13 | nice_places.sort(reverse=True) 14 | print(nice_places) -------------------------------------------------------------------------------- /chapter_03/shrinking_guest_list.py: -------------------------------------------------------------------------------- 1 | def p(guest): 2 | print("Hello " +guest+ ". I would like to invite you to dinner.") 3 | def sorry(guest): 4 | print("Sorry "+guest+ ". Sadly you can't come since we won't have enough room for all of you.") 5 | 6 | guest_list = ['Aristotle','Sartre','Epictetus'] 7 | list(map(p,guest_list)) 8 | print("Oh no! Epictetus was enslaved by the Epaphroditus. He can't come to diner!") 9 | guest_list.remove('Epictetus') 10 | guest_list.append('Senecea') 11 | list(map(p,guest_list)) 12 | print("Ordered a bigger table! More guests!") 13 | guest_list.insert(0,'Kant') 14 | guest_list.insert(2,'Gautama') 15 | guest_list.append('Confucius') 16 | list(map(p,guest_list)) 17 | print("Oh no! The table won't arrive in time!") 18 | white_list = ['Aristotle','Confucius'] 19 | 20 | list(map(p,filter(lambda guest: guest in white_list,guest_list))) 21 | list(map(sorry,filter(lambda guest: guest not in white_list,guest_list))) 22 | print(guest_list.clear()) 23 | #Does the same thing just with list comprehension 24 | #list(map(p,[guest for guest in guest_list if guest in white_list])) 25 | #list(map(p,[guest for guest in guest_list if guest not in white_list])) -------------------------------------------------------------------------------- /chapter_04/animals.py: -------------------------------------------------------------------------------- 1 | animals = ['termites','bees','ants'] 2 | for animal in animals: 3 | print(animal + " build nests.") 4 | print("Don't mess with those!") 5 | -------------------------------------------------------------------------------- /chapter_04/buffet.py: -------------------------------------------------------------------------------- 1 | food = ('potatoe salad','noodles','turkey','caesar salad','pork') 2 | for f in food: 3 | print(f) 4 | food = ('potatoe salad','soup','lasagna','caesar salad','pork') 5 | for f in food: 6 | print(f) 7 | -------------------------------------------------------------------------------- /chapter_04/counting_million.py: -------------------------------------------------------------------------------- 1 | numbers = [i for i in range(1,1000001)] 2 | for x in numbers: 3 | print(x) -------------------------------------------------------------------------------- /chapter_04/counting_twenty.py: -------------------------------------------------------------------------------- 1 | numbers = [i for i in range(1,21)] 2 | for number in numbers: 3 | print(number) 4 | -------------------------------------------------------------------------------- /chapter_04/cube_comprehension.py: -------------------------------------------------------------------------------- 1 | [i*i*i for i in range(1,11)] 2 | -------------------------------------------------------------------------------- /chapter_04/cubes.py: -------------------------------------------------------------------------------- 1 | cubes = list(map(lambda x: x*x*x,list(range(1,11)))) 2 | for cube in cubes: 3 | print(cube) 4 | -------------------------------------------------------------------------------- /chapter_04/many_pizzas.py: -------------------------------------------------------------------------------- 1 | pizzas = ['salami','peperoni','pineapple'] 2 | other_pizzas = pizzas[:] 3 | other_pizzas.append('tuna') 4 | print("My favourite pizzas are:") 5 | list(map(print,pizzas)) 6 | print("My friends favourite pizzas are:") 7 | list(map(print,other_pizzas)) 8 | -------------------------------------------------------------------------------- /chapter_04/more_loops.py: -------------------------------------------------------------------------------- 1 | my_foods = ['pizza', 'falafel', 'carrot cake'] 2 | friend_foods = my_foods[:] 3 | friend_foods.append('beef') 4 | print("My favorite foods are:") 5 | list(map(print,my_foods)) 6 | print("\nMy friend's favorite foods are:") 7 | list(map(print,friend_foods)) 8 | -------------------------------------------------------------------------------- /chapter_04/multiple_three.py: -------------------------------------------------------------------------------- 1 | mulitple_three = [i*3 for i in range(1,11)] 2 | for number in mulitple_three: 3 | print(number) 4 | -------------------------------------------------------------------------------- /chapter_04/odd_numbers.py: -------------------------------------------------------------------------------- 1 | numbers = list(filter(lambda x: x % 2 ==1,list(range(1,21)))) 2 | #numbers = list(range(1,21,2)) 3 | for number in numbers: 4 | print(number) -------------------------------------------------------------------------------- /chapter_04/pizza.py: -------------------------------------------------------------------------------- 1 | pizzas = ['salami','peperoni','pineapple'] 2 | for pizza in pizzas: 3 | print(pizza) -------------------------------------------------------------------------------- /chapter_04/slices.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | numbers = [randint(0,9) for i in range(99)] 4 | print(numbers) 5 | print("First three items are " + str(numbers[:3])) 6 | print("Middle three items are" + str(numbers[49:52])) 7 | print("Last three items are" + str(numbers[-3:])) 8 | -------------------------------------------------------------------------------- /chapter_04/sum_million.py: -------------------------------------------------------------------------------- 1 | numbers = [i for i in range(1,1000001)] 2 | print(min(numbers)) 3 | print(max(numbers)) 4 | print(sum(numbers)) 5 | -------------------------------------------------------------------------------- /chapter_05/alien_colour.py: -------------------------------------------------------------------------------- 1 | def is_green(alien_colour): 2 | return alien_colour == 'green' 3 | 4 | alien_colour = 'yellow' 5 | print(is_green(alien_colour)) 6 | alien_colour = 'green' 7 | print(is_green(alien_colour)) 8 | -------------------------------------------------------------------------------- /chapter_05/alien_colour2.py: -------------------------------------------------------------------------------- 1 | def points(alien_colour): 2 | return 5 if alien_colour == 'green' else 10 3 | print(points('green')) 4 | print(points('yellow')) 5 | -------------------------------------------------------------------------------- /chapter_05/alien_colour3.py: -------------------------------------------------------------------------------- 1 | def points(alien_colour): 2 | if(alien_colour == 'green'): 3 | return 5 4 | elif(alien_colour == 'yellow'): 5 | return 10 6 | elif(alien_colour == 'red'): 7 | return 15 8 | else: 9 | return 0 10 | 11 | print(points('green')) 12 | print(points('yellow')) 13 | print(points('red')) 14 | print(points('')) 15 | -------------------------------------------------------------------------------- /chapter_05/conditional_tests.py: -------------------------------------------------------------------------------- 1 | #Only two tests 2 | flower = 'rose' 3 | print("Is flower == 'rose'? I say true") 4 | print(flower== 'rose') 5 | 6 | print("Is flower.upper() == 'rose'? I say false") 7 | print(flower.upper() == 'rose') 8 | 9 | -------------------------------------------------------------------------------- /chapter_05/fruits.py: -------------------------------------------------------------------------------- 1 | fruits = ['apple','orange','banana','pineapple','kiwi','pomegranate', 2 | 'grapes','pears','strawberry','watermelon','lemon','mango','papaya','maracuja', 3 | 'durian','pitaya','fig'] 4 | 5 | def is_inside(object,list): 6 | if object in list: 7 | print("Yes "+object+ " is in fruits") 8 | else: 9 | print("No " + object + " is not in fruits") 10 | 11 | is_inside('tomatoe',fruits) 12 | is_inside('apple',fruits) -------------------------------------------------------------------------------- /chapter_05/greeting.py: -------------------------------------------------------------------------------- 1 | def greet_user(username): 2 | if username is 'admin': 3 | print("Hello Admin! You're now operating with special rights") 4 | else: 5 | print("Hello " + username.title() + "! How are you doing today ?") 6 | 7 | def greeting(usernames): 8 | if usernames: 9 | for username in usernames: 10 | greet_user(username) 11 | 12 | usernames = ['admin','john','black knight'] 13 | greeting(usernames) 14 | 15 | -------------------------------------------------------------------------------- /chapter_05/ordinals.py: -------------------------------------------------------------------------------- 1 | ordinals = [i for i in range(1,10)] 2 | for ordinal in ordinals: 3 | if ordinal == 1: 4 | print("1st") 5 | elif ordinal == 2: 6 | print("2nd") 7 | elif ordinal == 3: 8 | print("3rd") 9 | else: 10 | print(str(ordinal)+"th") -------------------------------------------------------------------------------- /chapter_05/stages_of_life.py: -------------------------------------------------------------------------------- 1 | def life_stage(age): 2 | if(age<2): 3 | print("You're a baby.") 4 | elif(age>= 2 and age < 4): 5 | print("You're a toddler.") 6 | elif(age>= 4 and age < 13): 7 | print("You're a kid, kid.") 8 | elif(age>= 13 and age < 20): 9 | print("You're a teenager.") 10 | elif(age>= 20 and age < 65): 11 | print("You're an adult.") 12 | else: 13 | print("You're an elder.") 14 | 15 | [life_stage(i) for i in range(100)] 16 | -------------------------------------------------------------------------------- /chapter_05/valid_username.py: -------------------------------------------------------------------------------- 1 | users = ['John','Saskia','Georg','Melinda','Kent'] 2 | other_users = ['JOHN','Evelyn','oscar','melinda','Dustin'] 3 | 4 | def check_name(new_user,users_lower): 5 | if new_user.lower() not in users_lower: 6 | print("Welcome to our website!") 7 | users.append(new_user) 8 | else: 9 | print("Sorry " + new_user +" is already taken.") 10 | 11 | def check_names(): 12 | users_lower = [user.lower() for user in users] 13 | list(map(lambda x :check_name(x,users_lower),other_users)) 14 | 15 | check_names() 16 | 17 | 18 | -------------------------------------------------------------------------------- /chapter_06/cities.py: -------------------------------------------------------------------------------- 1 | chongqing = {'name':'chongqing', 2 | 'country' : 'china', 3 | 'population':30751600, 4 | 'fact':''' 5 | The only municipality under direct controll of the government 6 | but not on the east cost of China.''' 7 | } 8 | 9 | lagos = {'name':'lagos', 10 | 'country' : 'nigeria', 11 | 'population':16060303, 12 | 'fact':''' 13 | The average temperature is 26.3°C throughout the year. 14 | ''' 15 | } 16 | dhaka = {'name':'dhaka', 17 | 'country' : 'bangladesh', 18 | 'population':14399000, 19 | 'fact':'''Exists since the first millenium. 20 | ''' 21 | } 22 | cities = [chongqing,lagos,dhaka] 23 | for city in cities: 24 | print("Name: " + city['name']) 25 | print("Country: " + city['country']) 26 | print("Population: " + str(city['population'])) 27 | print("Random Fact: " + city['fact']) -------------------------------------------------------------------------------- /chapter_06/favorite_number.py: -------------------------------------------------------------------------------- 1 | ''' Interestingly enough, although it is stated later in the book that the order 2 | of insertion is not maintained, because of the implementation of dicts in 3.6 using 3 | more compact hashtables, the order of insertion is being preserverd, although 4 | one should use ordereddict if order is necessary''' 5 | 6 | import math 7 | favorite_numbers = {'Alice' : [42], 8 | 'Bob' : [23], 9 | 'Charlie' : [math.pi], 10 | 'Dustin' : [3], 11 | 'Eliza' : [math.e] 12 | } 13 | for name, number in favorite_numbers.items(): 14 | print(name+"s favorite numbers are: ") 15 | for x in number: 16 | print(x) -------------------------------------------------------------------------------- /chapter_06/glossary.py: -------------------------------------------------------------------------------- 1 | #Only five words 2 | 3 | glossary = {'dict' : 'map', 'python' : 'interpreted programming language', 4 | 'print':'function that prints to stdout',"':'":'no {,} necessary!' 5 | ,'list':'data structure'} 6 | for word, meaning in glossary.items(): 7 | print("Word:",word,"Meaning:",meaning) 8 | -------------------------------------------------------------------------------- /chapter_06/people.py: -------------------------------------------------------------------------------- 1 | person_one = { 2 | 'first_name' : 'john', 3 | 'last_name' : 'smith', 4 | 'age':'33', 5 | 'city' : 'New Orleans'} 6 | person_two = { 7 | 'first_name' : 'Eileen', 8 | 'last_name' : 'Wade', 9 | 'age':'43', 10 | 'city' : 'Vancouver'} 11 | person_three = { 12 | 'first_name' : 'Aisling', 13 | 'last_name' : 'Bloom', 14 | 'age':'33', 15 | 'city' : 'Belfast'} 16 | persons = [person_one,person_two,person_three] 17 | for person in persons: 18 | print('Their name is ' + person['first_name'] +' ' + person['last_name']) 19 | print("They're " + person['age'] +" years old and lives in " + person['city']) 20 | 21 | -------------------------------------------------------------------------------- /chapter_06/person.py: -------------------------------------------------------------------------------- 1 | person_dict = {'first_name' : 'john', 'last_name' : 'smith', 'age':'33','city' : 'New Orleans',} 2 | print('His name is ' + person_dict['first_name'] +' ' + person_dict['last_name']) 3 | print("He's " + person_dict['age'] +" years old and lives in " + person_dict['city']) 4 | 5 | -------------------------------------------------------------------------------- /chapter_06/pets.py: -------------------------------------------------------------------------------- 1 | pet_one = { 2 | 'name': 'harold', 3 | 'species':'parrot', 4 | 'owner': 'margeret' 5 | } 6 | pet_two = { 7 | 'name': 'bob', 8 | 'species':'dog', 9 | 'owner': 'elizbeth' 10 | } 11 | pet_three = { 12 | 'name': 'mandorlo', 13 | 'species':'fish', 14 | 'owner': 'eric' 15 | } 16 | pets = [pet_one,pet_two,pet_three] 17 | for pet in pets: 18 | print("The name is " + pet['name'].title() + '.') 19 | print("It's a " + pet['species'].title() + '.') 20 | print("The owner is " + pet['owner'].title() + '.') 21 | -------------------------------------------------------------------------------- /chapter_06/places.py: -------------------------------------------------------------------------------- 1 | places_dict = { 2 | 'Franky': ['High Acre','Westerbeach','Raymead'], 3 | 'Marlyn': ['Lorfield','Mallowport','Faysnow'], 4 | 'Kaydon': ['Dorhall','Reddell','Linvale'] 5 | } 6 | for person, places in places_dict.items(): 7 | print(person+'s favourite places are:') 8 | for place in places: 9 | print(place) 10 | print() -------------------------------------------------------------------------------- /chapter_06/polling.py: -------------------------------------------------------------------------------- 1 | persons = ['jen','sarah','jordanna','charlize','thelma','edward'] 2 | favourite_languages = { 3 | 'jen':'python', 4 | 'sarah':'c', 5 | 'edward':'ruby', 6 | 'phil':'python'} 7 | 8 | for person in persons: 9 | print("Hello " + person.title() + "!") 10 | if person in favourite_languages.keys(): 11 | print("Thank you for taking the survey!") 12 | else: 13 | print("Hey how about this neat little survey here?") 14 | -------------------------------------------------------------------------------- /chapter_06/rivers.py: -------------------------------------------------------------------------------- 1 | rivers = {'Nile':'Egypt','Amazon':'Brazil','Yangtze':'China', 2 | 'Mississippi':'United States','Yenisei':'Russia','Huang He':'China'} 3 | 4 | for river,country in rivers.items(): 5 | print("The",river,"runs through",country) 6 | print() 7 | [print(river) for river in rivers.keys()] 8 | print() 9 | [print(country) for country in set(rivers.values())] 10 | 11 | -------------------------------------------------------------------------------- /chapter_07/deli.py: -------------------------------------------------------------------------------- 1 | unfinished_sandwiches = ['tuna sandwich', 'bacon sandwich', 'chicken sandwich'] 2 | finished = [] 3 | while unfinished_sandwiches: 4 | sandwich = unfinished_sandwiches.pop() 5 | print("I'm making a " + sandwich) 6 | finished.append(sandwich) 7 | print("Sandiwiches that have been made: ") 8 | for sandwich in finished: 9 | print(sandwich.title()) -------------------------------------------------------------------------------- /chapter_07/infinity.py: -------------------------------------------------------------------------------- 1 | while True: 2 | continue -------------------------------------------------------------------------------- /chapter_07/multiple.py: -------------------------------------------------------------------------------- 1 | #for multiple of ten, call with parameeter multiple = 10 2 | def multiple_of(to_check,multiple): 3 | return not (to_check % multiple) 4 | 5 | print(multiple_of(520,5)) -------------------------------------------------------------------------------- /chapter_07/pastrami.py: -------------------------------------------------------------------------------- 1 | unfinished_sandwiches = ['tuna sandwich', 'bacon sandwich', 'chicken sandwich'] 2 | for i in range(3): 3 | unfinished_sandwiches.append('pastrami sandwich') 4 | finished = [] 5 | print("Sorry the deli has run out of ingredients to make pastrami sandwiches") 6 | while 'pastrami sandwich' in unfinished_sandwiches: 7 | unfinished_sandwiches.remove('pastrami sandwich') 8 | while unfinished_sandwiches: 9 | sandwich = unfinished_sandwiches.pop() 10 | print("I'm making a " + sandwich) 11 | finished.append(sandwich) 12 | print("Sandiwiches that have been made: ") 13 | for sandwich in finished: 14 | print(sandwich.title()) -------------------------------------------------------------------------------- /chapter_07/pizza.py: -------------------------------------------------------------------------------- 1 | def print_pizza(toppings): 2 | if len(toppings) == 0: 3 | print("A pizza without any toppings it is!") 4 | return 5 | print("A pizza with: ") 6 | for topping in toppings: 7 | print(topping) 8 | 9 | def get_toppings(toppings,prompt): 10 | topping = input(prompt) 11 | if len(topping.strip()) == 0 or topping == 'quit': 12 | return False 13 | toppings.append(topping) 14 | return True 15 | 16 | def run(): 17 | prompt = "What topping do you want on your pizza?\n" 18 | prompt += "Type 'quit' if you have don't have anything to add: " 19 | toppings = [] 20 | valid_topping = True 21 | while valid_topping: 22 | valid_topping = get_toppings(toppings,prompt) 23 | print_pizza(toppings) 24 | 25 | run() -------------------------------------------------------------------------------- /chapter_07/rental.py: -------------------------------------------------------------------------------- 1 | car_type = input("What kind of car do you want?: ") 2 | print("Let me see if I can find a " + car_type + '.') 3 | -------------------------------------------------------------------------------- /chapter_07/restaurant.py: -------------------------------------------------------------------------------- 1 | seats_necessary = int(input("How many persons are you?: ")) 2 | if seats_necessary > 8: 3 | print("I'm sorry, you'll have to wait.") 4 | elif seats_necessary < 1: 5 | print("Sorry, you'll have to give me something that makes sense.") 6 | else: 7 | print("Yes, we have a table ready for you.") 8 | -------------------------------------------------------------------------------- /chapter_07/tickets.py: -------------------------------------------------------------------------------- 1 | def get_price(age): 2 | if age < 3: 3 | return 0 4 | if age < 12: 5 | return 10 6 | return 15 7 | 8 | def run(): 9 | while True: 10 | try: 11 | print(get_price(int(input("What's your age?: ")))) 12 | except: 13 | print("Mistakes were made") 14 | break 15 | 16 | def run_alt(): 17 | limit = 5 18 | counter = 0 19 | while counter < limit: 20 | age = input("What's your age? ") 21 | print("Your price is: " + str(get_price(int(age)))) 22 | run() -------------------------------------------------------------------------------- /chapter_07/vacation.py: -------------------------------------------------------------------------------- 1 | active = True 2 | vacations = {} 3 | while active: 4 | name = input("What's your name?: ") 5 | location = input("And where do you want to travel?: ") 6 | vacations[name] = location 7 | state = input("Do you want to continue?: yes or no ") 8 | if state == 'no': 9 | active = False 10 | for name, location in vacations.items(): 11 | print(name+ " wants to travel to " + location) -------------------------------------------------------------------------------- /chapter_08/album.py: -------------------------------------------------------------------------------- 1 | def make_album(artist_name,album_title,number_songs=''): 2 | album = {'artist': artist_name, 3 | 'title' : album_title 4 | } 5 | if number_songs: 6 | album['tracknumbers'] = number_songs 7 | return album 8 | 9 | print(make_album('Marvin Gaye',"What's going on")) 10 | print(make_album('Micheal Jackson',"Thriller")) 11 | print(make_album('Kraftwerk',"Autobahn")) 12 | print(make_album('The Velvet Underground & Nico','The Velvet Underground & Nico',number_songs=11)) -------------------------------------------------------------------------------- /chapter_08/car.py: -------------------------------------------------------------------------------- 1 | def build_car(manufacturer, model_name, **kwargs): 2 | car = {} 3 | car['manufacturer'] = manufacturer 4 | car['model_name'] = model_name 5 | for k,v in kwargs.items(): 6 | car[k] = v 7 | return car 8 | 9 | -------------------------------------------------------------------------------- /chapter_08/cars.py: -------------------------------------------------------------------------------- 1 | def build_car(manufacturer, model_name, **kwargs): 2 | car = {} 3 | car['manufacturer'] = manufacturer 4 | car['model_name'] = model_name 5 | for k,v in kwargs.items(): 6 | car[k] = v 7 | return car 8 | print(build_car('subaru','outback',color='blue', tow_package=True)) 9 | 10 | -------------------------------------------------------------------------------- /chapter_08/cities.py: -------------------------------------------------------------------------------- 1 | def city_country(name,country): 2 | return name.title() + ', '+ country.title() 3 | print(city_country('Singapore','Singapore')) 4 | print(city_country('Casblanca','Morocco')) 5 | print(city_country('Kolkata','India')) 6 | -------------------------------------------------------------------------------- /chapter_08/favourite_book.py: -------------------------------------------------------------------------------- 1 | def print_book(title): 2 | print("One of my favourite books is " + title) 3 | 4 | print_book("Catch 22") -------------------------------------------------------------------------------- /chapter_08/great.py: -------------------------------------------------------------------------------- 1 | def show_magicians(magicians): 2 | for magician in magicians: 3 | print(magician.title()) 4 | 5 | def make_great(magicians): 6 | new_list = [] 7 | for magician in magicians: 8 | new_list.append(magician.title() + " the Great") 9 | return new_list 10 | 11 | magicians = ['merlin','gandalf','voldemort'] 12 | new_list = make_great(magicians[:]) 13 | show_magicians(magicians) 14 | show_magicians(new_list) 15 | 16 | -------------------------------------------------------------------------------- /chapter_08/imports.py: -------------------------------------------------------------------------------- 1 | import car 2 | print(car.build_car('subaru','outback',color='blue', tow_package=True)) 3 | 4 | from car import build_car 5 | print(build_car('subaru','outback',color='blue', tow_package=True)) 6 | 7 | from car import build_car as bc 8 | print(bc('subaru','outback',color='blue', tow_package=True)) 9 | 10 | import car as c 11 | print(c.build_car('subaru','outback',color='blue', tow_package=True)) 12 | 13 | from car import * 14 | print(build_car('subaru','outback',color='blue', tow_package=True)) 15 | -------------------------------------------------------------------------------- /chapter_08/magicians.py: -------------------------------------------------------------------------------- 1 | def show_magicians(magicians): 2 | for magician in magicians: 3 | print(magician) 4 | magicians = ['merlin','gandalf','voldemort'] 5 | show_magicians(magicians) 6 | 7 | -------------------------------------------------------------------------------- /chapter_08/message.py: -------------------------------------------------------------------------------- 1 | def display_message(): 2 | print("In this chapter functions are introduced.") 3 | 4 | display_message() -------------------------------------------------------------------------------- /chapter_08/sandwiches.py: -------------------------------------------------------------------------------- 1 | def show_ingredients(*ingredients): 2 | print("Those are the ingredients you want on your sandwich:") 3 | for ing in ingredients: 4 | print(ing) 5 | show_ingredients('chicken') 6 | show_ingredients('tuna','mayo') 7 | show_ingredients('ham','tomato','lettuce') 8 | -------------------------------------------------------------------------------- /chapter_08/shirt.py: -------------------------------------------------------------------------------- 1 | def make_shirt(size='L',message='I love Python'): 2 | print("A shirt size", size) 3 | print("Message:",message) 4 | make_shirt('M') 5 | make_shirt('L') 6 | s = "Strange women lying in ponds distributing swords\n" 7 | s += "is no basis for a system of government!" 8 | make_shirt(message=s,size='L') -------------------------------------------------------------------------------- /chapter_08/user_album.py: -------------------------------------------------------------------------------- 1 | def make_album(artist_name,album_title,number_songs=''): 2 | album = {'artist': artist_name, 3 | 'title' : album_title 4 | } 5 | if number_songs: 6 | album['tracknumbers'] = number_songs 7 | return album 8 | 9 | active = True 10 | while active: 11 | artist = input("What is the name of the artist?: ") 12 | title = input("What is the name of the title?: ") 13 | print(make_album(artist, title)) 14 | further = input("Do you want to continue?: y n ") 15 | if further == 'n': 16 | active = False 17 | -------------------------------------------------------------------------------- /chapter_08/user_profile.py: -------------------------------------------------------------------------------- 1 | def build_profile(first, last, **user_info): 2 | profile = {} 3 | profile['first_name'] = first 4 | profile['last_name'] = last 5 | for key, value in user_info.items(): 6 | profile[key] = value 7 | return profile 8 | 9 | user_profile = build_profile('john','doe',age=33,occupation='programmer') 10 | print(user_profile) 11 | -------------------------------------------------------------------------------- /chapter_09/admin.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | 3 | def __init__(self, 4 | first_name, 5 | last_name, 6 | password = '', 7 | id = '', 8 | mail =''): 9 | self.first_name = first_name 10 | self.last_name = last_name 11 | self.password = password 12 | self.id = id 13 | self.mail = mail 14 | self.login_attempts = 0 15 | 16 | def describe_user(self): 17 | print("Name", 18 | self.first_name.title(), 19 | self.last_name.title()) 20 | def greet(self): 21 | print("Hello " + self.first_name.title() + " " + 22 | self.last_name.title() + 23 | "! How are you doing?") 24 | 25 | def increment_login_attempts(self,increment): 26 | new_value = self.login_attempts + increment 27 | old_value = self.login_attempts 28 | self.login_attempts = new_value if increment > 0 else old_value 29 | 30 | def reset_login_attempts(self): 31 | self.login_attempts = 0 32 | 33 | class Admin(User): 34 | 35 | def __init__(self,first_name,last_name,privileges): 36 | super().__init__(first_name,last_name) 37 | self.privileges = Privileges(privileges) 38 | 39 | def show_privileges(self): 40 | self.privileges.show_privileges() 41 | 42 | class Privileges(): 43 | 44 | def __init__(self,privileges): 45 | self.privileges = privileges 46 | 47 | def show_privileges(self): 48 | for privilege in self.privileges: 49 | print(privilege) 50 | 51 | privilege_list = ['can delete user','can suspend user','can alter user details'] 52 | admin = Admin('John','Doe',privilege_list) 53 | admin.show_privileges() -------------------------------------------------------------------------------- /chapter_09/admin_module.py: -------------------------------------------------------------------------------- 1 | from user_module import User 2 | from privilege_module import Privileges 3 | 4 | class Admin(User): 5 | 6 | def __init__(self,first_name,last_name,privileges): 7 | super().__init__(first_name,last_name) 8 | self.privileges = Privileges(privileges) 9 | 10 | def show_privileges(self): 11 | self.privileges.show_privileges() 12 | -------------------------------------------------------------------------------- /chapter_09/battery_upgrade.py: -------------------------------------------------------------------------------- 1 | class Car(): 2 | def __init__(self, make, model, year): 3 | self.make = make 4 | self.model = model 5 | self.year = year 6 | self.odometer_reading = 0 7 | def get_descriptive_name(self): 8 | long_name = str(self.year) + ' ' + self.make + ' ' + self.model 9 | return long_name.title() 10 | def read_odometer(self): 11 | print("This car has " + str(self.odometer_reading) + " miles on it.") 12 | def update_odometer(self, mileage): 13 | if mileage >= self.odometer_reading: 14 | self.odometer_reading = mileage 15 | else: 16 | print("You can't roll back an odometer!") 17 | def increment_odometer(self, miles): 18 | self.odometer_reading += miles 19 | 20 | class Battery(): 21 | 22 | def __init__(self): 23 | self.size = 70 24 | def upgrade(self,new): 25 | self.size = new 26 | def get_size(self): 27 | print(self.size) 28 | 29 | class Electric_Car(Car): 30 | 31 | def __init__(self,make,model,year): 32 | super().__init__(make,model,year) 33 | self.battery = Battery() 34 | 35 | def upgrade_battery(self,size): 36 | self.battery.upgrade(size) 37 | 38 | def get_size(self): 39 | self.battery.get_size() 40 | 41 | electric = Electric_Car('foo','bar',2019) 42 | 43 | electric.get_size() 44 | electric.upgrade_battery(100) 45 | electric.get_size() -------------------------------------------------------------------------------- /chapter_09/dice.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | #Currying! 4 | def dice_generator(n): 5 | def function(): 6 | return randint(1,n) 7 | return function 8 | 9 | 10 | def print_dice(d): 11 | for i in range(10): 12 | print(d()) 13 | 14 | sides = [6,10,20] 15 | dice = map(dice_generator,sides) 16 | 17 | for d in dice: 18 | print('---') 19 | print_dice(d) 20 | -------------------------------------------------------------------------------- /chapter_09/ice_cream.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | 3 | def __init__(self,restaurant_name,cuisine_type): 4 | self.restaurant_name = restaurant_name 5 | self.cuisine_type = cuisine_type 6 | 7 | def describe_restaurant(self): 8 | print("Name: ",self.restaurant_name) 9 | print("Type: ",self.cuisine_type) 10 | 11 | class Ice_Cream(Restaurant): 12 | 13 | def __init__(self,name,cuisine_type,flavours): 14 | super().__init__(name,cuisine_type) 15 | self.flavours = flavours 16 | 17 | def availabe_flavours(self): 18 | for flavour in self.flavours: 19 | print(flavour.title()) 20 | 21 | flavours = ['chocolate','vanilla'] 22 | ice = Ice_Cream('Ice Cream Corner', 'Ice cream', flavours) 23 | ice.availabe_flavours() 24 | 25 | 26 | -------------------------------------------------------------------------------- /chapter_09/login.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | 3 | def __init__(self, 4 | first_name, 5 | last_name, 6 | password = '', 7 | id = '', 8 | mail =''): 9 | self.first_name = first_name 10 | self.last_name = last_name 11 | self.password = password 12 | self.id = id 13 | self.mail = mail 14 | self.login_attempts = 0 15 | 16 | def describe_user(self): 17 | print("Name", 18 | self.first_name.title(), 19 | self.last_name.title()) 20 | def greet(self): 21 | print("Hello " + self.first_name.title() + " " + 22 | self.last_name.title() + 23 | "! How are you doing?") 24 | 25 | def increment_login_attempts(self,increment): 26 | new_value = self.login_attempts + increment 27 | old_value = self.login_attempts 28 | self.login_attempts = new_value if increment > 0 else old_value 29 | 30 | def reset_login_attempts(self): 31 | self.login_attempts = 0 32 | 33 | 34 | u = User("patrick","nieri") 35 | u.increment_login_attempts(5) 36 | print(u.login_attempts) 37 | u.reset_login_attempts() 38 | print(u.login_attempts) -------------------------------------------------------------------------------- /chapter_09/mult_module.py: -------------------------------------------------------------------------------- 1 | from admin_module import Admin 2 | 3 | admin = Admin('Foo','Bar',['add users']) 4 | admin.show_privileges() 5 | -------------------------------------------------------------------------------- /chapter_09/ordered.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | #Only five words 3 | 4 | glossary = [('dict' , 'map'),('python' , 'interpreted programming language'), 5 | ('print' , 'function that prints to stdout'),("':'" , 'no {,} necessary!') 6 | ,('list' , 'data structure')] 7 | order = OrderedDict(glossary) 8 | for word, meaning in order.items(): 9 | print("Word:",word,"Meaning:",meaning) 10 | -------------------------------------------------------------------------------- /chapter_09/privilege_module.py: -------------------------------------------------------------------------------- 1 | class Privileges(): 2 | 3 | def __init__(self,privileges): 4 | self.privileges = privileges 5 | 6 | def show_privileges(self): 7 | for privilege in self.privileges: 8 | print(privilege) -------------------------------------------------------------------------------- /chapter_09/restaurant.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | 3 | def __init__(self,restaurant_name,cuisine_type): 4 | self.restaurant_name = restaurant_name 5 | self.cuisine_type = cuisine_type 6 | self.open = False 7 | 8 | def describe_restaurant(self): 9 | print("Name: ",self.restaurant_name) 10 | print("Type: ",self.cuisine_type) 11 | 12 | def open_restaurant(self): 13 | self.open = True 14 | print("Restaurant is now open!") 15 | 16 | res1 = Restaurant("Happy Lotus","Chinese") 17 | res2 = Restaurant("Dancing Sombrero","Mexican") 18 | res3 = Restaurant("Feisty Pretzel","German") 19 | 20 | res1.describe_restaurant() 21 | res2.describe_restaurant() 22 | res3.describe_restaurant() 23 | -------------------------------------------------------------------------------- /chapter_09/restaurant_module.py: -------------------------------------------------------------------------------- 1 | from restaurant import Restaurant 2 | 3 | # prints the output from restaurant aswell 4 | restaurant = Restaurant('foo','bar') 5 | restaurant.describe_restaurant() 6 | -------------------------------------------------------------------------------- /chapter_09/served.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | 3 | def __init__(self,restaurant_name,cuisine_type): 4 | self.restaurant_name = restaurant_name 5 | self.cuisine_type = cuisine_type 6 | self.open = False 7 | self.number_served = 0 8 | 9 | def describe_restaurant(self): 10 | print("Name: ",self.restaurant_name) 11 | print("Type: ",self.cuisine_type) 12 | 13 | def is_open(self): 14 | return self.open 15 | 16 | def open_restaurant(self): 17 | self.open = True 18 | print("Restaurant is now open!") 19 | 20 | def set_number_served(self,number): 21 | if self.is_open() and number > 0: 22 | self.number_served = number 23 | else: 24 | print("Closed restaurant can't take customers") 25 | 26 | def increment_number_served(self,number): 27 | if number < 0: 28 | print("Incompatible Value") 29 | return 30 | else: 31 | self.set_number_served(number) 32 | 33 | restaurant = Restaurant("Happy Lotus","Chinese") 34 | print(restaurant.number_served) 35 | restaurant.number_served = 50 36 | print(restaurant.number_served) 37 | 38 | restaurant.number_served = 0 39 | restaurant.set_number_served(50) 40 | restaurant.open_restaurant() 41 | restaurant.set_number_served(50) 42 | print(restaurant.number_served) 43 | 44 | restaurant.number_served = 0 45 | restaurant.increment_number_served(50) 46 | print(restaurant.number_served) 47 | -------------------------------------------------------------------------------- /chapter_09/user.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | 3 | def __init__(self, 4 | first_name, 5 | last_name, 6 | password = '', 7 | id = '', 8 | mail =''): 9 | self.first_name = first_name 10 | self.last_name = last_name 11 | self.password = password 12 | self.id = id 13 | self.mail = mail 14 | 15 | def describe_user(self): 16 | print("Name", 17 | self.first_name.title(), 18 | self.last_name.title()) 19 | def greet(self): 20 | print("Hello " + self.first_name.title() + " " + 21 | self.last_name.title() + 22 | "! How are you doing?") 23 | 24 | users = [User("patrick","nieri"), 25 | User("rafael","hardy"), 26 | User("olga","schuyler")] 27 | 28 | for u in users: 29 | u.describe_user() 30 | u.greet() 31 | -------------------------------------------------------------------------------- /chapter_09/user_module.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | 3 | def __init__(self, 4 | first_name, 5 | last_name, 6 | password = '', 7 | id = '', 8 | mail =''): 9 | self.first_name = first_name 10 | self.last_name = last_name 11 | self.password = password 12 | self.id = id 13 | self.mail = mail 14 | self.login_attempts = 0 15 | 16 | def describe_user(self): 17 | print("Name", 18 | self.first_name.title(), 19 | self.last_name.title()) 20 | def greet(self): 21 | print("Hello " + self.first_name.title() + " " + 22 | self.last_name.title() + 23 | "! How are you doing?") 24 | 25 | def increment_login_attempts(self,increment): 26 | new_value = self.login_attempts + increment 27 | old_value = self.login_attempts 28 | self.login_attempts = new_value if increment > 0 else old_value 29 | 30 | def reset_login_attempts(self): 31 | self.login_attempts = 0 32 | -------------------------------------------------------------------------------- /chapter_10/addititon.py: -------------------------------------------------------------------------------- 1 | print("Please enter two numbers") 2 | print("Add two zeros to quit") 3 | def add_two(): 4 | try: 5 | one = int(input()) 6 | two = int(input()) 7 | except ValueError: 8 | print("Sorry one of your numbers couldn't be read.") 9 | return True 10 | else: 11 | print(str(one + two)) 12 | if one == 0 and two == 0: 13 | return False 14 | return True 15 | 16 | while add_two(): 17 | continue 18 | -------------------------------------------------------------------------------- /chapter_10/cat_dog.py: -------------------------------------------------------------------------------- 1 | def read_files(f): 2 | try: 3 | with open(f) as file_object: 4 | lines = file_object.readlines() 5 | except FileNotFoundError: 6 | print(f,'not found') 7 | else: 8 | for l in lines: 9 | print(l.strip()) 10 | 11 | files = ['pets/dog.txt','cat.txt'] 12 | 13 | for f in files: 14 | read_files(f) -------------------------------------------------------------------------------- /chapter_10/common.py: -------------------------------------------------------------------------------- 1 | def count_occurences_file(f, to_count): 2 | try: 3 | with open(f) as file_object: 4 | lines = file_object.readlines() 5 | except FileNotFoundError: 6 | print("File not found") 7 | else: 8 | s ='' 9 | for l in lines: 10 | if l.isspace(): 11 | continue 12 | s += l.strip() 13 | 14 | return s.lower().count('the') 15 | 16 | file_name = 'text/frankenstein.txt' 17 | print(count_occurences_file(file_name,'the')) 18 | 19 | -------------------------------------------------------------------------------- /chapter_10/fav_number.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | file_name = 'text/fav_num.json' 4 | 5 | def get_fav_from_user(): 6 | return int(input("What's your favourite number?: ")) 7 | 8 | def save_fav_number(): 9 | n = get_fav_from_user() 10 | with open(file_name,'w') as file_object: 11 | json.dump(n,file_object) 12 | 13 | def get_fav_number(): 14 | try: 15 | with open(file_name) as file_object: 16 | return json.load(file_object) 17 | except FileNotFoundError: 18 | save_fav_number() 19 | return "Number saved" 20 | 21 | 22 | print(get_fav_number()) 23 | -------------------------------------------------------------------------------- /chapter_10/guest.py: -------------------------------------------------------------------------------- 1 | filename = 'text/guest.txt' 2 | 3 | name = input("What is your name?: ") 4 | with open(filename,'a') as file_object: 5 | file_object.write(name+'\n') 6 | -------------------------------------------------------------------------------- /chapter_10/guest_book.py: -------------------------------------------------------------------------------- 1 | filename = 'text/guest_book.txt' 2 | 3 | names = [] 4 | while True: 5 | print("What is your name?") 6 | user_input = input("Enter 'n' if you want to stop: ") 7 | if user_input == 'n': 8 | break 9 | names.append(user_input) 10 | 11 | with open(filename,'a') as file_object: 12 | for name in names: 13 | file_object.write(name+'\n') 14 | -------------------------------------------------------------------------------- /chapter_10/learning.py: -------------------------------------------------------------------------------- 1 | filename = 'text/learning_python.txt' 2 | 3 | with open(filename) as file_object: 4 | #print whole file 5 | contents = file_object.read().rstrip() 6 | print(contents) 7 | print('---') 8 | 9 | with open(filename) as file_object: 10 | #print file line by line 11 | for line in file_object: 12 | print(line.rstrip()) 13 | print('---') 14 | 15 | with open(filename) as file_object: 16 | lines = file_object.readlines() 17 | 18 | for line in lines: 19 | print(line.rstrip()) 20 | -------------------------------------------------------------------------------- /chapter_10/learning_language.py: -------------------------------------------------------------------------------- 1 | filename = 'text/learning_python.txt' 2 | 3 | with open(filename) as file_object: 4 | for line in file_object: 5 | print(line.replace('Python','Haskell').strip()) 6 | 7 | -------------------------------------------------------------------------------- /chapter_10/pets/dog.txt: -------------------------------------------------------------------------------- 1 | lola 2 | sadie 3 | max 4 | -------------------------------------------------------------------------------- /chapter_10/poll.py: -------------------------------------------------------------------------------- 1 | filename = 'poll.txt' 2 | 3 | reasons = [] 4 | 5 | print("To exit the poll press 'n'") 6 | while True: 7 | user_input = input("Why do you like programming?: ") 8 | if user_input == 'n': 9 | break 10 | reasons.append(user_input) 11 | 12 | with open(filename,'a') as file_object: 13 | for reason in reasons: 14 | file_object.write(reason+'\n') -------------------------------------------------------------------------------- /chapter_10/text/cat.txt: -------------------------------------------------------------------------------- 1 | bella 2 | charlie 3 | lucy 4 | -------------------------------------------------------------------------------- /chapter_10/text/fav_num.json: -------------------------------------------------------------------------------- 1 | 5 -------------------------------------------------------------------------------- /chapter_10/text/guest.txt: -------------------------------------------------------------------------------- 1 | John Doe 2 | Foo Bar 3 | -------------------------------------------------------------------------------- /chapter_10/text/guest_book.txt: -------------------------------------------------------------------------------- 1 | Foo Bar Buzz 2 | Buzz Bar Foo 3 | Bar Foo Buzz 4 | -------------------------------------------------------------------------------- /chapter_10/text/learning_python.txt: -------------------------------------------------------------------------------- 1 | In Python you can write functions without '{}'. 2 | In Python you can use functions as first class citizens. 3 | In Python you can write code without alot of boilerplatecode. 4 | In Python you can import modules and define yourself ones easily. 5 | -------------------------------------------------------------------------------- /chapter_11/city_country.py: -------------------------------------------------------------------------------- 1 | def format_city(city, country, population=0): 2 | formated = city +', ' +country 3 | if population: 4 | return formated + ' - population ' + str(population) 5 | return formated -------------------------------------------------------------------------------- /chapter_11/employee.py: -------------------------------------------------------------------------------- 1 | class Employee(): 2 | 3 | def __init__(self,first_name,last_name,annual_salary): 4 | self.first_name = first_name 5 | self.last_name = last_name 6 | self.annual_salary = annual_salary 7 | 8 | def give_raise(self,amount=5000): 9 | self.annual_salary += amount 10 | 11 | def get_salary(self): 12 | return self.annual_salary -------------------------------------------------------------------------------- /chapter_11/test_city_country.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from city_country import format_city as fc 3 | 4 | class CityCountryTest(unittest.TestCase): 5 | 6 | def test_correct_output_1(self): 7 | result = fc('New York','United States') 8 | self.assertEqual('New York, United States', result) 9 | 10 | def test_correct_output_2(self): 11 | result = fc('Sydney','Australia') 12 | self.assertEqual('Sydney, Australia', result) 13 | 14 | def test_correct_output_3(self): 15 | result = fc('Kinshasa','DR Congo') 16 | self.assertEqual('Kinshasa, DR Congo', result) 17 | 18 | def test_correct_output_population(self): 19 | result = fc('Nairobi','Kenia',int(4e6)) 20 | self.assertEqual('Nairobi, Kenia - population 4000000',result) 21 | 22 | def test_correct_output_population_2(self): 23 | result = fc('Moscow','Russia',12500000) 24 | self.assertEqual('Moscow, Russia - population 12500000',result) 25 | 26 | unittest.main() -------------------------------------------------------------------------------- /chapter_11/test_employee.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from employee import Employee as e 3 | 4 | class EmployeeTest(unittest.TestCase): 5 | 6 | def setUp(self): 7 | self.emp = e('Foo','Bar',50000) 8 | 9 | def test_increase_salary_default(self): 10 | self.assertEqual(50000,self.emp.get_salary()) 11 | self.emp.give_raise() 12 | self.assertEqual(55000,self.emp.get_salary()) 13 | 14 | def test_increase_salary_custom(self): 15 | self.assertEqual(50000,self.emp.get_salary()) 16 | self.emp.give_raise(10000) 17 | self.assertEqual(60000,self.emp.get_salary()) 18 | 19 | unittest.main() -------------------------------------------------------------------------------- /chapter_18/meal_planner/Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | name = "pypi" 3 | url = "https://pypi.org/simple" 4 | verify_ssl = true 5 | 6 | [dev-packages] 7 | 8 | [packages] 9 | django = "*" 10 | 11 | [requires] 12 | python_version = "3.7" 13 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/Pipfile.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_meta": { 3 | "hash": { 4 | "sha256": "627ef89f247ecee27e9ef0dabe116108d09c47abf171c900a8817befa64f9dd2" 5 | }, 6 | "pipfile-spec": 6, 7 | "requires": { 8 | "python_version": "3.7" 9 | }, 10 | "sources": [ 11 | { 12 | "name": "pypi", 13 | "url": "https://pypi.org/simple", 14 | "verify_ssl": true 15 | } 16 | ] 17 | }, 18 | "default": { 19 | "django": { 20 | "hashes": [ 21 | "sha256:1226168be1b1c7efd0e66ee79b0e0b58b2caa7ed87717909cd8a57bb13a7079a", 22 | "sha256:9a4635813e2d498a3c01b10c701fe4a515d76dd290aaa792ccb65ca4ccb6b038" 23 | ], 24 | "index": "pypi", 25 | "version": "==2.2.13" 26 | }, 27 | "pytz": { 28 | "hashes": [ 29 | "sha256:1c557d7d0e871de1f5ccd5833f60fb2550652da6be2693c1e02300743d21500d", 30 | "sha256:b02c06db6cf09c12dd25137e563b31700d3b80fcc4ad23abb7a315f2789819be" 31 | ], 32 | "version": "==2019.3" 33 | }, 34 | "sqlparse": { 35 | "hashes": [ 36 | "sha256:40afe6b8d4b1117e7dff5504d7a8ce07d9a1b15aeeade8a2d10f130a834f8177", 37 | "sha256:7c3dca29c022744e95b547e867cee89f4fce4373f3549ccd8797d8eb52cdb873" 38 | ], 39 | "version": "==0.3.0" 40 | } 41 | }, 42 | "develop": {} 43 | } 44 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'meal_planner.settings') 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_planner/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davrad/pythoncrashcourse/b73bf31e4237e4400ecc5ed59726fa760754bf1a/chapter_18/meal_planner/meal_planner/__init__.py -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_planner/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for meal_planner project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1.7. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '8jl7v2idgueeb7n@ssm+qxf!fe9)oix4+$uamep4e0!vytj83_' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 41 | 'meal_plans' 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'meal_planner.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [os.path.join(BASE_DIR, 'templates')] 60 | , 61 | 'APP_DIRS': True, 62 | 'OPTIONS': { 63 | 'context_processors': [ 64 | 'django.template.context_processors.debug', 65 | 'django.template.context_processors.request', 66 | 'django.contrib.auth.context_processors.auth', 67 | 'django.contrib.messages.context_processors.messages', 68 | ], 69 | }, 70 | }, 71 | ] 72 | 73 | WSGI_APPLICATION = 'meal_planner.wsgi.application' 74 | 75 | 76 | # Database 77 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 78 | 79 | DATABASES = { 80 | 'default': { 81 | 'ENGINE': 'django.db.backends.sqlite3', 82 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 83 | } 84 | } 85 | 86 | 87 | # Password validation 88 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 89 | 90 | AUTH_PASSWORD_VALIDATORS = [ 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 99 | }, 100 | { 101 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 102 | }, 103 | ] 104 | 105 | 106 | # Internationalization 107 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 108 | 109 | LANGUAGE_CODE = 'en-us' 110 | 111 | TIME_ZONE = 'UTC' 112 | 113 | USE_I18N = True 114 | 115 | USE_L10N = True 116 | 117 | USE_TZ = True 118 | 119 | 120 | # Static files (CSS, JavaScript, Images) 121 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 122 | 123 | STATIC_URL = '/static/' 124 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_planner/urls.py: -------------------------------------------------------------------------------- 1 | """meal_planner URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from django.conf.urls import url, include 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | url(r'', include('meal_plans.urls', namespace='meal_plans')) 23 | ] 24 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_planner/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for meal_planner project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'meal_planner.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_plans/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davrad/pythoncrashcourse/b73bf31e4237e4400ecc5ed59726fa760754bf1a/chapter_18/meal_planner/meal_plans/__init__.py -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_plans/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_plans/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class MealPlansConfig(AppConfig): 5 | name = 'meal_plans' 6 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_plans/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_plans/templates/meal_plans/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 |
9 |

10 | Meal Plans 11 |

12 |

13 | Design your meal plans here! 14 |

15 |
16 | 17 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_plans/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_plans/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import views 4 | 5 | app_name = 'meal_plans' 6 | 7 | urlpatterns = [ 8 | # Meal Plans 9 | url(r'^$', views.index, name='index'), 10 | ] 11 | -------------------------------------------------------------------------------- /chapter_18/meal_planner/meal_plans/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | 4 | def index(request): 5 | return render(request, 'meal_plans/index.html') 6 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | name = "pypi" 3 | url = "https://pypi.org/simple" 4 | verify_ssl = true 5 | 6 | [dev-packages] 7 | 8 | [packages] 9 | django = "*" 10 | 11 | [requires] 12 | python_version = "3.7" 13 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/Pipfile.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_meta": { 3 | "hash": { 4 | "sha256": "627ef89f247ecee27e9ef0dabe116108d09c47abf171c900a8817befa64f9dd2" 5 | }, 6 | "pipfile-spec": 6, 7 | "requires": { 8 | "python_version": "3.7" 9 | }, 10 | "sources": [ 11 | { 12 | "name": "pypi", 13 | "url": "https://pypi.org/simple", 14 | "verify_ssl": true 15 | } 16 | ] 17 | }, 18 | "default": { 19 | "django": { 20 | "hashes": [ 21 | "sha256:4d23f61b26892bac785f07401bc38cbf8fa4cec993f400e9cd9ddf28fd51c0ea", 22 | "sha256:6e974d4b57e3b29e4882b244d40171d6a75202ab8d2402b8e8adbd182e25cf0c" 23 | ], 24 | "index": "pypi", 25 | "version": "==2.2.3" 26 | }, 27 | "pytz": { 28 | "hashes": [ 29 | "sha256:303879e36b721603cc54604edcac9d20401bdbe31e1e4fdee5b9f98d5d31dfda", 30 | "sha256:d747dd3d23d77ef44c6a3526e274af6efeb0a6f1afd5a69ba4d5be4098c8e141" 31 | ], 32 | "version": "==2019.1" 33 | }, 34 | "sqlparse": { 35 | "hashes": [ 36 | "sha256:40afe6b8d4b1117e7dff5504d7a8ce07d9a1b15aeeade8a2d10f130a834f8177", 37 | "sha256:7c3dca29c022744e95b547e867cee89f4fce4373f3549ccd8797d8eb52cdb873" 38 | ], 39 | "version": "==0.3.0" 40 | } 41 | }, 42 | "develop": {} 43 | } 44 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pizzeria.settings') 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davrad/pythoncrashcourse/b73bf31e4237e4400ecc5ed59726fa760754bf1a/chapter_18/pizzeria/pizzas/__init__.py -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from pizzas.models import Pizza, Topping 4 | 5 | 6 | # Register your models here. 7 | admin.site.register(Pizza) 8 | admin.site.register(Topping) 9 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class PizzasConfig(AppConfig): 5 | name = 'pizzas' 6 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Topping(models.Model): 5 | 6 | name = models.CharField(max_length=200) 7 | 8 | def __str__(self): 9 | return self.name 10 | 11 | 12 | class Pizza(models.Model): 13 | 14 | name = models.CharField(max_length=200) 15 | toppings = models.ManyToManyField(Topping, blank=True) 16 | 17 | def __str__(self): 18 | return self.name 19 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/templates/pizzas/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 |

9 | HomePage 10 |

11 | 12 | {% block content %}{% endblock content %} 13 | 14 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/templates/pizzas/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | {% extends 'pizzas/base.html' %} 9 | 10 | {% block content %} 11 |

12 | It's pizza time!: 13 | Pizzas! 14 |

15 | {% endblock content %} 16 | 17 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/templates/pizzas/pizza_id.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | {% extends 'pizzas/base.html' %} 9 | {% block content %} 10 |

Toppings:

11 | 20 | {% endblock content %} 21 | 22 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/templates/pizzas/pizzas.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | {% extends 'pizzas/base.html' %} 9 | 10 | {% block content %} 11 |

Pizzas to we offer!

12 | 21 | {% endblock content %} 22 | 23 | 24 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import views 4 | 5 | app_name = 'pizzas' 6 | 7 | urlpatterns = [ 8 | url(r'^$', views.index, name='index'), 9 | url(r'^pizza/$', views.pizza, name='pizza'), 10 | url(r'^pizza/(?P\d+)/$', views.pizza_id, name='pizza_id'), 11 | ] 12 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzas/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | from .models import Pizza 4 | 5 | 6 | def index(request): 7 | return render(request, 'pizzas/index.html') 8 | 9 | 10 | def pizza(request): 11 | pizzas = Pizza.objects.all() 12 | context = {'pizzas': pizzas} 13 | return render(request, 'pizzas/pizzas.html', context) 14 | 15 | 16 | def pizza_id(request, pizza_id): 17 | pizza_db = Pizza.objects.get(id=pizza_id) 18 | toppings = pizza_db.toppings.all() 19 | context = {'pizza': pizza_db, 'toppings': toppings} 20 | return render(request, 'pizzas/pizza_id.html', context) 21 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzeria/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davrad/pythoncrashcourse/b73bf31e4237e4400ecc5ed59726fa760754bf1a/chapter_18/pizzeria/pizzeria/__init__.py -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzeria/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for pizzeria project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1.7. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | # Quick-start development settings - unsuitable for production 19 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 20 | 21 | # SECURITY WARNING: keep the secret key used in production secret! 22 | SECRET_KEY = 'svo25g-&7(t(om767ok1_2j2c%w+ts#8mw61otk5#j&(x34xk7' 23 | 24 | # SECURITY WARNING: don't run with debug turned on in production! 25 | DEBUG = True 26 | 27 | ALLOWED_HOSTS = [] 28 | 29 | # Application definition 30 | 31 | INSTALLED_APPS = [ 32 | 'django.contrib.admin', 33 | 'django.contrib.auth', 34 | 'django.contrib.contenttypes', 35 | 'django.contrib.sessions', 36 | 'django.contrib.messages', 37 | 'django.contrib.staticfiles', 38 | 39 | # Own apps 40 | 'pizzas' 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'pizzeria.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [os.path.join(BASE_DIR, 'templates')] 59 | , 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'pizzeria.wsgi.application' 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | # Password validation 85 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 86 | 87 | AUTH_PASSWORD_VALIDATORS = [ 88 | { 89 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 90 | }, 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 99 | }, 100 | ] 101 | 102 | # Internationalization 103 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 104 | 105 | LANGUAGE_CODE = 'en-us' 106 | 107 | TIME_ZONE = 'UTC' 108 | 109 | USE_I18N = True 110 | 111 | USE_L10N = True 112 | 113 | USE_TZ = True 114 | 115 | # Static files (CSS, JavaScript, Images) 116 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 117 | 118 | STATIC_URL = '/static/' 119 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzeria/urls.py: -------------------------------------------------------------------------------- 1 | """pizzeria URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from django.conf.urls import url, include 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | url(r'', include('pizzas.urls', namespace='pizzas')) 23 | ] 24 | -------------------------------------------------------------------------------- /chapter_18/pizzeria/pizzeria/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for pizzeria project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pizzeria.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /learning_log/Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | name = "pypi" 3 | url = "https://pypi.org/simple" 4 | verify_ssl = true 5 | 6 | [dev-packages] 7 | 8 | [packages] 9 | django = "*" 10 | 11 | [requires] 12 | python_version = "3.7" 13 | -------------------------------------------------------------------------------- /learning_log/Pipfile.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_meta": { 3 | "hash": { 4 | "sha256": "627ef89f247ecee27e9ef0dabe116108d09c47abf171c900a8817befa64f9dd2" 5 | }, 6 | "pipfile-spec": 6, 7 | "requires": { 8 | "python_version": "3.7" 9 | }, 10 | "sources": [ 11 | { 12 | "name": "pypi", 13 | "url": "https://pypi.org/simple", 14 | "verify_ssl": true 15 | } 16 | ] 17 | }, 18 | "default": { 19 | "django": { 20 | "hashes": [ 21 | "sha256:84f370f6acedbe1f3c41e1a02de44ac206efda3355e427139ecb785b5f596d80", 22 | "sha256:e8fe3c2b2212dce6126becab7a693157f1a441a07b62ec994c046c76af5bb66d" 23 | ], 24 | "index": "pypi", 25 | "version": "==2.2.13" 26 | }, 27 | "pytz": { 28 | "hashes": [ 29 | "sha256:a494d53b6d39c3c6e44c3bec237336e14305e4f29bbf800b599253057fbb79ed", 30 | "sha256:c35965d010ce31b23eeb663ed3cc8c906275d6be1a34393a1d73a41febf4a048" 31 | ], 32 | "version": "==2020.1" 33 | }, 34 | "sqlparse": { 35 | "hashes": [ 36 | "sha256:022fb9c87b524d1f7862b3037e541f68597a730a8843245c349fc93e1643dc4e", 37 | "sha256:e162203737712307dfe78860cc56c8da8a852ab2ee33750e33aeadf38d12c548" 38 | ], 39 | "version": "==0.3.1" 40 | } 41 | }, 42 | "develop": {} 43 | } 44 | -------------------------------------------------------------------------------- /learning_log/learning_log/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davrad/pythoncrashcourse/b73bf31e4237e4400ecc5ed59726fa760754bf1a/learning_log/learning_log/__init__.py -------------------------------------------------------------------------------- /learning_log/learning_log/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for learning_log project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1.7. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | # Quick-start development settings - unsuitable for production 19 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 20 | 21 | # SECURITY WARNING: keep the secret key used in production secret! 22 | SECRET_KEY = 'grnnh2#!cpiv@-2ld%uaqrd2nl0(sug(ixxkrb#=rulnl^vd=5' 23 | 24 | # SECURITY WARNING: don't run with debug turned on in production! 25 | DEBUG = True 26 | 27 | ALLOWED_HOSTS = [] 28 | 29 | # Application definition 30 | 31 | INSTALLED_APPS = [ 32 | 'django.contrib.admin', 33 | 'django.contrib.auth', 34 | 'django.contrib.contenttypes', 35 | 'django.contrib.sessions', 36 | 'django.contrib.messages', 37 | 'django.contrib.staticfiles', 38 | 39 | # My apps 40 | 'learning_logs' 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'learning_log.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [os.path.join(BASE_DIR, 'templates')] 59 | , 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'learning_log.wsgi.application' 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | # Password validation 85 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 86 | 87 | AUTH_PASSWORD_VALIDATORS = [ 88 | { 89 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 90 | }, 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 99 | }, 100 | ] 101 | 102 | # Internationalization 103 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 104 | 105 | LANGUAGE_CODE = 'en-us' 106 | 107 | TIME_ZONE = 'UTC' 108 | 109 | USE_I18N = True 110 | 111 | USE_L10N = True 112 | 113 | USE_TZ = True 114 | 115 | # Static files (CSS, JavaScript, Images) 116 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 117 | 118 | STATIC_URL = '/static/' 119 | -------------------------------------------------------------------------------- /learning_log/learning_log/urls.py: -------------------------------------------------------------------------------- 1 | """learning_log URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import include, url 17 | from django.contrib import admin 18 | from django.urls import path 19 | 20 | urlpatterns = [ 21 | url(r'', include('learning_logs.urls', namespace='learning_logs')), 22 | path('admin/', admin.site.urls), 23 | ] 24 | -------------------------------------------------------------------------------- /learning_log/learning_log/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for learning_log project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning_log.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /learning_log/learning_logs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davrad/pythoncrashcourse/b73bf31e4237e4400ecc5ed59726fa760754bf1a/learning_log/learning_logs/__init__.py -------------------------------------------------------------------------------- /learning_log/learning_logs/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from learning_logs.models import Topic, Entry 4 | 5 | admin.site.register(Topic) 6 | admin.site.register(Entry) 7 | -------------------------------------------------------------------------------- /learning_log/learning_logs/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class LearningLogsConfig(AppConfig): 5 | name = 'learning_logs' 6 | -------------------------------------------------------------------------------- /learning_log/learning_logs/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | from .models import Topic, Entry 4 | 5 | 6 | class TopicForm(forms.ModelForm): 7 | class Meta: 8 | model = Topic 9 | fields = ['text'] 10 | labels = {'text': ''} 11 | 12 | 13 | class EntryForm(forms.ModelForm): 14 | class Meta: 15 | model = Entry 16 | fields = ['text'] 17 | labels = {'text': ''} 18 | widgets = {'text': forms.Textarea(attrs={'cols': 80})} 19 | -------------------------------------------------------------------------------- /learning_log/learning_logs/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.7 on 2019-03-21 13:14 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | initial = True 8 | 9 | dependencies = [ 10 | ] 11 | 12 | operations = [ 13 | migrations.CreateModel( 14 | name='Topic', 15 | fields=[ 16 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 17 | ('text', models.CharField(max_length=200)), 18 | ('date_added', models.DateTimeField(auto_now_add=True)), 19 | ], 20 | ), 21 | ] 22 | -------------------------------------------------------------------------------- /learning_log/learning_logs/migrations/0002_entry.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1.7 on 2019-03-21 13:44 2 | 3 | import django.db.models.deletion 4 | from django.db import migrations, models 5 | 6 | 7 | class Migration(migrations.Migration): 8 | dependencies = [ 9 | ('learning_logs', '0001_initial'), 10 | ] 11 | 12 | operations = [ 13 | migrations.CreateModel( 14 | name='Entry', 15 | fields=[ 16 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 17 | ('text', models.TextField()), 18 | ('date_added', models.DateTimeField(auto_now_add=True)), 19 | ('topic', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='learning_logs.Topic')), 20 | ], 21 | options={ 22 | 'verbose_name_plural': 'entries', 23 | }, 24 | ), 25 | ] 26 | -------------------------------------------------------------------------------- /learning_log/learning_logs/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davrad/pythoncrashcourse/b73bf31e4237e4400ecc5ed59726fa760754bf1a/learning_log/learning_logs/migrations/__init__.py -------------------------------------------------------------------------------- /learning_log/learning_logs/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Topic(models.Model): 5 | """A topic the user is learning about""" 6 | text = models.CharField(max_length=200) 7 | date_added = models.DateTimeField(auto_now_add=True) 8 | 9 | def __str__(self): 10 | """Return a string """ 11 | return self.text 12 | 13 | 14 | class Entry(models.Model): 15 | """Something specific learned about a topic""" 16 | topic = models.ForeignKey(Topic, on_delete=models.CASCADE) 17 | text = models.TextField() 18 | date_added = models.DateTimeField(auto_now_add=True) 19 | 20 | class Meta: 21 | verbose_name_plural = 'entries' 22 | 23 | def __str__(self): 24 | if len(self.text) < 50: 25 | return self.text 26 | return self.text[:50] + "..." 27 | -------------------------------------------------------------------------------- /learning_log/learning_logs/templates/learning_logs/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 |

9 | Learning Log - 10 | Topics 11 |

12 | 13 | {% block content %} {% endblock content %} 14 | 15 | -------------------------------------------------------------------------------- /learning_log/learning_logs/templates/learning_logs/edit_entry.html: -------------------------------------------------------------------------------- 1 | {% extends 'learning_logs/base.html' %} 2 | 3 | {% block content %} 4 |

5 | {{ topic }} 6 |

7 | 8 |

Edit entry:

9 |
10 | {% csrf_token %} 11 | {{ form.as_p }} 12 | 13 |
14 | 15 | {% endblock content %} 16 | -------------------------------------------------------------------------------- /learning_log/learning_logs/templates/learning_logs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | {% extends "learning_logs/base.html" %} 9 | 10 | {% block content %} 11 |

12 | Learning Log helps you keep track of your learning, for any topic you're 13 | learning about. 14 |

15 | {% endblock content %} 16 | 17 | 18 | -------------------------------------------------------------------------------- /learning_log/learning_logs/templates/learning_logs/new_entry.html: -------------------------------------------------------------------------------- 1 | {% extends "learning_logs/base.html" %} 2 | 3 | {% block content %} 4 |

{{ topic }}

5 |

Add a new entry:

6 |
7 | {% csrf_token %} 8 | {{ form.as_p }} 9 | 10 |
11 | {% endblock content %} -------------------------------------------------------------------------------- /learning_log/learning_logs/templates/learning_logs/new_topic.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | {% extends 'learning_logs/base.html' %} 9 | 10 | {% block content %} 11 |

Add a new topic:

12 |
13 | {% csrf_token %} 14 | {{ form.as_p }} 15 | 16 |
17 | 18 | {% endblock content %} 19 | 20 | -------------------------------------------------------------------------------- /learning_log/learning_logs/templates/learning_logs/topic.html: -------------------------------------------------------------------------------- 1 | {% extends 'learning_logs/base.html' %} 2 | 3 | {% block content %} 4 |

Topic: {{ topic }}

5 | 6 |

Entries:

7 |

8 | 9 | add new entry 10 | 11 |

12 | 29 | 30 | {% endblock content %} 31 | -------------------------------------------------------------------------------- /learning_log/learning_logs/templates/learning_logs/topics.html: -------------------------------------------------------------------------------- 1 | {% extends 'learning_logs/base.html' %} 2 | 3 | {% block content %} 4 |

Topics

5 | 6 | 17 | 18 | 19 | Add a new topic 20 | 21 | 22 | {% endblock content %} 23 | 24 | -------------------------------------------------------------------------------- /learning_log/learning_logs/tests.py: -------------------------------------------------------------------------------- 1 | # Create your tests here. 2 | -------------------------------------------------------------------------------- /learning_log/learning_logs/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import views 4 | 5 | app_name = 'learning_logs' 6 | 7 | urlpatterns = [ 8 | url(r'^$', views.index, name='index'), 9 | url(r'^topics/$', views.topics, name='topics'), 10 | url(r'^topics/(?P\d+)/$', views.topic, name='topic'), 11 | url(r'^new_topic/$', views.new_topic, name='new_topic'), 12 | url(r'^new_entry/(?P\d+)/$', views.new_entry, name='new_entry'), 13 | url(r'^edit_entry/(?P\d+)/$', views.edit_entry, name='edit_entry'), 14 | ] 15 | -------------------------------------------------------------------------------- /learning_log/learning_logs/views.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponseRedirect 2 | from django.shortcuts import render 3 | from django.urls import reverse 4 | 5 | from .forms import TopicForm, EntryForm 6 | from .models import Topic, Entry 7 | 8 | 9 | def index(request): 10 | """The home page for Learning Log""" 11 | return render(request, 'learning_logs/index.html') 12 | 13 | 14 | def topics(request): 15 | topics = Topic.objects.order_by('date_added') 16 | context = {'topics': topics} 17 | return render(request, 'learning_logs/topics.html', context) 18 | 19 | 20 | def topic(request, topic_id): 21 | topic = Topic.objects.get(id=topic_id) 22 | entries = topic.entry_set.order_by('-date_added') 23 | context = {'topic': topic, 'entries': entries} 24 | return render(request, 'learning_logs/topic.html', context) 25 | 26 | 27 | def new_topic(request): 28 | if request.method != 'POST': 29 | form = TopicForm() 30 | else: 31 | form = TopicForm(request.POST) 32 | if form.is_valid(): 33 | form.save() 34 | return HttpResponseRedirect(reverse('learning_logs:topics')) 35 | 36 | context = {'form': form} 37 | return render(request, 'learning_logs/new_topic.html', context) 38 | 39 | 40 | def new_entry(request, topic_id): 41 | topic = Topic.objects.get(id=topic_id) 42 | 43 | if request.method != 'POST': 44 | form = EntryForm() 45 | else: 46 | form = EntryForm(data=request.POST) 47 | if form.is_valid(): 48 | new_entry = form.save(commit=False) 49 | new_entry.topic = topic 50 | new_entry.save() 51 | return HttpResponseRedirect(reverse('learning_logs:topic', 52 | args=[topic_id])) 53 | 54 | context = {'topic': topic, 'form': form} 55 | return render(request, 'learning_logs/new_entry.html', context) 56 | 57 | 58 | def edit_entry(request, entry_id): 59 | entry = Entry.objects.get(id=entry_id) 60 | topic = entry.topic 61 | 62 | if request.method != 'POST': 63 | form = EntryForm(instance=Entry) 64 | else: 65 | form = EntryForm(instance=entry, data=request.POST) 66 | if form.is_valid(): 67 | form.save() 68 | return HttpResponseRedirect(reverse('learning_logs:topic', 69 | args=[topic.id])) 70 | context = {'entry': entry, 'topic': topic, 'form': form} 71 | return render(request, 'learning_logs/edit_entry.html', context) 72 | -------------------------------------------------------------------------------- /learning_log/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning_log.settings') 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | --------------------------------------------------------------------------------