├── .circleci └── config.yml ├── .csslintrc ├── .dbwebb-validate.config ├── .dbwebb.course ├── .dbwebb.map ├── .dbwebb.moss ├── .dbwebb.tests ├── .dbwebb.version ├── .dbwebb ├── cli.version ├── inspect ├── inspect-src │ ├── config.bash │ ├── inspect.bash │ ├── kmom.d │ │ ├── kmom03 │ │ │ ├── 10_lab.bash │ │ │ ├── 20_marvin.bash │ │ │ └── 90_bash-prompt.bash │ │ ├── kmom04 │ │ │ ├── 10_lab.bash │ │ │ ├── 20_marvin.bash │ │ │ └── 90_bash-prompt.bash │ │ ├── kmom05 │ │ │ ├── 10_lab.bash │ │ │ ├── 20_marvin.bash │ │ │ └── 90_bash-prompt.bash │ │ ├── kmom06 │ │ │ ├── 10_lab.bash │ │ │ ├── 20_analyzer.bash │ │ │ └── 90_bash-prompt.bash │ │ ├── post.bash │ │ ├── pre.bash │ │ ├── run.bash │ │ └── tentamen │ │ │ ├── 10_correct.bash │ │ │ ├── 20_view-code.bash │ │ │ └── 90_bash-prompt.bash │ └── text │ │ ├── kmom06.txt │ │ ├── tentamen.txt │ │ └── tentamen_extra.txt ├── lab.version ├── test │ ├── examiner │ │ ├── __init__.py │ │ ├── cli_parser.py │ │ ├── colorama │ │ │ ├── __init__.py │ │ │ ├── ansi.py │ │ │ ├── ansitowin32.py │ │ │ ├── initialise.py │ │ │ ├── tests │ │ │ │ ├── __init__.py │ │ │ │ ├── ansi_test.py │ │ │ │ ├── ansitowin32_test.py │ │ │ │ ├── initialise_test.py │ │ │ │ ├── isatty_test.py │ │ │ │ ├── utils.py │ │ │ │ └── winterm_test.py │ │ │ ├── win32.py │ │ │ └── winterm.py │ │ ├── common_errors.py │ │ ├── exam_test_case.py │ │ ├── exam_test_case_exam.py │ │ ├── exam_test_result.py │ │ ├── exam_test_result_exam.py │ │ ├── exceptions.py │ │ ├── fail_message.py │ │ ├── helper_functions.py │ │ ├── run_tests.py │ │ └── sentry.py │ ├── functions.bash │ ├── run.bash │ ├── run.d.bash │ ├── scaffold.d │ │ └── template │ │ │ ├── base_test │ │ │ └── base_test_exam │ ├── scripts.d │ │ ├── docker.d.bash │ │ ├── examiner.d.bash │ │ ├── generate.d.bash │ │ ├── helpers │ │ │ └── docker-correct-extra.d.bash │ │ ├── lab.d.bash │ │ └── validate.d.bash │ └── suite.d │ │ ├── kmom01 │ │ └── plane │ │ │ ├── test_plane.py │ │ │ └── test_plane_structure.py │ │ ├── kmom02 │ │ └── marvin1 │ │ │ ├── extra_test_marvin1.py │ │ │ ├── test_marvin.py │ │ │ └── test_marvin1_structure.py │ │ ├── kmom03 │ │ └── marvin2 │ │ │ ├── extra_test_marvin2.py │ │ │ ├── test_main.py │ │ │ ├── test_marvin1_functions.py │ │ │ ├── test_marvin2.py │ │ │ └── test_marvin2_structure.py │ │ ├── kmom04 │ │ └── marvin3 │ │ │ ├── extra_test_inventory.py │ │ │ ├── test_inventory_functions.py │ │ │ ├── test_main.py │ │ │ └── test_marvin3_structure.py │ │ ├── kmom05 │ │ └── marvin4 │ │ │ ├── extra_test_marvin4.py │ │ │ ├── test_emission_functions.py │ │ │ ├── test_emission_menu.py │ │ │ └── test_marvin4_structure.py │ │ ├── kmom06 │ │ └── analyzer │ │ │ ├── extra_test_analyzer.py │ │ │ ├── test_analyzer.py │ │ │ └── test_analyzer_structure.py │ │ ├── kmom10 │ │ └── typing │ │ │ └── test_typing_structure.py │ │ └── tentamen │ │ └── test_exam.py ├── upload.exclude ├── upload.include └── validate.exclude ├── .eslintrc.json ├── .gitattributes ├── .gitignore ├── .gitmodules ├── .html-minifier.conf ├── .jscsrc ├── .pylintrc ├── .pylintrc_almost_pythonic ├── .pylintrc_default ├── .pylintrc_pythonic ├── .requirements.txt ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── REVISION.md ├── docker-compose.yaml ├── example ├── argparse │ ├── cli_parser.py │ ├── main.py │ ├── programs │ │ └── extended.py │ └── step-by-step │ │ ├── step_1 │ │ └── cli_parser.py │ │ ├── step_2 │ │ └── cli_parser.py │ │ ├── step_3 │ │ ├── cli_parser.py │ │ └── main.py │ │ ├── step_4 │ │ ├── cli_parser.py │ │ └── main.py │ │ └── step_5 │ │ ├── cli_parser.py │ │ └── main.py ├── ascii-canvas │ ├── art │ │ ├── cat-in-forest.json │ │ ├── cat-on-background.json │ │ └── cat-with-alien-in-forest.json │ ├── graphic │ │ ├── alien.txt │ │ ├── base.txt │ │ ├── cat.txt │ │ └── tree.txt │ ├── main.py │ ├── option.py │ └── painting.py ├── avatar-today │ ├── file │ │ ├── avatar.py │ │ ├── avatar │ │ │ ├── garfield.txt │ │ │ ├── miss_muppet.txt │ │ │ ├── muppet.txt │ │ │ ├── odie.txt │ │ │ └── piglet.txt │ │ └── main.py │ ├── list │ │ ├── avatar.py │ │ └── main.py │ └── no-list │ │ ├── avatar.py │ │ └── main.py ├── cgi │ ├── execute-another-file.cgi │ ├── execute-another-file.py │ ├── hello-web.cgi │ ├── serve-as-html.cgi │ └── serve-as-text.cgi ├── cli │ ├── mynameis.py │ ├── mynameis2.py │ └── print-opt-arg.py ├── cmd │ ├── dice │ │ ├── dice.py │ │ ├── diceshell.py │ │ └── main.py │ └── turtle │ │ └── main.py ├── curses │ ├── border.py │ ├── border_ext.py │ ├── bouncing-ball.py │ ├── move-pad.py │ ├── orig │ │ ├── bouncing-ball2.py │ │ ├── bouncing-ball3.py │ │ └── snake.py │ ├── readstring.py │ └── snake.py ├── debugger │ ├── functions.py │ ├── if.py │ ├── loop_function.py │ └── while.py ├── dictionary │ └── warehouse.py ├── emission_data │ ├── emission_data.py │ └── emission_data_small.py ├── emission_scripts │ ├── 1990.csv │ ├── 2005.csv │ ├── 2017.csv │ ├── csv-dict.py │ ├── emission_data.py │ └── emm.csv ├── encoding │ ├── encoding.py │ ├── save_to_json_file.py │ └── test_input.py ├── excel │ ├── README.md │ ├── advanced-worked-hours-tracker.py │ └── simple-worked-hours-tracker.py ├── file │ ├── list │ │ ├── items.txt │ │ └── list-to-file.py │ └── string │ │ ├── items.txt │ │ └── string-to-file.py ├── flow │ ├── for.py │ ├── if.py │ └── while.py ├── functions │ ├── energy │ │ ├── energy_calculation.py │ │ ├── functions.py │ │ └── main.py │ ├── functions_v2.py │ ├── sandwich.py │ └── waysub.py ├── getopt │ ├── main.py │ └── usage.py ├── greeting │ └── greeting.py ├── hello │ ├── hello-fel.py_ │ ├── hello-name.py │ └── hello.py ├── hello_world │ ├── hello.cgi │ ├── hello.py │ ├── hw_commands.py │ ├── hw_function.py │ ├── hw_main.py │ └── hw_script.py ├── image │ ├── image.py │ └── mos.jpg ├── intro-challenge │ └── instructions.md ├── json │ ├── json.txt │ └── parse-json.py ├── lecture_prep │ ├── .dbwebb │ │ └── correct.bash │ ├── assignments.md │ ├── exam.py │ ├── myths.txt │ └── solutions │ │ ├── ht18 │ │ ├── analyze_functions_andreas.py │ │ ├── analyze_functions_emil.py │ │ ├── exam.py │ │ └── myths.txt │ │ ├── ht19 │ │ ├── advanced.py │ │ ├── analyze_functions.py │ │ ├── analyze_functions_emil.py │ │ ├── assignments.md │ │ └── exam.py │ │ └── ht21 │ │ ├── analyze_functions.py │ │ ├── analyze_functions_ordinary.py │ │ ├── assignments.md │ │ ├── exam.py │ │ ├── myths.txt │ │ └── test.py ├── lectures │ ├── 2019 │ │ ├── kmom01 │ │ │ ├── cost_of_candy.py │ │ │ ├── money_converter.py │ │ │ └── time_converter.py │ │ ├── kmom02 │ │ │ ├── bacon.py │ │ │ ├── concat.py │ │ │ ├── debugger.py │ │ │ ├── debugger_assignment.py │ │ │ ├── fixed.py │ │ │ ├── flow.py │ │ │ ├── follower.py │ │ │ ├── for.py │ │ │ ├── gatherer.py │ │ │ ├── if.py │ │ │ ├── oneway.py │ │ │ ├── recent.py │ │ │ ├── savings_calculator.py │ │ │ ├── stepper.py │ │ │ ├── truthiness.py │ │ │ ├── validate-password.py │ │ │ ├── wanted.py │ │ │ └── while.py │ │ ├── kmom03 │ │ │ ├── arguments.py │ │ │ ├── execution_flow.py │ │ │ ├── function.py │ │ │ ├── layercake.py │ │ │ ├── letter_inverter.py │ │ │ ├── numberplates.py │ │ │ └── return.py │ │ ├── kmom04 │ │ │ ├── start │ │ │ │ ├── clothes.py │ │ │ │ ├── main.py │ │ │ │ └── shoes.py │ │ │ └── work │ │ │ │ ├── clothes.py │ │ │ │ ├── main.py │ │ │ │ └── shoes.py │ │ ├── kmom05 │ │ │ └── nested_loops.py │ │ └── kmom06 │ │ │ ├── alphapet.py │ │ │ ├── movies.txt │ │ │ ├── player_score.py │ │ │ ├── search_movie.py │ │ │ ├── shoe_size.py │ │ │ └── tuple.py │ ├── 2020 │ │ ├── kmom01 │ │ │ ├── cost_of_candy.py │ │ │ ├── sec_to_hours.py │ │ │ └── sek_to_yen.py │ │ ├── kmom02-1 │ │ │ ├── for-assignment.py │ │ │ ├── for.py │ │ │ ├── if-assignment.py │ │ │ ├── if.py │ │ │ ├── problem.py │ │ │ ├── string.py │ │ │ ├── while-assignment.py │ │ │ └── while.py │ │ ├── kmom02-2 │ │ │ ├── bacon.py │ │ │ ├── concat.py │ │ │ ├── debugger.py │ │ │ ├── debugger_assignment.py │ │ │ ├── factorial.py │ │ │ ├── password-validator.py │ │ │ └── truthiness.py │ │ ├── kmom03 │ │ │ ├── assignment1.py │ │ │ ├── assignment2.py │ │ │ ├── assignment3.py │ │ │ ├── search_list.py │ │ │ ├── slicing.py │ │ │ └── sort.py │ │ ├── kmom04 │ │ │ ├── arguments.py │ │ │ ├── execution_flow.py │ │ │ ├── executionflow_assignment.py │ │ │ ├── layer_cake.py │ │ │ ├── message_changer.py │ │ │ ├── string_modifier.py │ │ │ └── sum_lists.py │ │ ├── kmom05 │ │ │ ├── dictionary.py │ │ │ ├── find_movies.py │ │ │ ├── movies.txt │ │ │ ├── shoe_sizes.py │ │ │ └── tupler.py │ │ └── kmom06 │ │ │ ├── A5.py │ │ │ ├── data.txt │ │ │ ├── manifesto.txt │ │ │ ├── read.py │ │ │ ├── read_assignment.py │ │ │ ├── shopping.txt │ │ │ ├── shoppinglist.py │ │ │ └── write-append.py │ ├── 2021 │ │ ├── kmom01 │ │ │ ├── candy.py │ │ │ ├── money_converter.py │ │ │ ├── time_converter.py │ │ │ └── variables.py │ │ ├── kmom02-1 │ │ │ ├── for.py │ │ │ ├── for_assignment.py │ │ │ ├── if.py │ │ │ ├── if_assignment.py │ │ │ ├── problem.py │ │ │ ├── string.py │ │ │ ├── while.py │ │ │ └── while_assignment.py │ │ ├── kmom02-2 │ │ │ ├── factorial.py │ │ │ ├── fixed.py │ │ │ ├── follower.py │ │ │ ├── gatherer.py │ │ │ ├── hamburger.py │ │ │ ├── one_way_flag.py │ │ │ ├── recent_holder.py │ │ │ ├── stepper.py │ │ │ ├── truthiness-exercise.py │ │ │ ├── truthiness.py │ │ │ ├── try-except-assignment.py │ │ │ ├── try-except.py │ │ │ └── wanted_holder.py │ │ ├── kmom03 │ │ │ ├── cake.py │ │ │ ├── calc_many_squares.py │ │ │ ├── calc_square.py │ │ │ ├── change_message.py │ │ │ ├── default_arguments.py │ │ │ ├── greeters.py │ │ │ ├── main.py │ │ │ ├── main_for_greeter.py │ │ │ ├── praktiskt_problem │ │ │ │ ├── conversions.py │ │ │ │ ├── output.py │ │ │ │ └── spaghetti.py │ │ │ └── toggle_letter.py │ │ ├── kmom04 │ │ │ ├── bubble_sort.py │ │ │ ├── instruments.py │ │ │ ├── list_as_argument.py │ │ │ ├── list_summer.py │ │ │ ├── movies_with_me.py │ │ │ ├── movies_with_me_part2.py │ │ │ └── zero_to_twenty.py │ │ ├── kmom05 │ │ │ ├── dicts.py │ │ │ ├── golfing.py │ │ │ ├── movies.py │ │ │ ├── shoes.py │ │ │ └── tuples.py │ │ └── kmom06 │ │ │ ├── alfapet.py │ │ │ ├── dogs.txt │ │ │ ├── line_reader.py │ │ │ ├── manifesto.txt │ │ │ ├── points.py │ │ │ ├── read.py │ │ │ ├── read_from.txt │ │ │ ├── shopping.txt │ │ │ ├── shoppinglist.py │ │ │ └── write_to_file.py │ └── 2022 │ │ ├── kmom01 │ │ ├── candy.py │ │ ├── candy_sol1.py │ │ ├── candy_sol2.py │ │ ├── cast.py │ │ ├── types.py │ │ └── variables.py │ │ ├── kmom02 │ │ ├── for.py │ │ ├── for_task.py │ │ ├── for_task_start.py │ │ ├── problem.py │ │ ├── problem_1.py │ │ ├── problem_2.py │ │ ├── problem_3.py │ │ ├── problem_4.py │ │ └── string.py │ │ ├── kmom02_2 │ │ ├── factorial.py │ │ ├── factorial_steps.py │ │ ├── truthiness_int.py │ │ ├── truthiness_none.py │ │ ├── truthiness_str.py │ │ └── truthiness_task.py │ │ ├── kmom03 │ │ ├── cake.py │ │ ├── greeters.py │ │ ├── main.py │ │ ├── main_for_greeters.py │ │ ├── persons.py │ │ └── praktisk_problemlosning │ │ │ ├── calculations.py │ │ │ ├── destination_data.py │ │ │ ├── output.py │ │ │ ├── spaghetti.py │ │ │ └── spaghetti_new.py │ │ ├── kmom05 │ │ └── exceptions.py │ │ └── kmom06 │ │ ├── alfapet.py │ │ ├── file_reader_task.py │ │ ├── manifesto.txt │ │ ├── points.py │ │ ├── points_1.py │ │ ├── points_2.py │ │ ├── points_3.py │ │ ├── read_from.txt │ │ ├── read_from_file.py │ │ └── write_to_file.py ├── list │ └── tic-tac-toe.py ├── marvin │ ├── alice-ch1.txt │ ├── common-words.txt │ ├── format.py │ ├── format.txt │ ├── marvin.py │ ├── old │ │ └── marvin.py │ ├── quotes.txt │ ├── quotes_lgtg.txt │ └── words.txt ├── matrix │ └── do-matrix.py ├── module_lecture │ ├── data.txt │ ├── debug.log │ ├── edit.py │ ├── formatted_lines.txt │ ├── random_line_formatter.py │ ├── random_lines.txt │ ├── shop.py │ ├── shopping_list.txt │ ├── start │ │ ├── clothes.py │ │ ├── main.py │ │ └── shoes.py │ ├── test.py │ └── work │ │ ├── clothes.py │ │ ├── main.py │ │ └── shoes.py ├── old_exams │ ├── lp1-2018 │ │ ├── .dbwebb │ │ │ └── correct.bash │ │ ├── README.md │ │ ├── analyze_functions_solution.py │ │ ├── assignments.md │ │ ├── date_time_functions_solution.py │ │ ├── exam.py │ │ ├── solution.py │ │ └── value-of-time.txt │ ├── lp1-2019 │ │ ├── .dbwebb │ │ │ └── correct.bash │ │ ├── README.md │ │ ├── assignments.md │ │ ├── exam.py │ │ ├── manifesto.txt │ │ └── solution.py │ ├── lp1-2020 │ │ ├── .dbwebb │ │ │ └── correct.bash │ │ ├── README.md │ │ ├── analyze_functions_solution.py │ │ ├── assignments.md │ │ ├── exam.py │ │ ├── solution.py │ │ ├── title.basics.csv │ │ └── title.ratings.csv │ ├── lp1-2021 │ │ ├── .dbwebb │ │ │ └── correct.bash │ │ ├── assignments.md │ │ ├── exam.py │ │ ├── numbers.txt │ │ ├── savingscentral_solution.py │ │ ├── solution.py │ │ └── stockbank_solution.py │ └── prep │ │ ├── .dbwebb │ │ └── correct.bash │ │ ├── README.md │ │ ├── analyze_functions_solution.py │ │ ├── assignments.md │ │ ├── exam.py │ │ ├── manifesto.txt │ │ └── solution.py ├── ping-pong │ └── matches.txt ├── ping │ └── ping.py ├── pylint │ ├── generate.bash │ └── messages.md ├── quote │ └── get-quote.py ├── real_path │ └── real_path.py ├── redovisa │ ├── img │ │ └── marvin.jpg │ ├── js │ │ └── main.js │ ├── me.html │ ├── om.html │ ├── redovisning.html │ └── style │ │ └── style.css ├── scope │ └── legb.py ├── scrape │ └── irc-from-dbwebb.py ├── slides │ ├── kmom01.html │ └── kmom02.html ├── sqlite │ └── sqlite-ping.py ├── text │ ├── lorum.txt │ └── phil.txt ├── try-except │ └── input-integer.py └── typing │ ├── easy.txt │ ├── hard.txt │ └── medium.txt ├── package.json └── tutorial ├── README.md ├── bool-expr.md ├── built-in-funcs.md ├── datetime.md ├── dict.md ├── faq.md ├── files.md ├── for.md ├── functions.md ├── if.md ├── input.md ├── list-basic.md ├── list-methods.md ├── math.md ├── objects.md ├── operators.md ├── random.md ├── range.md ├── string-basic.md ├── string-formatting.md ├── string-methods.md ├── string-module.md ├── string-translation.md ├── try-except.md ├── tuple.md ├── types.md ├── variables.md ├── while.md └── with-files.md /.csslintrc: -------------------------------------------------------------------------------- 1 | --ignore=import,box-model,qualified-headings,unique-headings,box-sizing,universal-selector,bulletproof-font-face,font-sizes,adjoining-classes,overqualified-elements,floats 2 | -------------------------------------------------------------------------------- /.dbwebb-validate.config: -------------------------------------------------------------------------------- 1 | # Validation tools 2 | DISABLE_HTMLHINT=true 3 | DISABLE_CSSLINT=true 4 | DISABLE_JSHINT=true 5 | DISABLE_ESLINT=true 6 | DISABLE_JSCS=true 7 | DISABLE_JSONLINT= 8 | DISABLE_PYLINT= 9 | DISABLE_PHP=true 10 | DISABLE_PHPMD=true 11 | DISABLE_PHPCS=true 12 | DISABLE_CHECKBASH=true 13 | DISABLE_CHECKSH=true 14 | DISABLE_YAML=true 15 | DISABLE_FILE_BOM= 16 | DISABLE_FILE_CRLF= 17 | 18 | # Minifying and uglify tools 19 | DISABLE_HTML_MINIFIER=true 20 | DISABLE_CLEANCSS= 21 | DISABLE_UGLIFYJS= 22 | DISABLE_PHPMINIFY=true 23 | -------------------------------------------------------------------------------- /.dbwebb.course: -------------------------------------------------------------------------------- 1 | DBW_COURSE="python" 2 | -------------------------------------------------------------------------------- /.dbwebb.map: -------------------------------------------------------------------------------- 1 | # 2 | # This file has two meanings. 3 | # First create these directories on dbwebb init-me in the me-dir. 4 | # Map item to dirname while doing, for example, dbwebb validate lab1 5 | # 6 | # 7 | # 8 | # DON'T! forget to update .dbwebb/validate.exclude to exclude dirs from validation 9 | # 10 | 11 | # kmom01 12 | me/kmom01/hello 13 | me/kmom01/plane 14 | me/kmom01/lab1 15 | 16 | # kmom02 17 | me/kmom02/lab2 18 | me/kmom02/marvin1 19 | me/kmom02/flow 20 | 21 | # kmom03 22 | me/kmom03/lab3 23 | me/kmom03/marvin2 24 | me/kmom03/functions 25 | 26 | # kmom04 27 | me/kmom04/lab4 28 | me/kmom04/list 29 | me/kmom04/marvin3 30 | 31 | # kmom05 32 | me/kmom05/lab5 33 | me/kmom05/warehouse 34 | me/kmom05/marvin4 35 | 36 | # kmom06 37 | me/kmom06/lab6 38 | me/kmom06/file 39 | me/kmom06/analyzer 40 | 41 | # kmom10 42 | me/kmom10/typing 43 | 44 | # redovisa 45 | me/redovisa 46 | -------------------------------------------------------------------------------- /.dbwebb.moss: -------------------------------------------------------------------------------- 1 | # 2 | # Files used for moss purpose. 3 | # action params file/dirname 4 | # 5 | 6 | [kmom01] 7 | me/kmom01/plane/plane.py 8 | 9 | [kmom02] 10 | me/kmom02/marvin1/marvin.py 11 | 12 | [kmom03] 13 | me/kmom03/marvin2/marvin2.py 14 | 15 | [kmom04] 16 | me/kmom04/marvin3/inventory.py 17 | 18 | [kmom05] 19 | me/kmom05/marvin4/emission_functions.py 20 | 21 | [kmom06] 22 | me/kmom06/analyzer/analyzer.py 23 | me/kmom06/analyzer/main.py 24 | 25 | [kmom10] 26 | me/kmom10/typing/* 27 | !me/kmom10/typing/__pycache__ 28 | -------------------------------------------------------------------------------- /.dbwebb.version: -------------------------------------------------------------------------------- 1 | v2.0.4 (2017-06-14) 2 | -------------------------------------------------------------------------------- /.dbwebb/cli.version: -------------------------------------------------------------------------------- 1 | v2.9.1 (2021-04-08) -------------------------------------------------------------------------------- /.dbwebb/inspect-src/config.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Sample configuration file to use with dbwebb gui for inspect. 4 | # This file is stored in the course repo and you can use it to override 5 | # settings from the script itself, or from your local configuration file. 6 | # 7 | 8 | # You can setup your configuration based on the $COURSE 9 | #echo $COURSE 10 | 11 | # Where are the inspect source files stored, default is in the course repo 12 | #export INSPECT_SOURCE_DIR="$DIR/.solutions/inspect-src" 13 | 14 | # Course specific settings 15 | export REDOVISA_HTTP_PREFIX="http://www.student.bth.se" 16 | export REDOVISA_HTTP_POSTFIX="me/redovisa" 17 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/inspect.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Sample configuration file to use with dbwebb gui for inspect. 4 | # This file is stored in the course repo and you can use it to override 5 | # settings from the script itself, or from your local configuration file. 6 | # 7 | 8 | # You can setup your configuration based on the $COURSE 9 | #echo $COURSE 10 | 11 | # Where are the inspect source files stored, default is in the course repo 12 | export INSPECT_SOURCE_DIR="$DIR/.solutions/inspect-src" 13 | 14 | # Course specific settings 15 | export REDOVISA_HTTP_PREFIX="http://www.student.bth.se" 16 | export REDOVISA_HTTP_POSTFIX="me/redovisa" -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom03/10_lab.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom03/lab3/ || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Run lab" 7 | python3 answer.py 8 | 9 | read -p "Press to view answer.py" answer 10 | cat answer.py -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom03/20_marvin.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom03/marvin2 || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Run Marvin2" 7 | python3 marvin.py 8 | 9 | read -p "Press to view marvin.py" answer 10 | cat marvin.py 11 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom03/90_bash-prompt.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom03/marvin2 || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Do manual stuff, if needed (write e/f to exit)?" 7 | bash 8 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom04/10_lab.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom04/lab4/ || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Run lab" 7 | python3 answer.py 8 | 9 | read -p "Press to view answer.py" answer 10 | cat answer.py -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom04/20_marvin.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom04/marvin3/ || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Run Marvin3" 7 | python3 main.py 8 | 9 | read -p "Press to view main.py" answer 10 | cat main.py 11 | 12 | read -p "Press to view marvin.py" answer 13 | cat marvin.py 14 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom04/90_bash-prompt.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom04/marvin3/ || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Do manual stuff, if needed (write e/f to exit)?" 7 | bash 8 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom05/10_lab.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom05/lab5/ || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Run lab" 7 | python3 answer.py 8 | 9 | read -p "Press to view answer.py" answer 10 | cat answer.py -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom05/20_marvin.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom05/marvin4/ || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Run Marvin3" 7 | python3 main.py 8 | 9 | read -p "Press to view main.py" answer 10 | cat main.py 11 | 12 | read -p "Press to view emission_functions.py" answer 13 | cat emission_functions.py 14 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom05/90_bash-prompt.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom05/marvin4/ || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Do manual stuff, if needed (write e/f to exit)?" 7 | bash 8 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom06/10_lab.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom06/lab6/ || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Run lab" 7 | python3 answer.py -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom06/20_analyzer.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom06/analyzer || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Run correct" 7 | bash .dbwebb/correct.bash 8 | 9 | read -p "Press to view main.py" answer 10 | cat main.py 11 | 12 | read -p "Press to view analyzer.py" answer 13 | cat analyzer.py 14 | 15 | read -p "Press to view menu.py" answer 16 | cat menu.py 17 | 18 | read -p "Press to view test_exam.py" answer 19 | cat .dbwebb/test_exam.py -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/kmom06/90_bash-prompt.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/kmom06/analyzer || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Do manual stuff, if needed (write e/f to exit)?" 7 | bash 8 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/post.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Script run AFTER kmom specific scripts. 4 | # Put tests here that applies to all kmoms. 5 | # 6 | # Available (and usable) data: 7 | # $COURSE 8 | # $KMOM 9 | # $ACRONYM 10 | # $REDOVISA_HTTP_PREFIX 11 | # $REDOVISA_HTTP_POSTFIX 12 | # eval "$BROWSER" "$url" & 13 | # 14 | printf ">>> -------------- Post (all kmoms) ---------------------\n" 15 | 16 | # # Open localhost:1337 in browser 17 | # printf "Open localhost:1337/eshop/index in browser\n" 18 | # eval "$BROWSER" "http://127.0.0.1:1337/eshop/index" & 19 | 20 | # # Open me/kmom01/redovisa 21 | # url="$REDOVISA_HTTP_PREFIX/~$ACRONYM/dbwebb-kurser/$COURSE/me/redovisa/htdocs" 22 | # printf "$url\n" 2>&1 23 | # eval "$BROWSER" "$url" & 24 | 25 | # echo 26 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/tentamen/10_correct.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/tentamen/ || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Run correct script" 7 | dbwebb test tentamen --no-validate 8 | 9 | # cant upload from inside docker so we run manual validate 10 | cd ../../ && make validate what=me/tentamen 11 | 12 | read -p "Press to view code" answer 13 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/tentamen/20_view-code.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/tentamen/ || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "View exam.py" 7 | cat exam.py 8 | 9 | read -p "Press to view reader.py" answer 10 | 11 | cat reader.py 12 | 13 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/kmom.d/tentamen/90_bash-prompt.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd me/tentamen || exit 3 | e() { exit; }; export -f e 4 | f() { exit 1; }; export -f f 5 | 6 | echo "Do manual stuff, if needed (write e/f to exit)?" 7 | bash 8 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/text/kmom06.txt: -------------------------------------------------------------------------------- 1 | Bra jobbar, alla tester går igenom och koden validerar. 2 | 3 | Jag hittade heller inget i din kod att kommentera på. -------------------------------------------------------------------------------- /.dbwebb/inspect-src/text/tentamen.txt: -------------------------------------------------------------------------------- 1 | Jag har tittat på din inlämning. 2 | 3 | Du är GODKÄND. 4 | 5 | Jag hittade inget speciellt att anmärka på i koden. 6 | 7 | Kul att du gillade kursen. 8 | -------------------------------------------------------------------------------- /.dbwebb/inspect-src/text/tentamen_extra.txt: -------------------------------------------------------------------------------- 1 | Som du säkert vet är tentan tyvärr inte godkänd, datum för omtentor kan du hitta under denna länk: 2 | https://dbwebb.se/kurser/python-v3/kmom10#omexamination 3 | 4 | Har du några frågor på hur det kommer gå till kan du alltid kontakta oss på Discord eller email. 5 | 6 | Det är alltid jobbigt att koda under tidspress och vissa dagar fungerar det inte alls. Det är bara att ta nya tag och försöka igen. Tack för din feedback, den är väldigt uppskattat. 7 | 8 | Vi önskar dig ett lycka till på omtentan, det kommer säkert att gå bra! -------------------------------------------------------------------------------- /.dbwebb/lab.version: -------------------------------------------------------------------------------- 1 | v4 2 | -------------------------------------------------------------------------------- /.dbwebb/test/examiner/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Meta data for code 3 | """ 4 | from examiner.exam_test_case import ExamTestCase 5 | from examiner.exam_test_case_exam import ExamTestCaseExam 6 | from examiner.exam_test_result import ExamTestResult 7 | from examiner.exam_test_result_exam import ExamTestResultExam 8 | from examiner.helper_functions import check_for_tags as tags, find_path_to_assignment, import_module 9 | 10 | # Version structure major.minor[.patch][sub] 11 | __version__ = '2.6.0' 12 | -------------------------------------------------------------------------------- /.dbwebb/test/examiner/colorama/__init__.py: -------------------------------------------------------------------------------- 1 | # pylint: skip-file 2 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. 3 | from .initialise import init, deinit, reinit, colorama_text, just_fix_windows_console 4 | from .ansi import Fore, Back, Style, Cursor 5 | from .ansitowin32 import AnsiToWin32 6 | 7 | __version__ = '0.4.6' 8 | 9 | -------------------------------------------------------------------------------- /.dbwebb/test/examiner/colorama/tests/__init__.py: -------------------------------------------------------------------------------- 1 | # pylint: skip-file 2 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. 3 | -------------------------------------------------------------------------------- /.dbwebb/test/examiner/exam_test_case_exam.py: -------------------------------------------------------------------------------- 1 | """ 2 | Overriding TestCase for exam tool. 3 | """ 4 | from examiner.exam_test_case import ExamTestCase 5 | 6 | class ExamTestCaseExam(ExamTestCase): 7 | """ 8 | Custom class for examination. 9 | Can set points for assignments and a threshold for passing. 10 | """ 11 | 12 | points_for_pass = -1 13 | points_worth = 0 14 | -------------------------------------------------------------------------------- /.dbwebb/test/scripts.d/helpers/docker-correct-extra.d.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | 4 | BASE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 5 | . "$BASE_DIR/../../functions.bash" 6 | 7 | 8 | get_python_command 9 | export COURSE_REPO_BASE="${BASE_DIR}/../../../../" 10 | export PYTHON_EXECUTER="$py" 11 | export EXAMINER_RUNNER="examiner.run_tests" 12 | export TESTSUITE=$1 13 | export ARGUMENTS="--extra" 14 | export LOG="$COURSE_REPO_BASE/.log/test/docker/test-extra.ansi" 15 | 16 | 17 | execute_with_timeout 7 60 bash .dbwebb/test/scripts.d/examiner.d.bash 18 | -------------------------------------------------------------------------------- /.dbwebb/test/scripts.d/validate.d.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | HEADER="scripts.d/$( basename -- "$0" ) start" 4 | FOOTER="scripts.d/$( basename -- "$0" ) end" 5 | 6 | 7 | 8 | printf "$HEADER 9 | 10 | Validation: \"dbwebb validate $TESTSUITE\": 11 | " | tee -a "$LOG" 12 | 13 | 14 | 15 | for opt in $ARGUMENTS; do 16 | case $opt in 17 | "--no-validate" ) 18 | skip=true 19 | ;; 20 | "--docker" ) 21 | make_validate=true 22 | esac 23 | done; 24 | 25 | 26 | 27 | if [[ "$skip" ]]; then 28 | printf "Skipped validate .. 29 | " | tee -a "$LOG" 30 | else 31 | if [[ "$make_validate" ]]; then 32 | bash -c "set -o pipefail && make validate what='$TESTSUITE' | tee -a '$LOG' " 33 | status=$? 34 | else 35 | bash -c "set -o pipefail && dbwebb validate '$TESTSUITE' | tee -a '$LOG' " 36 | status=$? 37 | fi 38 | fi 39 | 40 | printf " 41 | $FOOTER 42 | $SEPARATOR 43 | " | tee -a "$LOG" 44 | 45 | 46 | exit $status 47 | -------------------------------------------------------------------------------- /.dbwebb/upload.exclude: -------------------------------------------------------------------------------- 1 | - *:Zone.Identifier -------------------------------------------------------------------------------- /.dbwebb/upload.include: -------------------------------------------------------------------------------- 1 | # dbwebb config files 2 | - /.dbwebb.exclude 3 | - /.dbwebb.include 4 | - /.dbwebb.tests 5 | - /.dbwebb.version 6 | /.dbwebb/* 7 | /.dbwebb* 8 | 9 | # Validator config files 10 | /.*rc 11 | /.*.xml 12 | /.*.conf 13 | /.*.json 14 | 15 | # Python generated file 16 | - __pycache__/ 17 | 18 | /example/ 19 | /example/** 20 | 21 | /me/ 22 | - /me/anax-lite/.bin 23 | - /me/anax-lite/cache/cimage/* 24 | - vendor/mos/cimage/webroot 25 | - vendor/**/config 26 | - vendor/**/docs 27 | - vendor/**/test 28 | - node_modules/ 29 | - **/.vscode 30 | - **/.idea 31 | /me/** 32 | 33 | - */ 34 | - * 35 | -------------------------------------------------------------------------------- /.dbwebb/validate.exclude: -------------------------------------------------------------------------------- 1 | # 2 | # dbwebb validate exclude and include files for validate and publish. 3 | # 4 | # Paths start from courserepo, so path to me is "./me". 5 | # 6 | 7 | # ignore non assignment folders 8 | -./me/kmom01/hello/* 9 | -./me/kmom02/flow/* 10 | -./me/kmom03/functions/* 11 | -./me/kmom04/list/* 12 | -./me/kmom05/warehouse/* 13 | -./me/kmom06/file/* 14 | -./me/kmom10/prep/* 15 | 16 | # Start by removing some common -files and add some +subdirs 17 | -*/.git/* 18 | -*/build/* 19 | -*/cache/* 20 | -*/docs/* 21 | -*/lib/* 22 | -*.min.* 23 | -*.png 24 | -*.jpg 25 | -./.venv 26 | 27 | -./me/*/vendor/* 28 | -./me/*/node_modules/* 29 | 30 | #-./me/*/platforms/* 31 | #+./me/*/platforms/browser/www/*.html 32 | #+./me/*/platforms/browser/www/css/*.css 33 | #+./me/*/platforms/browser/www/js/*.js 34 | 35 | # -- Really remove files, even if found below +subdirs 36 | #--*font-awesome* 37 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Force LF as lineendings, on textfiles 2 | * text eol=lf 3 | 4 | # Autodetect text files 5 | * text=auto 6 | 7 | # ...Unless the name matches the following 8 | # overriding patterns 9 | 10 | # Definitively text files 11 | #*.txt text 12 | #*.c text 13 | #*.h text 14 | 15 | # Ensure those won't be messed up with 16 | *.webm binary 17 | *.gif binary 18 | *.png binary 19 | *.jpg binary 20 | *.jpeg binary 21 | *.sqlite binary 22 | *.mp3 binary 23 | *.mp4 binary 24 | *.ogg binary 25 | *.pdf binary 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | debug.log 2 | me/ 3 | bin/ 4 | build/ 5 | .venv/ 6 | venv/ 7 | vendor/ 8 | node_modules/ 9 | package-lock.json 10 | .log/ 11 | exam/ 12 | inspect-gui 13 | klingochklang/ 14 | 15 | example/sqlite/ping.db 16 | example/intro-challenge/folder* 17 | 18 | __pycache__ 19 | *.pyc 20 | 21 | # VSCode 22 | .vscode/ 23 | 24 | # Mac OS 25 | .DS_Store 26 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule ".solutions"] 2 | path = .solutions 3 | url = git@bitbucket.org:mosbth/python-solutions.git 4 | -------------------------------------------------------------------------------- /.html-minifier.conf: -------------------------------------------------------------------------------- 1 | { 2 | "removeComments": true, 3 | "collapseWhitespace": true, 4 | "conservativeCollapse": true, 5 | "collapseBooleanAttributes": true, 6 | "removeAttributeQuotes": true, 7 | "removeRedundantAttributes": true, 8 | "useShortDoctype": true, 9 | "removeEmptyAttributes": false, 10 | "removeOptionalTags": false, 11 | "removeEmptyElements": false, 12 | "lint": false, 13 | "keepClosingSlash": true, 14 | "caseSensitive": true, 15 | "minifyJS": true, 16 | "minifyCSS": false 17 | } 18 | 19 | -------------------------------------------------------------------------------- /.jscsrc: -------------------------------------------------------------------------------- 1 | { 2 | "validateIndentation": 4, 3 | "requireCurlyBraces": ["while", "do", "try", "catch", "for"], 4 | "disallowKeywords": [ "with" ], 5 | 6 | 7 | 8 | "requireAlignedMultilineParams": "firstParam", 9 | 10 | 11 | 12 | "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"], 13 | "requireSpacesInForStatement": true, 14 | "requireSpaceAfterComma": {"allExcept": ["trailing"]}, 15 | "requireSpaceBeforeBlockStatements": 1, 16 | "requireSpacesInFunctionExpression": { 17 | "beforeOpeningCurlyBrace": true 18 | }, 19 | 20 | 21 | 22 | "disallowSpaceBeforeComma": {"allExcept": ["sparseArrays"]}, 23 | "disallowSpaceBeforeSemicolon": { "allExcept": [ "(" ] }, 24 | 25 | 26 | 27 | "disallowMixedSpacesAndTabs": true, 28 | 29 | 30 | 31 | "validateLineBreaks": "LF", 32 | "requireLineFeedAtFileEnd": true, 33 | "disallowTrailingWhitespace": true 34 | } 35 | -------------------------------------------------------------------------------- /.pylintrc_almost_pythonic: -------------------------------------------------------------------------------- 1 | [MESSAGES CONTROL] 2 | 3 | disable=locally-disabled,locally-enabled,superfluous-parens,invalid-name 4 | 5 | 6 | [FORMAT] 7 | 8 | # Maximum number of characters on a single line. 9 | max-line-length=79 10 | 11 | 12 | [REPORTS] 13 | 14 | #reports=no 15 | -------------------------------------------------------------------------------- /.pylintrc_pythonic: -------------------------------------------------------------------------------- 1 | [MESSAGES CONTROL] 2 | 3 | disable=locally-disabled,locally-enabled 4 | 5 | 6 | [FORMAT] 7 | 8 | # Maximum number of characters on a single line. 9 | max-line-length=79 10 | 11 | 12 | [REPORTS] 13 | 14 | #reports=no 15 | -------------------------------------------------------------------------------- /.requirements.txt: -------------------------------------------------------------------------------- 1 | pylint == 2.16.2 2 | #coverage 3 | #flake8 4 | #flake8-docstrings 5 | #pycodestyle 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - "3.4" 5 | - "3.5" 6 | - "3.6" 7 | - "3.7-dev" 8 | - "nightly" 9 | 10 | sudo: false 11 | 12 | 13 | 14 | git: 15 | submodules: false 16 | 17 | 18 | 19 | addons: 20 | apt: 21 | packages: 22 | #- pylint 23 | #- php-codesniffer 24 | #- phpmd 25 | #- shellcheck 26 | 27 | 28 | 29 | matrix: 30 | allow_failures: 31 | - python: "3.7-dev" 32 | - python: "nightly" 33 | 34 | 35 | 36 | before_script: 37 | - make install 38 | 39 | 40 | script: 41 | - make test 42 | 43 | 44 | 45 | notifications: 46 | irc: "irc.freenode.org#dbwebb" 47 | 48 | webhooks: 49 | urls: 50 | - https://webhooks.gitter.im/e/e9644e16dba8fa098005 51 | 52 | # options: [always|never|change] default: always 53 | on_success: change 54 | on_failure: always 55 | on_start: never 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. 2 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | volumes: 4 | mysql_data: {} 5 | mariadb_data: {} 6 | 7 | services: 8 | # Primary services to use with this course 9 | python: &python 10 | image: dbwebb/courserepo:python 11 | volumes: 12 | - ".:/home/dbwebb/repo" 13 | - "/home/dbwebb/repo/bin" 14 | - "/home/dbwebb/repo/build" 15 | - "/home/dbwebb/repo/node_modules" 16 | - "/home/dbwebb/repo/vendor" 17 | #- "./example/sql/inspect/my.cnf:/home/dbwebb/.my.cnf" 18 | 19 | cli: 20 | <<: *python 21 | 22 | server: 23 | <<: *python 24 | ports: 25 | - "18080:80" 26 | 27 | courserepo: 28 | image: dbwebb/courserepo:cli 29 | volumes: 30 | - ".:/home/dbwebb/repo" 31 | #- "/home/dbwebb/repo/bin" 32 | #- "/home/dbwebb/repo/build" 33 | #- "/home/dbwebb/repo/node_modules" 34 | #- "/home/dbwebb/repo/vendor" 35 | #- "./example/sql/inspect/my.cnf:/home/dbwebb/.my.cnf" 36 | -------------------------------------------------------------------------------- /example/argparse/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Main cli-program, to start it all up by reading command line 6 | options and arguments and the executing whats to be executed. 7 | 8 | See usage.py for details how to use program. 9 | >>> import cli_parser 10 | >>> help(cli_parser) 11 | 12 | or 13 | 14 | $ pydoc cli_parser 15 | 16 | """ 17 | 18 | import sys 19 | import cli_parser 20 | 21 | 22 | def main(): 23 | """ 24 | Main function where it all starts. 25 | """ 26 | 27 | cli_parser.parse_options() 28 | 29 | print(cli_parser.options) 30 | 31 | print(cli_parser.options["known_args"]["command"]) 32 | 33 | print() 34 | 35 | sys.exit() 36 | 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /example/argparse/step-by-step/step_1/cli_parser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Parse CLI options. 6 | 7 | Basic, prints args and unknown_args 8 | Try it: 9 | $ python3 cli_parser.py -h 10 | $ python3 cli_parser.py hej 11 | """ 12 | 13 | import argparse 14 | 15 | parser = argparse.ArgumentParser() 16 | 17 | args, unknown_args = parser.parse_known_args() 18 | 19 | print("args: ", vars(args)) 20 | print("unknown_args: ", unknown_args) 21 | -------------------------------------------------------------------------------- /example/argparse/step-by-step/step_2/cli_parser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Parse CLI options. 6 | 7 | Basic 2, prints args and unknown_args 8 | $ python3 cli_parser.py -h 9 | $ python3 cli_parser.py hello 10 | $ python3 cli_parser.py hello world 11 | """ 12 | 13 | import argparse 14 | 15 | parser = argparse.ArgumentParser() 16 | 17 | parser.add_argument("first") 18 | 19 | args, unknown_args = parser.parse_known_args() 20 | 21 | print("args: ", vars(args)) 22 | print("unknown_args: ", unknown_args) 23 | -------------------------------------------------------------------------------- /example/argparse/step-by-step/step_3/cli_parser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Parse CLI options. 6 | Basic 3, prints args and unknown_args 7 | """ 8 | 9 | import argparse 10 | 11 | options = {} 12 | 13 | def parse_options(): 14 | """ 15 | parse arguments and commands sent at start up. 16 | """ 17 | 18 | parser = argparse.ArgumentParser() 19 | 20 | parser.add_argument("first") 21 | 22 | args, unknown_args = parser.parse_known_args() 23 | 24 | options["args"] = vars(args) 25 | options["unknown_args"] = unknown_args 26 | 27 | return options 28 | -------------------------------------------------------------------------------- /example/argparse/step-by-step/step_3/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Main cli-program, to start it all up by reading command line 6 | options and arguments and then executing whats to be executed. 7 | 8 | $ python3 cli_parser.py -h 9 | $ python3 cli_parser.py hello 10 | $ python3 cli_parser.py hello world 11 | """ 12 | 13 | import sys 14 | import cli_parser 15 | 16 | 17 | 18 | def main(): 19 | """ 20 | Main function where it all starts. 21 | """ 22 | 23 | options = cli_parser.parse_options() 24 | 25 | print(options) 26 | 27 | if options["args"]["first"]: 28 | print("Your input was: ", options["args"]["first"]) 29 | 30 | sys.exit() 31 | 32 | if __name__ == "__main__": 33 | main() 34 | -------------------------------------------------------------------------------- /example/argparse/step-by-step/step_4/cli_parser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Parse CLI options. 6 | Basic 4, prints args and unknown_args with --silent and --verbose 7 | """ 8 | 9 | import argparse 10 | 11 | options = {} 12 | 13 | def parse_options(): 14 | """ 15 | parse arguments and commands sent at start up. 16 | """ 17 | 18 | parser = argparse.ArgumentParser() 19 | 20 | parser.add_argument("--silent", dest="silent", action="store_true") 21 | parser.add_argument("--verbose", dest="verbose", action="store_true") 22 | 23 | parser.add_argument("first") 24 | 25 | args, unknown_args = parser.parse_known_args() 26 | 27 | options["args"] = vars(args) 28 | options["unknown_args"] = unknown_args 29 | 30 | return options 31 | -------------------------------------------------------------------------------- /example/argparse/step-by-step/step_5/cli_parser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Parse CLI options. 6 | Basic 5, using subparser 7 | """ 8 | 9 | import argparse 10 | 11 | options = {} 12 | 13 | def parse_options(): 14 | """ 15 | parse arguments and commands sent at start up. 16 | """ 17 | 18 | parser = argparse.ArgumentParser() 19 | 20 | parser.add_argument("--silent", dest="silent", action="store_true") 21 | parser.add_argument("--verbose", dest="verbose", action="store_true") 22 | 23 | subparsers = parser.add_subparsers(title="commands (positional arguments)", 24 | help='Available commands', dest="command") 25 | 26 | subparsers.add_parser("hello", help="Respons to hello") 27 | subparsers.add_parser("goodbye", help="Respons to goodbye") 28 | 29 | 30 | args, unknown_args = parser.parse_known_args() 31 | 32 | options["args"] = vars(args) 33 | options["unknown_args"] = unknown_args 34 | 35 | return options 36 | -------------------------------------------------------------------------------- /example/ascii-canvas/art/cat-in-forest.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Cat sits in a forest.", 3 | "parts": [ 4 | { 5 | "file": "graphic/base.txt", 6 | "pos_x": 0, 7 | "pos_y": 0 8 | }, 9 | { 10 | "file": "graphic/tree.txt", 11 | "pos_x": 5, 12 | "pos_y": 5 13 | }, 14 | { 15 | "file": "graphic/cat.txt", 16 | "pos_x": 60, 17 | "pos_y": 10 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /example/ascii-canvas/art/cat-on-background.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Cat on a background.", 3 | "parts": [ 4 | { 5 | "file": "graphic/base.txt", 6 | "pos_x": 0, 7 | "pos_y": 0 8 | }, 9 | { 10 | "file": "graphic/cat.txt", 11 | "pos_x": 10, 12 | "pos_y": 10 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /example/ascii-canvas/art/cat-with-alien-in-forest.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Cat meets alien in a forest.", 3 | "parts": [ 4 | { 5 | "file": "graphic/base.txt", 6 | "pos_x": 0, 7 | "pos_y": 0 8 | }, 9 | { 10 | "file": "graphic/tree.txt", 11 | "pos_x": 15, 12 | "pos_y": 1 13 | }, 14 | { 15 | "file": "graphic/alien.txt", 16 | "pos_x": 2, 17 | "pos_y": 7 18 | }, 19 | { 20 | "file": "graphic/cat.txt", 21 | "pos_x": 60, 22 | "pos_y": 10 23 | } 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /example/ascii-canvas/graphic/alien.txt: -------------------------------------------------------------------------------- 1 | o o 2 | )-( 3 | (O O) 4 | \=/ 5 | .-"-. 6 | //\ /\\ 7 | _// / \ \\_ 8 | =./ {,-.} \.= 9 | || || 10 | || || 11 | __|| ||__ 12 | `---" "---' 13 | -------------------------------------------------------------------------------- /example/ascii-canvas/graphic/cat.txt: -------------------------------------------------------------------------------- 1 | /\_/\ 2 | /\ / o o \ 3 | //\\ \~(*)~/ 4 | ` \/ ^ / 5 | | \|| || 6 | \ '|| || 7 | \)()-()) 8 | -------------------------------------------------------------------------------- /example/ascii-canvas/graphic/tree.txt: -------------------------------------------------------------------------------- 1 | ,@@@@@@@, 2 | ,,,. ,@@@@@@/@@, .oo8888o. 3 | ,&%%&%&&%,@@@@@/@@@@@@,8888\88/8o 4 | ,%&\%&&%&&%,@@@\@@@/@@@88\88888/88' 5 | %&&%&%&/%&&%@@\@@/ /@@@88888\88888' 6 | %&&%/ %&%%&&@@\ V /@@' `88\8 `/88' 7 | `&%\ ` /%&' |.| \ '|8' 8 | |o| | | | | 9 | |.| | | | | 10 | \\/ ._\//_/__/ ,\_//__\\/. \_//__/_ 11 | -------------------------------------------------------------------------------- /example/ascii-canvas/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """To display an ascii painting made up of several smaller parts.""" 5 | 6 | import option 7 | import painting 8 | 9 | 10 | def main(): 11 | """Main function where it all starts.""" 12 | options = option.parse_options() 13 | if not options["silent"]: 14 | print(__doc__) 15 | if options["verbose"]: 16 | print(options) 17 | 18 | art = painting.create_from_file( 19 | options["filename"], 20 | verbose=options["verbose"] 21 | ) 22 | print(art) 23 | 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /example/ascii-canvas/option.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Read options and arguments from command line and supply to program. 6 | 7 | Using argparse to parse options and arguments. 8 | """ 9 | 10 | import argparse 11 | 12 | VERSION = "v1.0.0 (2017-10-03)" 13 | 14 | 15 | def parse_options(): 16 | """Parse command line options/arguments and return them as a dictionary.""" 17 | parser = argparse.ArgumentParser( 18 | description="Make an ascii painting." 19 | ) 20 | parser.add_argument( 21 | "-v", "--version", 22 | action="version", 23 | version=VERSION 24 | ) 25 | parser.add_argument( 26 | "-s", "--silent", 27 | action="store_true", 28 | help="be more silent." 29 | ) 30 | parser.add_argument( 31 | "--verbose", 32 | action="store_true", 33 | help="be more verbose." 34 | ) 35 | parser.add_argument( 36 | "filename", 37 | help="path to JSON configuration file." 38 | ) 39 | 40 | return vars(parser.parse_args()) 41 | 42 | 43 | if __name__ == "__main__": 44 | pass 45 | -------------------------------------------------------------------------------- /example/avatar-today/file/avatar/garfield.txt: -------------------------------------------------------------------------------- 1 | -- -- 2 | .:" | .:'" | 3 | -- ___ ___ - 4 | /:. / . \ / . \ .\ 5 | |:|. ;\___/O\___/ :| 6 | |:|. | `__|__' | .| 7 | |:|. \_, ,_/ / 8 | \______ |__/ 9 | |:. \ 10 | /.:,| | \ 11 | /.:,.| | \ 12 | |::.. \_;_\-; | 13 | _____|::.. .::| | 14 | / ----, .::/__, /__, 15 | \_______|,...____;_;_|../_;_| 16 | -------------------------------------------------------------------------------- /example/avatar-today/file/avatar/miss_muppet.txt: -------------------------------------------------------------------------------- 1 | / '. .' \ 2 | | |`\ \,,,/ /`| | 3 | \.;;;;;-;;;;;./ 4 | .;;;;-'"'"'-;;;;, 5 | ;;.-(((( ))))-.;; 6 | ,;;/ =/_o/___\o_\= \;;, 7 | ,;;;/ .-' '-. \;;;, 8 | ,;;;;/ / \ \;;;;, 9 | ,;;;;| \ \ / / |;;;;, 10 | ;;;;;\ /-`.__.__.`-\ /;;;;; 11 | ;;;;;\ ` \.-./ ` /;;;;; 12 | ;;;;;;-._ , '-' , _.-;;;;;; 13 | ';;;;/()`'-'-=-'-'`()\;;;;' 14 | jgs `/`\ '()()()()()() /`\` 15 | -------------------------------------------------------------------------------- /example/avatar-today/file/avatar/muppet.txt: -------------------------------------------------------------------------------- 1 | .---. .---. 2 | ( -o- )---( -o- ) 3 | ;-...-` `-...-; 4 | / \ 5 | / \ 6 | | /_ _\ | 7 | \`'.`'"--.....--"'`.'`/ 8 | \ '. `._.` .' / 9 | _.-''. `-.,___,.-` .''-._ 10 | `--._ `'-._______.-'` _.--` 11 | jgs / \ 12 | /.-'`\ .'. /`'-.\ 13 | ` '.' '.' 14 | -------------------------------------------------------------------------------- /example/avatar-today/file/avatar/piglet.txt: -------------------------------------------------------------------------------- 1 | ooooo oo 2 | $o"o$"o o$$o$ 3 | "$ $ $"o o"$o $"o 4 | $"o"o"$o o"$ $ $o$ 5 | $"o"o$o$oooo$"o"o"o"o$ 6 | ""o" o "o $$ $"o""$ 7 | $o$ o ""o$ $o$" 8 | o " "o "o """$" 9 | o o$$"o"oo"" "o$" 10 | " $$ $ o"" o"oo" 11 | " """$ o " o o" 12 | "o """" o "o$ 13 | oo $ooo "o o$$$ 14 | o o" o$$$o$o$o$$$$ "o 15 | o " " $o$$$$$$$$$$$$$o o 16 | " o o"$o$$$$$$$$$$$$$$$$ " "o 17 | o" o o o"o"$$$$$$$$$$$$$$$$o$ o o 18 | o o o"o$" $$$$$$$$$$$$$$$$$$o$ o " 19 | o "o"o" $$$$$$$$$$$$$o$$$$$ "$ $ $ 20 | "$o$" $$$$$$$$$$$"$$$$$$$$ "o$ oo 21 | $$$$$$$$$$$$$$$$$$$$" "$o" 22 | $$$$$$$$$$"$$$$$$$$$ 23 | $$$$$$$$$$$$$$$$$$" 24 | $$$$$$"$$$$$$$$" 25 | "$$$$$$$$$$$$ 26 | o $"""""oo" o o 27 | o"o" " ""o"o" o o 28 | o"o"o o "o$"oo $ $" 29 | "" "" "" 30 | -------------------------------------------------------------------------------- /example/avatar-today/file/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Print out the avatar of today. 6 | 7 | This example shows how to work with a main-function together 8 | with own defined functions that reside in a own defined module. 9 | """ 10 | 11 | import avatar 12 | 13 | 14 | if __name__ == '__main__': 15 | print(__doc__) 16 | print(avatar.today()) 17 | -------------------------------------------------------------------------------- /example/avatar-today/list/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Print out the avatar of today. 6 | 7 | This example shows how to work with a main-function together 8 | with own defined functions that reside in a own defined module. 9 | """ 10 | 11 | import avatar 12 | 13 | 14 | if __name__ == '__main__': 15 | print(__doc__) 16 | print(avatar.today()) 17 | -------------------------------------------------------------------------------- /example/avatar-today/no-list/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Print out the avatar of today. 6 | 7 | This example shows how to work with a main-function together 8 | with own defined functions that reside in a own defined module. 9 | """ 10 | 11 | import avatar 12 | 13 | 14 | if __name__ == '__main__': 15 | print(__doc__) 16 | print(avatar.today()) 17 | -------------------------------------------------------------------------------- /example/cgi/execute-another-file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Execute a .py-file that has the same filename as this file. 6 | A file hello.cgi will execute the file hello.py and wrap its 7 | output with a HTTP header to be able to display the output as 8 | a webpage. 9 | 10 | """ 11 | 12 | print(""" 13 | Executing code and printing some nice message. 14 | """) 15 | -------------------------------------------------------------------------------- /example/cgi/hello-web.cgi: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Execute as cgi-skript and send a correct HTTP header. 6 | 7 | """ 8 | 9 | 10 | # To write pagecontent to sys.stdout as bytes instead of string 11 | import sys 12 | import codecs 13 | 14 | 15 | # Enable debugging of cgi-.scripts 16 | import cgitb 17 | cgitb.enable() 18 | 19 | 20 | 21 | # Send the HTTP header for plain text or for html 22 | print("Content-Type: text/plain;charset=utf-8") 23 | #print("Content-Type: text/html;charset=utf-8") 24 | print("") 25 | 26 | 27 | # Here comes the content of the webpage 28 | content = """ 29 | Hello The World of Web 30 | """ 31 | 32 | 33 | # Write page content 34 | sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) 35 | sys.stdout.write(content) 36 | -------------------------------------------------------------------------------- /example/cli/print-opt-arg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Print out the options and arguments. 6 | """ 7 | 8 | 9 | import sys 10 | import getopt 11 | 12 | 13 | opts, args = getopt.getopt(sys.argv[1:], "hv", [ 14 | "help", 15 | "version" 16 | ]) 17 | 18 | 19 | print(f"Number of options: {len(opts)}") 20 | print(f"Number of arguments: {len(args)}") 21 | 22 | print(opts) 23 | print(args) 24 | -------------------------------------------------------------------------------- /example/cmd/dice/dice.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example on a class rolling dices. 6 | 7 | """ 8 | 9 | import random 10 | 11 | 12 | class Dice(): 13 | """ 14 | Example of dice class. 15 | """ 16 | faces = 6 17 | 18 | 19 | def __init__(self): 20 | random.seed() 21 | self.rollsMade = 0 22 | 23 | 24 | def roll(self): 25 | """ 26 | Roll a dice once and return the value. 27 | """ 28 | self.rollsMade += 1 29 | return random.randint(1, self.faces) 30 | 31 | 32 | def getRollsMade(self): 33 | """ 34 | Get number of rolls made. 35 | """ 36 | return self.rollsMade 37 | -------------------------------------------------------------------------------- /example/cmd/dice/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Roll a dice and see how it turns out. 6 | 7 | This is sample code on how to use classes together with the 8 | cmd-module to quickly create small CLI applications. 9 | 10 | There is a class for the shell, that has callbacks for each commands. 11 | That class is following a structure that the cmd-module expects. 12 | 13 | There is a class representing the Dice. Just to act as a Dice. 14 | 15 | The command module: 16 | https://docs.python.org/3/library/cmd.html 17 | 18 | """ 19 | 20 | import diceshell 21 | 22 | 23 | if __name__ == '__main__': 24 | print(__doc__) 25 | diceshell.Shell().cmdloop() 26 | -------------------------------------------------------------------------------- /example/curses/readstring.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Show off how to read string from keyboard when in curses. 6 | """ 7 | 8 | import curses 9 | 10 | 11 | def main(scr): 12 | """ 13 | Enter a string, while echoing to the window. Press enter and the string is echoed to the 14 | screen. Press a character to exit the program while the string being returned and printed 15 | by the caller. 16 | """ 17 | 18 | # Clear the screen of any output 19 | scr.clear() 20 | 21 | # Draw a border 22 | scr.border() 23 | 24 | # Move cursor to center 25 | scr.move(1, 1) 26 | 27 | # Refresh to draw out 28 | scr.refresh() 29 | 30 | # Get a string from the user 31 | curses.echo() 32 | msg = scr.getstr() 33 | scr.move(2, 2) 34 | scr.addstr(msg) 35 | scr.refresh() 36 | 37 | # Wait for user input. 38 | scr.getch() 39 | return msg 40 | 41 | 42 | if __name__ == "__main__": 43 | print(__doc__) 44 | print(main.__doc__) 45 | input("Press enter to begin playing...") 46 | res = curses.wrapper(main) 47 | print(res) 48 | -------------------------------------------------------------------------------- /example/debugger/functions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example script showing definition and usage of functions in python. 6 | For the article Funktioner, parametrar och returvärden. 7 | """ 8 | 9 | def calculate_energy_return(time_in_microwave, effect=800): 10 | """ 11 | Calculates the energy consumption i kWh 12 | Returns the consumption 13 | """ 14 | energy = effect * time_in_microwave / 1000 15 | return energy 16 | 17 | def calculate_cost(energy, price_p_kwh=78.04): 18 | """ 19 | Calculates the cost for a given energy consumption 20 | Returns the cost in kr 21 | """ 22 | cost = energy * price_p_kwh / 100 23 | return cost 24 | 25 | emil_time = 2.5 / 60 26 | emil_energy = calculate_energy_return(emil_time) 27 | emil_cost = calculate_cost(emil_energy) 28 | 29 | print("Emil använder " + str(emil_energy) + " kWh och detta kostar " + str(emil_cost) + " kr") 30 | 31 | nice_string = f"Emil använder {emil_energy:.4f} kWh och detta kostar {emil_cost:.4f} kr" 32 | print(nice_string) 33 | -------------------------------------------------------------------------------- /example/debugger/if.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example script showing usage of if-statements for article 6 | Villkor och loopar 7 | """ 8 | 9 | 10 | number_of_apples = 9 11 | 12 | if number_of_apples > 10: 13 | print("Du har mer än 10 äpplen") 14 | elif 5 < number_of_apples <= 10: 15 | print("Du blev snabbt mätt och åt bara upp några av dina äpplen") 16 | else: 17 | print("Du har nog varit hungrig och ätit upp dina äpplen") 18 | 19 | # 20 | # 21 | # type_of_fruit = "päron" 22 | # number_of_fruits = 13 23 | # 24 | # if number_of_fruits > 10: 25 | # if type_of_fruit == "äpple": 26 | # print("Du har mer än 10 äpplen") 27 | # else: 28 | # print("Du har mer än 10 frukter") 29 | -------------------------------------------------------------------------------- /example/debugger/while.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example script showing usage of while-loop for article 6 | Villkor och loopar 7 | """ 8 | 9 | while True: 10 | user_input = input("Skriv in antal äpplen (eller q för avslut): ") 11 | if user_input == "q": 12 | print("Du är nu klar med att äta äpplen.") 13 | print("Hej då!") 14 | break 15 | else: 16 | try: 17 | number_of_apples = int(user_input) 18 | except ValueError: 19 | print("Oj! Du skrev inte in en siffra.") 20 | continue 21 | 22 | if number_of_apples > 10: 23 | print("Du har mer än 10 äpplen") 24 | elif 5 < number_of_apples <= 10: 25 | print("Du blev snabbt mätt och åt bara upp några av dina äpplen") 26 | else: 27 | print("Du har nog varit hungrig och ätit upp dina äpplen") 28 | -------------------------------------------------------------------------------- /example/encoding/encoding.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Check and verify locale settings to see if UTF-8 is output correctly. 5 | """ 6 | 7 | import sys 8 | import locale 9 | import os 10 | 11 | print("Default encoding is (sys.getdefaultencoding()): ", sys.getdefaultencoding()) 12 | print("(sys.stdin.encoding): ", sys.stdin.encoding) 13 | print("(sys.stdout.encoding): ", sys.stdout.encoding) 14 | print("(sys.stderr.encoding): ", sys.stderr.encoding) 15 | 16 | print("Default locale is (locale.getdefaultlocale()): ", locale.getdefaultlocale()) 17 | 18 | print("Environment variable PYTHONIOENCODING: ", os.environ.get("PYTHONIOENCODING")) 19 | print("Environment variable LANG: ", os.environ.get("LANG")) 20 | print("Environment variable LC_CTYPE: ", os.environ.get("LC_CTYPE")) 21 | 22 | print("The letters alpha, beta, gamma: \u03b1\u03b2\u03b3") 23 | -------------------------------------------------------------------------------- /example/encoding/save_to_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Save UTF to JSON file and then read it. 6 | """ 7 | 8 | import json 9 | 10 | 11 | if __name__ == '__main__': 12 | print(__doc__) 13 | 14 | filename = "data.json" 15 | data = {"name": "Åsa Äppelöstad"} 16 | 17 | with open(filename, "w", encoding="utf-8") as f: 18 | json.dump(data, f, ensure_ascii=False) 19 | print(f"Saved UTF-8 characters to file: '{filename}'.") 20 | 21 | with open(filename, "r", encoding="utf-8") as f: 22 | dataRead = json.load(f) 23 | print(f"Loaded file '{filename}'.") 24 | print(dataRead) 25 | -------------------------------------------------------------------------------- /example/encoding/test_input.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Originated from a forumpost: 6 | http://dbwebb.se/forum/posting.php?mode=reply&f=44&t=4552 7 | 8 | On Cygwin doing backspace of an utf-8 character such as 'ö' will fail with 9 | error message: 10 | 11 | $ python3 test_input.py 12 | --> 13 | Traceback (most recent call last): 14 | File "p.py", line 8, in 15 | a = input("-->") 16 | UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 0: 17 | unexpected end of data 18 | 19 | """ 20 | 21 | a = input("-->") 22 | 23 | print(repr(a)) 24 | -------------------------------------------------------------------------------- /example/excel/README.md: -------------------------------------------------------------------------------- 1 | Python to Excel 2 | ================ 3 | 4 | This example scripts is written by Felix Khoi and will go over how you can write from Python to Excel. 5 | 6 | The example will contain two versions, one simple and one more advanced. 7 | In the simple one you will have to manually write code to write to Excel, it just contains a example of how you do it. 8 | The more advanced script will show a user dialog where it lets the user select excel-file, date, hours and project. 9 | 10 | OpenPyXL 11 | =========== 12 | 13 | The script uses the import [OpenPyXL](https://openpyxl.readthedocs.org/en/default/). 14 | -------------------------------------------------------------------------------- /example/file/list/items.txt: -------------------------------------------------------------------------------- 1 | cookie 2 | cake 3 | tea 4 | -------------------------------------------------------------------------------- /example/file/list/list-to-file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Example of how to read the content of a file into a list 4 | """ 5 | 6 | # the name of the file 7 | filename = "items.txt" 8 | 9 | # with - as for reading a file automatically closes it after reading is done 10 | with open(filename) as filehandle: 11 | items_as_list = filehandle.readlines() 12 | 13 | # print what the list looks like 14 | print(items_as_list) 15 | 16 | 17 | 18 | # add item to the list 19 | items_as_list.append("cup") 20 | # print what the list looks like after change 21 | print(items_as_list) 22 | 23 | 24 | # join the list into a string with a comma ","" between every item 25 | list_as_str = ",".join(items_as_list) 26 | # show what the string looks like after join 27 | print(list_as_str) 28 | 29 | 30 | # write the line to the file 31 | with open(filename, "w") as filehandle: 32 | filehandle.write(list_as_str) 33 | -------------------------------------------------------------------------------- /example/file/string/items.txt: -------------------------------------------------------------------------------- 1 | cookie 2 | cake 3 | tea -------------------------------------------------------------------------------- /example/flow/for.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example script showing usage of for-loop for article 6 | Villkor och loopar 7 | """ 8 | 9 | for i in range(10): 10 | print(i) 11 | 12 | 13 | for number_of_apples in range(3, 15): 14 | if number_of_apples > 10: 15 | print("Du har mer än 10 äpplen") 16 | elif 5 < number_of_apples <= 10: 17 | print("Du blev snabbt mätt och åt bara upp några av dina äpplen") 18 | else: 19 | print("Du har nog varit hungrig och ätit upp dina äpplen") 20 | 21 | 22 | for _ in range(5): 23 | print("python är ett spännande programmeringsspråk") 24 | 25 | 26 | for letter in "räksmörgås": 27 | if letter in "åäö": 28 | print(letter) 29 | -------------------------------------------------------------------------------- /example/flow/if.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example script showing usage of if-statements for article 6 | Villkor och loopar 7 | """ 8 | 9 | 10 | number_of_apples = 13 11 | 12 | if number_of_apples > 10: 13 | print("Du har mer än 10 äpplen") 14 | 15 | 16 | number_of_apples = 9 17 | 18 | if number_of_apples > 10: 19 | print("Du har mer än 10 äpplen") 20 | else: 21 | print("Du har nog varit hungrig och ätit upp dina äpplen") 22 | 23 | 24 | number_of_apples = 9 25 | 26 | if number_of_apples > 10: 27 | print("Du har mer än 10 äpplen") 28 | elif 5 < number_of_apples <= 10: 29 | print("Du blev snabbt mätt och åt bara upp några av dina äpplen") 30 | else: 31 | print("Du har nog varit hungrig och ätit upp dina äpplen") 32 | 33 | 34 | type_of_fruit = "päron" 35 | number_of_fruits = 13 36 | 37 | if number_of_fruits > 10: 38 | if type_of_fruit == "äpple": 39 | print("Du har mer än 10 äpplen") 40 | else: 41 | print("Du har mer än 10 frukter") 42 | -------------------------------------------------------------------------------- /example/flow/while.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example script showing usage of while-loop for article 6 | Villkor och loopar 7 | """ 8 | 9 | number = 2 10 | 11 | while number < 20: 12 | print(number) 13 | number = number + number 14 | 15 | 16 | while True: 17 | user_input = input("Skriv in antal äpplen (eller q för avslut): ") 18 | if user_input == "q": 19 | print("Du är nu klar med att äta äpplen.") 20 | print("Hej då!") 21 | break 22 | else: 23 | try: 24 | number_of_apples = int(user_input) 25 | except ValueError: 26 | print("Oj! Du skrev inte in en siffra.") 27 | continue 28 | 29 | if number_of_apples > 10: 30 | print("Du har mer än 10 äpplen") 31 | elif 5 < number_of_apples <= 10: 32 | print("Du blev snabbt mätt och åt bara upp några av dina äpplen") 33 | else: 34 | print("Du har nog varit hungrig och ätit upp dina äpplen") 35 | -------------------------------------------------------------------------------- /example/functions/energy/energy_calculation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Functions used to calculate energy consumption and cost 3 | """ 4 | 5 | def calculate_energy(time_in_microwave, effect=800): 6 | """ 7 | Calculates the energy consumption i kWh 8 | Returns the consumption 9 | """ 10 | energy = effect * time_in_microwave / 1000 11 | return energy 12 | 13 | def calculate_cost(energy, price_per_kwh=78.04): 14 | """ 15 | Calculates the cost for a given energy consumption 16 | Returns the cost in kr 17 | """ 18 | cost = energy * price_per_kwh / 100 19 | return cost 20 | 21 | if __name__ == "__main__": 22 | print("Test av calculate energy:") 23 | print(calculate_energy(800)) 24 | print("name: " + __name__) 25 | -------------------------------------------------------------------------------- /example/functions/sandwich.py: -------------------------------------------------------------------------------- 1 | """ 2 | Functions used to format strings from lists. 3 | """ 4 | 5 | def create_sandwich_string(ingredients, presentation="Prova vår sandwich som innehåller"): 6 | """ 7 | Takes a presentation string and concatenates it with a list 8 | that is comma separated, last element has an "och" before insted of ",". 9 | """ 10 | number_of_ingredients = len(ingredients) 11 | if number_of_ingredients == 1: 12 | return f"{presentation} {ingredients[0]}." 13 | 14 | return f"{presentation} {', '.join(ingredients[:-1])} och {ingredients[-1]}." 15 | 16 | if __name__ == "__main__": 17 | print("Testar vår nya modul:") 18 | print(create_sandwich_string(["ost"]) == "Prova vår sandwich som innehåller ost.") 19 | print("name: " + __name__) 20 | -------------------------------------------------------------------------------- /example/functions/waysub.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example code for modules v2. 6 | """ 7 | 8 | import sandwich as s 9 | 10 | ingredients = ["ost", "bacon", "sallad", "majonnäs"] 11 | ingredients_string = s.create_sandwich_string(ingredients, "En BLT innehåller") 12 | print(ingredients_string) 13 | -------------------------------------------------------------------------------- /example/getopt/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Main cli-program, to start it all up by reading command line 6 | options and arguments and the executing whats to be executed. 7 | 8 | See usage.py for details how to use program. 9 | >>> import usage 10 | >>> help(usage) 11 | 12 | or 13 | 14 | $ pydoc usage 15 | 16 | """ 17 | 18 | import sys 19 | import usage 20 | 21 | 22 | def main(): 23 | """ 24 | Main function where it all starts. 25 | """ 26 | usage.parse_options() 27 | 28 | print("Default options:") 29 | print(usage.default_options) 30 | 31 | print("Active options:") 32 | print(usage.options) 33 | print() 34 | 35 | sys.exit() 36 | 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /example/greeting/greeting.py: -------------------------------------------------------------------------------- 1 | """ 2 | Programmet skriver tar namn och ålder som input från användaren. 3 | Värdena användaren skriver in används för att skapa en hälsning med namn, ålder och födelse år. 4 | """ 5 | 6 | year = 2017 # Hårdkodat värde för vilket år det är 7 | 8 | name = input("Skriv ett namn, klicka sen enter: ") # Ber användaren mata in ett namn 9 | age = input("Skriv en ålder, klicka sen enter: ") # Ber användaren mata in en ålder 10 | 11 | year_born = str(year - int(age)) # Födelse år räknas ut. Gör om age från string till integer med int() 12 | 13 | 14 | # Sätter ihop "Hej", name, ", du är ", age och " år gammal." till ett värde. 15 | greeting = "Hej " + name + ", du är " + age + " år gammal och föddes år " + year_born 16 | print(greeting) # Skriver ut ett string värde 17 | -------------------------------------------------------------------------------- /example/hello/hello-fel.py_: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Showing off som errors in Python. 6 | """ 7 | 8 | # Print out Hello World 9 | prin("Just saying Hello World") 10 | 11 | # Assign the string Hello World to a variable and print it out 12 | str1 = "Hello World in a variable" 13 | print(str2) 14 | 15 | # Combine two strings and print them out 16 | str2 = "Hello World!" 17 | str3 = "Its a nice day today!" 18 | print(str2 + " " + str4) 19 | 20 | # Combine string and values 21 | a = 40 22 | b = 2 23 | c = a + b 24 | str4 = "Summan är " + c + "." 25 | print(str2 + " " + str4) 26 | -------------------------------------------------------------------------------- /example/hello/hello.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Some various ways of saying Hello World in Python. 6 | """ 7 | 8 | # Print out Hello World 9 | print("Just saying Hello World") 10 | 11 | # Assign the string Hello World to a variable and print it out 12 | str1 = "Hello World in a variable" 13 | print(str1) 14 | 15 | # Combine two strings and print them out 16 | str2 = "Hello World!" 17 | str3 = "Its a nice day today!" 18 | print(str2 + " " + str3) 19 | 20 | # Combine string and values 21 | a = 40 22 | b = 2 23 | c = a + b 24 | str4 = "Summan är " + str(c) + "." 25 | print(str2 + " " + str4) 26 | -------------------------------------------------------------------------------- /example/hello_world/hello.cgi: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Some various ways of saying Hello World in Python 6 | Execute as cgi-skript and send a correct HTTP header. 7 | 8 | """ 9 | 10 | # Enable debugging of cgi-.scripts 11 | import cgitb 12 | cgitb.enable() 13 | 14 | 15 | 16 | # Define a function 17 | def hello(): 18 | """ 19 | Print out Hello World in a function. 20 | """ 21 | print("Hello World in a function.") 22 | 23 | 24 | 25 | # Send the HTTP header 26 | print("Content-Type: text/plain;charset=utf-8") 27 | #print("Content-Type: text/html;charset=utf-8") 28 | print("") 29 | 30 | 31 | 32 | # Here comes the content of the webpage 33 | 34 | # Call a function that prints out Hello World 35 | hello() 36 | 37 | # Print out Hello World 38 | print("Just saying Hello World") 39 | 40 | # Assign the string Hello World to a variable and print it out 41 | #str = "Hello World in a variable" 42 | #print(str) 43 | str1 = "Hello World in a variable" 44 | print(str1) 45 | -------------------------------------------------------------------------------- /example/hello_world/hello.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Some various ways of saying Hello World in Python. 6 | """ 7 | 8 | def hello(): 9 | """ 10 | Print out Hello World in a function. 11 | """ 12 | print("Hello World in a function.") 13 | 14 | 15 | # Call a function that prints out Hello World 16 | hello() 17 | 18 | # Print out Hello World 19 | print("Just saying Hello World") 20 | 21 | # Assign the string Hello World to a variable and print it out 22 | #str = "Hello World in a variable" 23 | #print(str) 24 | str1 = "Hello World in a variable" 25 | print(str1) 26 | -------------------------------------------------------------------------------- /example/hello_world/hw_commands.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example to just print out something 3 | """ 4 | 5 | print("\nHello Word\n") 6 | -------------------------------------------------------------------------------- /example/hello_world/hw_function.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | A function to say Hello, just to show off how functions and docstrings works. 6 | 7 | Use it like this. 8 | 9 | >>> import hw_function as hw 10 | >>> help(hw) 11 | >>> hw.say_it.__doc__ 12 | >>> hw.__doc__ 13 | 14 | Also try pydoc like this in the terminal: 15 | 16 | pydoc sys 17 | 18 | """ 19 | 20 | 21 | def say_it(): 22 | """ 23 | Just sayin to the world that we are here and now know python. 24 | 25 | Ths function is currently defined in a module named __name__. 26 | """ 27 | print(f"\nHello World in module {__name__}\n") 28 | -------------------------------------------------------------------------------- /example/hello_world/hw_main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Calling the function what says hello from a main-method and using docstrings 6 | to document it all. Showing how to import a file (module) with an external 7 | function. 8 | 9 | Import it and run it by calling the main function or run it as a script. 10 | 11 | 1) In the python interpreter 12 | 13 | >>> import hw_main as hw 14 | >>> hw.main() 15 | 16 | 17 | 2) In the shell 18 | 19 | $ python3 hw_main.py 20 | 21 | 22 | 3) Make it executable and just run it. 23 | 24 | $ chmod 755 hw_main.py 25 | $ ./hw_main.py 26 | 27 | """ 28 | 29 | import hw_function as hw 30 | 31 | 32 | def main(): 33 | """ 34 | This is the main method, I call it main by convention. 35 | """ 36 | print(hw.say_it.__doc__) 37 | hw.say_it() 38 | 39 | 40 | if __name__ == "__main__": 41 | print(main.__doc__) 42 | main() 43 | -------------------------------------------------------------------------------- /example/hello_world/hw_script.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Just print out a line of hello. 6 | """ 7 | 8 | print("\nHello Word\n") 9 | -------------------------------------------------------------------------------- /example/image/mos.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbwebb-se/python/ee7c85cfd6db49592b98fe5b1126a40e9b4d6a6a/example/image/mos.jpg -------------------------------------------------------------------------------- /example/json/json.txt: -------------------------------------------------------------------------------- 1 | { 2 | "colorsArray": [ 3 | { 4 | "hexValue": "#f00", 5 | "colorName": "red" 6 | }, 7 | { 8 | "hexValue": "#0f0", 9 | "colorName": "green" 10 | }, 11 | { 12 | "hexValue": "#00f", 13 | "colorName": "blue" 14 | }, 15 | { 16 | "hexValue": "#0ff", 17 | "colorName": "cyan" 18 | }, 19 | { 20 | "hexValue": "#f0f", 21 | "colorName": "magenta" 22 | }, 23 | { 24 | "hexValue": "#ff0", 25 | "colorName": "yellow" 26 | }, 27 | { 28 | "hexValue": "#000", 29 | "colorName": "black" 30 | }, 31 | { 32 | "hexValue": "#f0f", 33 | "colorName": "purple" 34 | }, 35 | { 36 | "hexValue": "#f9f", 37 | "colorName": "pink" 38 | } 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /example/lecture_prep/.dbwebb/correct.bash: -------------------------------------------------------------------------------- 1 | dbwebb test lecture_prep -------------------------------------------------------------------------------- /example/lecture_prep/exam.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Write your code in this file. Fill out the defined functions with your solutions. 4 | You are free to write additional functions and modules as you see fit. 5 | """ 6 | 7 | def analyze_text(): 8 | """ 9 | Assignment 1 10 | """ 11 | return True 12 | 13 | def verify_hex(hex_value): 14 | """ 15 | Assignment 2 16 | """ 17 | return hex_value 18 | 19 | 20 | 21 | if __name__ == '__main__': 22 | analyze_text() 23 | verify_hex("") 24 | -------------------------------------------------------------------------------- /example/lecture_prep/solutions/ht19/advanced.py: -------------------------------------------------------------------------------- 1 | """ 2 | Advanced python constructions 3 | """ 4 | # List comprehension 5 | ll = [] 6 | for i in range(0, 10): 7 | ll.append(i) 8 | print(ll) 9 | ll = [i for i in range(0, 10)] 10 | print(ll) 11 | # Dict comrehension with and if-case 12 | ll = {i:i*2 for i in range(0, 10) if i % 2} 13 | print(ll) 14 | 15 | # Generator with yield 16 | def f(): 17 | """ 18 | Yield example 19 | """ 20 | print("start") 21 | yield 1 22 | print("middle") 23 | yield 2 24 | print("middle 2") 25 | yield 3 26 | print("end") 27 | 28 | # Loop over generator 29 | for value in f(): 30 | print(value) 31 | # generator = f() 32 | # print(next(generator)) 33 | # print(next(generator)) 34 | # print(next(generator)) 35 | # print(next(generator)) 36 | -------------------------------------------------------------------------------- /example/lecture_prep/solutions/ht19/analyze_functions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Analyzes myths.txt 3 | """ 4 | 5 | def read_file_and_split_on_paragraphs(): 6 | """ 7 | Reads file and splits on paragraphs 8 | """ 9 | with open("myths.txt") as fh: 10 | for row in fh.read().split("\n\n"): 11 | yield row 12 | 13 | def top_3(high_score): 14 | """ 15 | Prints top 3 16 | """ 17 | print("\n".join([str(score) for score in sorted(high_score, reverse=True)[0:3]])) 18 | 19 | def sentences(): 20 | """ 21 | Counts sentences in paragraphs 22 | """ 23 | high_score = [row.count(".") for row in read_file_and_split_on_paragraphs()] 24 | top_3(high_score) 25 | 26 | 27 | 28 | def gods(): 29 | """ 30 | Counts the gods in each paragraph 31 | """ 32 | all_gods = [ 33 | "Odin", "Thor", "Hödur", "Baldur", "Tyr", 34 | "Heimdall", "Vidar", "Vali", "Loki", "Frigga", 35 | "Freya", "Nanna", "Iduna", "Sif", "Modi", "Magni" 36 | ] 37 | 38 | top_3([sum([paragraph.count(god) for god in all_gods])\ 39 | for paragraph in read_file_and_split_on_paragraphs()]) 40 | -------------------------------------------------------------------------------- /example/lecture_prep/solutions/ht21/test.py: -------------------------------------------------------------------------------- 1 | """ 2 | Hur generatorer och yield fungerar 3 | """ 4 | def f(): 5 | """ 6 | En generator 7 | """ 8 | print("inne i funktion") 9 | # print("inne 1") 10 | # yield 1 11 | # print("inne 2") 12 | # yield "hej" 13 | # print("inne 3") 14 | # yield 3 15 | # print("inne 4") 16 | # yield 4 17 | for v in [1,3,5,6,87,8,8]: 18 | yield str(v) 19 | 20 | generator = f() 21 | for value in generator: 22 | print("ute" + value) 23 | # print(generator) 24 | # print( 25 | # next(generator) 26 | # ) 27 | # print( 28 | # next(generator) 29 | # ) 30 | # print( 31 | # next(generator) 32 | # ) 33 | # print( 34 | # next(generator) 35 | # ) 36 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom01/cost_of_candy.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calculates the remainder after splurging 3 | on candy 4 | """ 5 | 6 | allowance = input("What is your allowance? ") 7 | cost_of_candy = input("How much candy did you buy? ") 8 | 9 | remainder = round(float(allowance) - float(cost_of_candy), 2) 10 | 11 | print("You have " + str(remainder) + " kr left") 12 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom01/money_converter.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example program of converting sek to yen 3 | """ 4 | # Skriv ett program som tar emot inmatning från användaren. Programmet ska ta emot antal svenska kronor. 5 | sek = float(input("Enter amount to convert in sek: ")) 6 | # Programmet ska sedan göra om dessa till Japanska Yen med dagens kurs: 1 SKR = 10.81 YEN. 7 | RATE = 10.81 8 | yen = sek * RATE 9 | # Programmet ska nu formaterat skriva ut hur många YEN det blir, 10 | print(str(sek) + " is " + str(yen) + "yen") 11 | # samt vad 10 och 12 | print( 13 | str(sek * 10) 14 | + " is " 15 | + str(yen * 10) 16 | + "yen" 17 | ) 18 | # 100 gånger så mycket blir. 19 | sek_converter_to_yen = ( 20 | str(sek * 100) 21 | + " is " 22 | + str(yen * 100) 23 | + "yen" 24 | ) 25 | print(sek_converter_to_yen) 26 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom01/time_converter.py: -------------------------------------------------------------------------------- 1 | """ 2 | Convert seconds to hours and seconds 3 | """ 4 | 5 | duration = int(input("Enter a duration in seconds: ")) 6 | 7 | hours = str(duration // (60*60)) 8 | seconds = str(duration % (60*60)) 9 | 10 | print(str(duration) + " seconds is " + hours + " hours and " + seconds + " seconds") 11 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/concat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Emil's stupid error, where he said to students 3 | that they should use isinstace() but solved with 4 | try-except 5 | """ 6 | 7 | long_string = "" 8 | while True: 9 | choice = input("Skriv in en sträng eller siffra: ") 10 | 11 | try: 12 | number_choice = int(choice) 13 | for _ in range(number_choice): 14 | print(long_string) 15 | long_string = "" 16 | except ValueError: 17 | long_string += choice 18 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/debugger.py: -------------------------------------------------------------------------------- 1 | """ 2 | Lets debug! 3 | """ 4 | import pdb 5 | # pylint: disable=forgotten-debug-statement 6 | variable = """ 7 | Phil played two or three times more, managing to obtain in all 8 | twenty-five cents additional. He reached the corner of Thirteenth Street 9 | just as the large public school, known as the Thirteenth Street School, 10 | was dismissed for its noon intermission.""" 11 | 12 | something = """,".:-'?""" 13 | variable = variable.lower() 14 | house = 0 15 | for lobster in variable: 16 | if lobster in something: 17 | pdb.set_trace() 18 | house += 1 19 | print(house) 20 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/debugger_assignment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find out what this program does. 3 | Start debugger with "python3 -m pdb debugger_assignment.py" 4 | or "import pdb" and "pdb.set_trace()" in the code and start program as usuall. 5 | 6 | Try running the program with both numbers 7 | """ 8 | number = "072-354 02 11" 9 | # number = "073-456 12 9a" 10 | correct = False 11 | if len(number) == 13 and number[3] == "-" and number[7] == " " and number[10] == " ": 12 | if number[0:3] in "070 072 073 076 079": 13 | n = number[4:].replace(" ", "") 14 | for c in n: 15 | if not c.isdigit(): 16 | print("Your number isnt valid") 17 | exit() 18 | print("It is a valid phone number") 19 | exit() 20 | print("Your number isn't valid") 21 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/fixed.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calc area of circle 3 | """ 4 | pii = 3.14 5 | 6 | radius = input("Enter the radius of a circle: ") 7 | 8 | area = int(radius) * int(radius) * pii 9 | 10 | print("Area of circle: " + str(area)) 11 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/flow.py: -------------------------------------------------------------------------------- 1 | """ 2 | Prints factorial for all numbers 2 to the input number 3 | """ 4 | 5 | while True: 6 | choice = input("Skriv en siffra eller 'done' för avslut: ") 7 | if choice == "done": 8 | break 9 | else: 10 | try: 11 | chosen_number = int(choice) 12 | except ValueError: 13 | print("Skriv en siffra") 14 | continue 15 | 16 | for number in range(2, chosen_number + 1): 17 | total = 1 18 | factorial_string = str(number) + "! = " 19 | while number > 0: 20 | total *= number 21 | if number > 1: 22 | factorial_string += str(number) + " * " 23 | else: 24 | factorial_string += str(number) 25 | number -= 1 26 | 27 | print(factorial_string + " = " + str(total)) 28 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/follower.py: -------------------------------------------------------------------------------- 1 | """ 2 | See which word is longer 3 | """ 4 | previous = input("Write another word: ") 5 | current = input("Write a word: ") 6 | 7 | while True: 8 | if len(current) > len(previous): 9 | print("Current word is longer") 10 | else: 11 | print("Previous word is longer") 12 | 13 | previous = current 14 | current = input("Write a word: ") 15 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/for.py: -------------------------------------------------------------------------------- 1 | """ 2 | Remove spaces from string 3 | """ 4 | message = "Python är det bästa programmeringsspråket!" 5 | end_message = "" 6 | for letter in message: 7 | if letter != " ": 8 | end_message += letter 9 | print(end_message) 10 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/gatherer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calc average of numbers 3 | """ 4 | count = 0 5 | total = 0 6 | number = 0 7 | 8 | while number != -999: 9 | number = int(input("Enter a number, -999 to quit: ")) 10 | if number != -999: 11 | total += number 12 | count += 1 13 | 14 | if count: 15 | print("Average", total / count) 16 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/if.py: -------------------------------------------------------------------------------- 1 | """ 2 | Nested if cases 3 | """ 4 | number_one = int(input("Siffra 1: ")) 5 | number_two = int(input("Siffra 2: ")) 6 | 7 | message = "Rejected" 8 | 9 | if 10 < number_one < 100: 10 | if 10 < number_two < 100: 11 | if number_one < 50 or number_two < 50: 12 | if number_two > 40 or number_two > 40: 13 | message = "Approved" 14 | 15 | print(message) 16 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/oneway.py: -------------------------------------------------------------------------------- 1 | """ 2 | A simple while-loop 3 | """ 4 | loop = True 5 | 6 | while loop: 7 | word = input("A word: ") 8 | 9 | if "e" in word: 10 | loop = False 11 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/recent.py: -------------------------------------------------------------------------------- 1 | """ 2 | Loop over characters in string 3 | """ 4 | word = "Elephant" 5 | 6 | for letter in word: 7 | print(letter) 8 | 9 | # print(letter) # validator complains on using loop variable outside loop 10 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/savings_calculator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calculate interset on savings 3 | """ 4 | # Skriv ett program som räknar på sparande. 5 | # ta emot tre värden: start kapital, ränta och slutvärde. 6 | start = float(input("Enter starting capital: ")) 7 | rate = float(input("Enter interest rate: ")) 8 | end_value = float(input("Enter end value: ")) 9 | # räkna ut hur många år pengarna ska stå på kontot innan vi har kommit upp i minst slutvärdet. 10 | new_value = start 11 | year = 0 12 | while new_value < end_value: 13 | new_value = new_value * (1 + rate / 100) 14 | print(new_value) 15 | year += 1 16 | print("It takes", year, "years to go from", start, "to", round(new_value, 2)) 17 | # Värdet efter 1 år med ränta kan räknas ut som: 18 | # new_value = old_value * (1 + interest / 100) 19 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/stepper.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stepper variable example 3 | """ 4 | multiplier = 1 5 | 6 | while multiplier <= 10: 7 | print(multiplier, "* 3 = ", multiplier * 3) 8 | multiplier += 1 9 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/truthiness.py: -------------------------------------------------------------------------------- 1 | """ 2 | What is True and what is False and how do we compare values? 3 | """ 4 | 5 | value1 = 0 6 | value2 = 0 7 | for i in range(1000): 8 | value1 += i 9 | for i in range(1000): 10 | value2 += i 11 | print(id(value1)) 12 | print(id(value2)) 13 | print(value1, "är lika med", value2, value1 == value2) 14 | print(value1, "is", value2, value1 is value2) 15 | 16 | # value = None 17 | # if value is None: 18 | # print("Value är inte en sträng") 19 | # elif value: 20 | # print("Icke tom sträng") 21 | # else: 22 | # value += "Inte längre tom" 23 | # print("EN tom sträng") 24 | # print(value) 25 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/validate-password.py: -------------------------------------------------------------------------------- 1 | """ 2 | Validate a password 3 | """ 4 | passwd = input("Enter a password: ") 5 | size = True 6 | 7 | if not passwd: 8 | size = False 9 | if len(passwd) > 10: 10 | size = False 11 | if size: 12 | found_digit = False 13 | for char in passwd: 14 | if char.isdigit(): 15 | found_digit = True 16 | break 17 | found_lower = False 18 | for char in passwd: 19 | if char.islower(): 20 | found_lower = True 21 | break 22 | 23 | found_upper = False 24 | for char in passwd: 25 | if char.isupper(): 26 | found_upper = True 27 | break 28 | if not found_digit or not found_lower or not found_upper: 29 | print("Your password need a digit, upper and lower") 30 | exit() 31 | else: 32 | print("Your password has incorrect size") 33 | exit() 34 | print("You have a valid password") 35 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/wanted.py: -------------------------------------------------------------------------------- 1 | """ 2 | Finds a number 3 | """ 4 | smallest = 99999 5 | 6 | while True: 7 | content = input("A number: ") 8 | if content == "q": 9 | break 10 | else: 11 | number = int(content) 12 | if number < smallest: 13 | smallest = number 14 | 15 | print(smallest) 16 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom02/while.py: -------------------------------------------------------------------------------- 1 | """ 2 | Print stars in terminal 3 | """ 4 | while True: 5 | nr_of_stars = input("Enter number of stars: ") 6 | if nr_of_stars.isdigit(): 7 | # for number in range(int(nr_of_stars)): 8 | print("*" * int(nr_of_stars)) 9 | else: 10 | break 11 | print() 12 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom03/arguments.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pets module 3 | """ 4 | 5 | def pets(species="cat", name="Kim", number_of_legs=4): 6 | """ 7 | Prints about pets 8 | """ 9 | output = "My pet is a {species} it's called {name} it has {legs} legs" 10 | print(output.format( 11 | species=species, 12 | name=name, 13 | legs=number_of_legs 14 | )) 15 | 16 | pets("dog", "Buster", 4) 17 | pets(species="parakit", number_of_legs=2) 18 | pets() 19 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom03/execution_flow.py: -------------------------------------------------------------------------------- 1 | """ 2 | Le executioner 3 | """ 4 | 5 | def f1(): 6 | """ 7 | f1 8 | """ 9 | print(3) 10 | 11 | def f2(): 12 | """ 13 | f2 14 | """ 15 | print(1) 16 | f4() 17 | 18 | def f3(): 19 | """ 20 | f3 21 | """ 22 | f2() 23 | f1() 24 | print(4) 25 | 26 | def f4(): 27 | """ 28 | f4 29 | """ 30 | print(2) 31 | 32 | 33 | f3() 34 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom03/function.py: -------------------------------------------------------------------------------- 1 | """ 2 | Introduction to functions and execution flow 3 | """ 4 | def f1(): 5 | """ 6 | print "hej" 7 | """ 8 | print("hej") 9 | 10 | def f2(): 11 | """ 12 | print "på" 13 | """ 14 | f1() 15 | print("på") 16 | f3() 17 | 18 | def f3(): 19 | """ 20 | print "dig" 21 | """ 22 | print("dig") 23 | f2() 24 | 25 | 26 | 27 | def countdown(): 28 | """ 29 | countdown from 3 to 1 30 | """ 31 | print(3) 32 | print(2) 33 | print(1) 34 | 35 | print("countdown from 3 to 1") 36 | countdown() 37 | print("Again!!!") 38 | countdown() 39 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom03/layercake.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tårta module 3 | """ 4 | def layer_cake( 5 | color="green", 6 | filling1="raspberry jam", 7 | filling2="custard", 8 | number_of_layers=3): 9 | """ 10 | Prints about our favorite layer cake 11 | """ 12 | output = "My cake is a {color} {layers} layer cake filled with {filling1} and {filling2}" 13 | print(output.format( 14 | color=color, 15 | layers=number_of_layers, 16 | filling1=filling1, 17 | filling2=filling2, 18 | )) 19 | 20 | layer_cake() 21 | layer_cake("blue") 22 | layer_cake("yellow", "blueberry jam") 23 | layer_cake("purple", "banana", "strawberries") 24 | layer_cake("purple", "banana", "strawberries", 42) 25 | layer_cake(number_of_layers=16) 26 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom03/letter_inverter.py: -------------------------------------------------------------------------------- 1 | """ 2 | Inverts dem letters 3 | """ 4 | 5 | def invert(letter): 6 | """ 7 | Change upper to lower and vice versa 8 | """ 9 | if letter.isupper(): 10 | return letter.lower() 11 | # else: 12 | return letter.upper() 13 | 14 | def take_message(): 15 | """ 16 | Change upper/lower for a message 17 | """ 18 | msg = input("Enter message: ") 19 | inverted_msg = "" 20 | for letter in msg: 21 | inverted_msg += invert(letter) 22 | print(inverted_msg) 23 | take_message() 24 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom03/numberplates.py: -------------------------------------------------------------------------------- 1 | """ 2 | Checks validity of swedish numberplates 3 | """ 4 | def is_valid_numberplate(numberplate): 5 | """ 6 | Checks validity 7 | """ 8 | valid = True 9 | 10 | if len(numberplate) != 6: 11 | valid = False 12 | 13 | if valid: 14 | if not (numberplate[0:3].isupper() and numberplate[0:3].isalpha()): 15 | valid = False 16 | if valid: 17 | for letter in numberplate[3:]: 18 | if not letter.isdigit(): 19 | valid = False 20 | break 21 | 22 | if valid: 23 | print("Nummerskylten är OK") 24 | else: 25 | print("Nummerskylten är inte OK") 26 | 27 | 28 | def take_input(): 29 | """ 30 | Takes input and sends choice to validity function 31 | """ 32 | while True: 33 | choice = input("Input numberplate or done for quit: ") 34 | 35 | if choice == "done": 36 | break 37 | else: 38 | is_valid_numberplate(choice) 39 | 40 | take_input() 41 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom03/return.py: -------------------------------------------------------------------------------- 1 | """ 2 | The difficult way to calculate 7^2 3 | """ 4 | 5 | def calc_square(a, b): 6 | """ 7 | (a+b)^2 8 | """ 9 | square = a**2 + b**2 + 2*a*b 10 | return square 11 | 12 | def calc_many_squares(): 13 | """ 14 | Squares it for many numbers 15 | """ 16 | for i in range(3): 17 | result = calc_square(i, i+1) 18 | print(result) 19 | return result 20 | 21 | calc_many_squares() 22 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom04/start/clothes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module concerned with clothes 3 | """ 4 | 5 | 6 | print("This is my name", __name__) 7 | print() 8 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom04/start/shoes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module concerned with shoes 3 | """ 4 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom04/work/clothes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module concerned with clothes 3 | """ 4 | 5 | def jeans(): 6 | """ 7 | Function that prints about relaxed footwear 8 | """ 9 | print("My workmans pants that has turned high fashion") 10 | 11 | 12 | def rain_coat(): 13 | """ 14 | Function that prints about clothes for rainy days 15 | """ 16 | print("I'm singing in the rain, because I wear a raincoat") 17 | 18 | 19 | def suit(): 20 | """ 21 | Function that prints about formal wear 22 | """ 23 | print("My name is Bond, James Bond!") 24 | 25 | # print("This is my name", __name__) 26 | # print() 27 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom04/work/main.py: -------------------------------------------------------------------------------- 1 | """ 2 | Main program that calls a lot of functions 3 | """ 4 | import shoes 5 | from clothes import jeans, rain_coat as rc, suit 6 | def galosh(): 7 | """ 8 | Function that prints about something in between 9 | """ 10 | print("Clothes or shoes, thats the question") 11 | 12 | 13 | def main(): 14 | """ 15 | Starting point of program 16 | """ 17 | print("I will now print information about shoes and clothes:") 18 | print() 19 | 20 | jeans() 21 | shoes.sneakers() 22 | rc() 23 | shoes.high_heels() 24 | galosh() 25 | shoes.slippers() 26 | suit() 27 | 28 | if __name__ == "__main__": 29 | main() 30 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom04/work/shoes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module concerned with shoes 3 | """ 4 | 5 | def sneakers(): 6 | """ 7 | Function that prints about relaxed footwear 8 | """ 9 | print("Uhhhhhhh, nice comfy feel") 10 | 11 | 12 | def high_heels(): 13 | """ 14 | Function that prints about formal footwear 15 | """ 16 | print("Ohhhhhhh, my feet hurts") 17 | 18 | def slippers(): 19 | """ 20 | Function that prints about the most relaxed footwear 21 | """ 22 | print("Ahhhhhhh, this is the best") 23 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom05/nested_loops.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sum nested loops 3 | """ 4 | list1 = [1, 2, 3, 4] 5 | list2 = [1, 2, [6, 7, 8], 5, 7, 9] 6 | list3 = [[1, 2], [6, 7, 8], [5, 7, 9], [7, 9, 13], 2] 7 | 8 | def sum_list(numbers): 9 | """ 10 | Traverse list and sum values 11 | """ 12 | total = 0 13 | print(numbers) 14 | for value in numbers: 15 | if isinstance(value, list): 16 | print(value) 17 | child_sum = 0 18 | for child_value in value: 19 | child_sum += child_value 20 | print("Child sum", child_sum) 21 | total += child_sum 22 | else: 23 | total += value 24 | print("Total", total) 25 | # sum_list(list1) 26 | # sum_list(list2) 27 | sum_list(list3) 28 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom06/movies.txt: -------------------------------------------------------------------------------- 1 | ( 2 | ("Baby Driver", “2017", “Edgar Wright"), 3 | ("Scott Pilgrim vs. the world", "2010", “Edgar Wright"), 4 | ("Thor: Ragnarok", “2017", "Taika Waititi"), 5 | (“What we do in the shadows", “2014", “Taika Waititi"), 6 | (“Tucker and Dale vs Evil", “2010", “Eli Craig"), 7 | ) 8 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom06/search_movie.py: -------------------------------------------------------------------------------- 1 | """ 2 | tuple assignment 3 | """ 4 | def search_movies(movies): 5 | """ 6 | Search for a movie 7 | """ 8 | s = input("What to search for: ") 9 | found_movies = [] 10 | for movie in movies: 11 | if s in movie: 12 | found_movies.append(movie) 13 | found_movies.sort() 14 | print(found_movies) 15 | 16 | if __name__ == "__main__": 17 | all_movies = [ 18 | ("Baby Driver", "2017", "Edgar Wright"), 19 | ("Scott Pilgrim vs. the world", "2010", "Edgar Wright"), 20 | ("Thor: Ragnarok", "2017", "Taika Waititi"), 21 | ("What we do in the shadows", "2014", "Taika Waititi"), 22 | ("Tucker and Dale vs Evil", "2010", "Eli Craig"), 23 | ] 24 | search_movies(all_movies) 25 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom06/shoe_size.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dictionary assignment 3 | """ 4 | def calculate_average_shoe_size(): 5 | """ 6 | Calculate the average shoe size of input 7 | """ 8 | info = {} 9 | while True: 10 | data = input("Enter name and shoe size: ").split(" ") 11 | if data[0] == "done": 12 | break 13 | info[data[0]] = int(data[1]) 14 | total_shoe_size = 0 15 | for person in sorted(info, key=info.get, reverse=True): 16 | total_shoe_size += info[person] 17 | print(person + ": " + str(info[person])) 18 | print(total_shoe_size / len(info)) 19 | 20 | if __name__ == "__main__": 21 | calculate_average_shoe_size() 22 | -------------------------------------------------------------------------------- /example/lectures/2019/kmom06/tuple.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tuple example 3 | """ 4 | LENGTH = 0 5 | WORD = 1 6 | def create_tuple(word): 7 | """ 8 | Make word to tuple with its length 9 | """ 10 | return (len(word), word) 11 | 12 | def sort_print(words): 13 | """ 14 | sort and print word in len order 15 | """ 16 | tuples = [] 17 | for word in words: 18 | tuples.append(create_tuple(word)) 19 | tuples.sort() 20 | pretty_print(tuples) 21 | 22 | def pretty_print(tuples): 23 | """ 24 | Make a pretty print 25 | """ 26 | for word in tuples: 27 | print(word[WORD], "has length", word[LENGTH]) 28 | if __name__ == "__main__": 29 | sort_print(["ko", "gris", "elefant", "lejon", "hund"]) 30 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom01/cost_of_candy.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calculates remaining money after buying candy 3 | 4 | Skriv ett program där du använder funktionen input() för att ta emot två värden allowance och cost_of_candy. 5 | Dra sedan cost_of_candy från allowance. Programmet ska sedan skriva ut hur mycket man har kvar efter 6 | att ha handlat godis tillsammans med strängen " kr". 7 | """ 8 | 9 | 10 | 11 | allowance = input("Vad är din månadspeng? ") 12 | 13 | cost_of_candy = input("Hur mycket har du handlat godis för? ") 14 | 15 | money_left = int(allowance) - int(cost_of_candy) 16 | 17 | print("Du har kvar " + str(money_left) + " kr") 18 | 19 | 20 | 21 | # allowance = int(input("Vad är din månadspeng? ")) 22 | # 23 | # cost_of_candy = int(input("Hur mycket har du handlat godis för? ")) 24 | # 25 | # money_left = str(allowance - cost_of_candy) 26 | # 27 | # print("Du har kvar " + money_left + " kr") 28 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom01/sec_to_hours.py: -------------------------------------------------------------------------------- 1 | """ 2 | Gör ett program där användaren kan skriva in ett antal sekunder. Konvertera sekunderna till timmar och 3 | överblivna sekunder och skriv ut resultatet. 4 | """ 5 | 6 | tot_sec = int(input("Hur mångar sekunder har du?")) 7 | 8 | hours = str(tot_sec // (60*60)) 9 | sec = str(tot_sec % (60*60)) 10 | 11 | print(str(tot_sec) + " seconds is " + hours + " hours and " + sec + " seconds") 12 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom01/sek_to_yen.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som tar emot inmatning från användaren. 3 | Programmet ska sedan göra om dessa till Japanska Yen med dagens kurs: 4 | 1 SKR = 10.81 YEN. 5 | 6 | Programmet ska nu formaterat skriva ut hur många YEN det blir, 7 | samt vad 10 och 8 | 100 gånger så mycket blir. 9 | """ 10 | RATE = 10.81 11 | 12 | sek = int(input("Skriv in sek: ")) 13 | 14 | yen = sek * RATE 15 | print(str(sek) + "kr är " + str(yen) + "yen") 16 | 17 | ten_times = sek * 10 18 | yen = ten_times * RATE 19 | 20 | print(str(ten_times) + "kr är " + str(yen) + "yen") 21 | 22 | ten_times = sek * 100 23 | yen = ten_times * RATE 24 | 25 | print(str(ten_times) + "kr är " + str(yen) + "yen") 26 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-1/for-assignment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som med hjälp av en for-loop plockar bort 3 | alla mellanslag från strängen "Python är det bästa programmeringsspråket!" 4 | 5 | När programmet är klart ska 6 | strängen bli "Pythonärdetbästaprogrammeringsspråket!" 7 | 8 | Tips. mellanslag är en egen karaktär, " ", vi kan jämföra mot. 9 | """ 10 | 11 | string = "Python är det bästa programmeringsspråket!" 12 | msg = "" 13 | for char in string: 14 | if char != " ": 15 | msg += char 16 | print(msg) 17 | 18 | 19 | # mindre bra lösning 20 | msg = "" 21 | for char in string: 22 | if char == " ": 23 | pass 24 | else: 25 | msg += char 26 | print(msg) 27 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-1/for.py: -------------------------------------------------------------------------------- 1 | """ 2 | Examples of for-loops 3 | """ 4 | for i, letter in enumerate("python snake"): 5 | print(letter, "has the position ", i) 6 | 7 | string = "" 8 | for number in "python": 9 | string = str(number) + string 10 | print(string) 11 | 12 | ROWS = 4 13 | COLS = 4 14 | for nr in range(ROWS): 15 | for nr2 in range(COLS): 16 | print("*", end="") 17 | print() 18 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-1/if-assignment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Check if input integers follow criteria 3 | """ 4 | first = int(input("Enter an integer")) 5 | second = int(input("Enter another integer")) 6 | 7 | # Non validating solution 8 | # message = "Rejected" 9 | # if (first > 10 and first < 100) and (second > 10 and second < 100): 10 | # if first < 50 or second < 50: 11 | # if first > 40 or second > 40: 12 | # message = "Approved" 13 | # 14 | # print(message) 15 | 16 | # Best solution 17 | message = "Rejected" 18 | if 10 < first < 100 and 10 < second < 100: 19 | if first < 50 or second < 50: 20 | if first > 40 or second > 40: 21 | message = "Approved" 22 | print(message) 23 | # 24 | # Less good solution 25 | # if 10 < first < 100 and 10 < second < 100: 26 | # if first < 50 or second < 50: 27 | # if first > 40 or second > 40: 28 | # print("Approved") 29 | # else: 30 | # print("Rejected") 31 | # else: 32 | # print("Rejected") 33 | # else: 34 | # print("Rejected") 35 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-1/if.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example of if-case 3 | """ 4 | nr_of_apples = 15 5 | nr_of_pears = 3 6 | 7 | correct = False 8 | if nr_of_apples > 10: 9 | print("Lots of apples") 10 | if nr_of_pears > 5: 11 | correct = True 12 | print("Lots of apples and pears") 13 | elif nr_of_apples > 5: 14 | print("lots of apples") 15 | else: 16 | print("Not many fruits") 17 | 18 | 19 | print(correct) 20 | print("After if") 21 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-1/problem.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som räknar på sparande. Programmet ska ta emot tre värden: 3 | start kapital, ränta och slutvärde. 4 | Programmet ska sedan räkna ut hur många år pengarna ska 5 | stå på kontot innan vi har kommit upp i minst slutvärdet. 6 | 7 | Värdet efter 1 år med ränta kan räknas ut som: 8 | new_value = old_value * (1 + interest / 100) 9 | 10 | Exempel: värdena 1000 i startkapital, 1200 i slutvärde och 5% ränta anges. 11 | Efter 1 år: 1000 * (1 + 5 / 100) = 1050 12 | Efter 2 år: 1050 * (1 + 5 / 100) = 1102.5 13 | Efter 3 år: 1102.5 * (1 + 5 / 100) = 1157.625 14 | Efter 4 år: 1157.625 * (1 + 5 / 100) = 1215.50625 - Dvs 4 år på kontot. 15 | """ 16 | 17 | amount_of_mouney = int(input("How much money do you have? ")) 18 | interest = int(input("What is your expected interest? ")) 19 | goal = int(input("What is your goal value? ")) 20 | 21 | years = 0 22 | while amount_of_mouney < goal: 23 | amount_of_mouney = amount_of_mouney * (1 + interest / 100) 24 | years += 1 25 | print("After", years, "years you have", round(amount_of_mouney, 5), "money") 26 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-1/string.py: -------------------------------------------------------------------------------- 1 | """ 2 | "" vs '' in strings 3 | """ 4 | string = '"I licked it, so it\'s mine"' 5 | print(string) 6 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-1/while.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example of while-loop 3 | """ 4 | total_sum = 0 5 | while True: 6 | number = int(input("Enter a number: ")) 7 | if number % 2 == 0: 8 | continue 9 | 10 | total_sum += number 11 | print("new sum is", total_sum) 12 | if total_sum > 21: 13 | break 14 | 15 | print(total_sum) 16 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-2/bacon.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find substrings 3 | """ 4 | text = ( 5 | "bacon ipsum dolor amet tail ribeye biltong leberkas pork loin short loin tenderloin tri-tip kielbasa " 6 | "sausage pancetta. Brisket short loin shoulder alcatra picanha swine cupim. Capicola ground round tri-tip, " 7 | "pancetta pastrami short loin short ribs spare ribs buffalo chuck. Pork ball tip beef ribs, " 8 | "ham hock alcatra tenderloin frankfurter spare ribs jowl tail burgdoggen t-bone prosciutto. " 9 | "Kielbasa ball tip alcatra spare ribs chuck fatback shankle hambutt hock pig pork chop strip steak landjaeger. " 10 | "Hamburger porchetta frankfurter buffalo swine tongue." 11 | ) 12 | 13 | find = input("Enther substring to find: ") 14 | 15 | for ind, letter in enumerate(text.lower()): 16 | if ind == 499: 17 | pass 18 | if letter == find[0]: 19 | found = True 20 | for ind2 in range(len(find)-1): 21 | if find[ind2+1] != text.lower()[ind+ind2+1]: 22 | found = False 23 | break 24 | if found: 25 | print(f"Found {find}, start: {ind}, stop: {ind+ind2+1}") 26 | 27 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-2/concat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som tar emot input från användaren. Beroende på inputens data typ gör en av två saker: 3 | 4 | En sträng: Konkatenera ihop med tidigare stränger. 5 | En siffra: Skriv ut den konkatenerade strängen det antal gånger, som siffran är. 6 | """ 7 | 8 | inp = "" 9 | string = "" 10 | while inp != "done": 11 | inp = input("Enter string or number: ") 12 | try: 13 | print(string * int(inp)) 14 | except ValueError: 15 | string += inp 16 | print(string) 17 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-2/debugger.py: -------------------------------------------------------------------------------- 1 | """ 2 | Lets debug! 3 | """ 4 | import pdb 5 | # pylint: disable=forgotten-debug-statement 6 | variable = """ 7 | Phil played two or three times more, managing to obtain in all 8 | twenty-five cents additional. He reached the corner of Thirteenth Street 9 | just as the large public school, known as the Thirteenth Street School, 10 | was dismissed for its noon intermission.""" 11 | 12 | something = """,".:-'?""" 13 | variable = variable.lower() 14 | house = 0 15 | for lobster in variable: 16 | if lobster in something: 17 | pdb.set_trace() 18 | house += 1 19 | print(house) 20 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-2/debugger_assignment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find out what this program does. 3 | Start debugger with "python3 -m pdb debugger_assignment.py" 4 | or "import pdb" and "pdb.set_trace()" in the code and start program as usuall. 5 | 6 | Try running the program with both numbers 7 | """ 8 | number = "072-354 02 11" 9 | # number = "073-456 12 9a" 10 | correct = False 11 | if len(number) == 13 and number[3] == "-" and number[7] == " " and number[10] == " ": 12 | if number[0:3] in "070 072 073 076 079": 13 | n = number[4:].replace(" ", "") 14 | for c in n: 15 | if not c.isdigit(): 16 | print("Your number isnt valid") 17 | exit() 18 | print("It is a valid phone number") 19 | exit() 20 | print("Your number isn't valid") 21 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-2/factorial.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calculate factorial for every number between 2 and user input. 3 | """ 4 | while True: 5 | chosen = input("Enter a number or done to exit: ") 6 | 7 | if chosen != "done": 8 | try: 9 | chosen_number = int(chosen) 10 | except ValueError: 11 | print("Enter a number!!!!") 12 | continue 13 | 14 | for number in range(2, chosen_number+1): 15 | total = 1 16 | factorial_string = str(number) + "!=" 17 | while number > 0: 18 | total *= number 19 | if number > 1: 20 | factorial_string += str(number) + " * " 21 | else: 22 | factorial_string += str(number) 23 | number -= 1 24 | print(f"{factorial_string} = {total}") 25 | else: 26 | exit() 27 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-2/password-validator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Ett giltig lösenord uppfyller följande krav: 3 | Innehåller minst en karaktärer. 4 | Innehåller max 10 karaktärerer. 5 | Innehåller minst ett heltal. Tips använd funktionen isdigit() 6 | """ 7 | password = input("Skriv in ditt lösenord: ") 8 | 9 | is_valid = False 10 | if password and len(password) < 11: 11 | for char in password: 12 | if char.isdigit(): 13 | is_valid = True 14 | break 15 | if is_valid: 16 | print("Your password is valid!") 17 | else: 18 | print("Your password is NOT valid!") 19 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom02-2/truthiness.py: -------------------------------------------------------------------------------- 1 | """ 2 | What is True and what is False and how do we compare values? 3 | """ 4 | 5 | value = 0 6 | value2 = 0 7 | for i in range(1000): 8 | value += i 9 | for i in range(1000): 10 | value2 += i 11 | print(id(value)) 12 | print(id(value2)) 13 | print(value, "equals", value, "==", value == value2) 14 | print(value, "equals", value2, "is", value is value2) 15 | 16 | # value = None 17 | # if value is None: 18 | # print("Value är inte en sträng") 19 | # elif value: 20 | # print("Icke tom sträng") 21 | # else: 22 | # value += "Inte längre tom" 23 | # print("EN tom sträng") 24 | # print(value) 25 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom03/assignment1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program för att bjuda in folk till bio. 3 | 4 | Programmet ska innehålla en lista där man kan lägga till nya människor som ska med. 5 | 6 | När användaren skriver in "done" ska programmet skriva ut följande: 7 | 8 | Alla namn i listan 9 | Vartannat namn i listan 10 | De tre sista namnen 11 | Namnen på index 2 och 3 12 | """ 13 | attende = "" 14 | attendees = [] 15 | while True: 16 | attende = input("Enter name: ") 17 | if attende == "done": 18 | break 19 | attendees.append(attende) 20 | 21 | # print("alla:") 22 | # for name in attendees: 23 | # print(name, end=", ") 24 | 25 | # for name in attendees[::2]: 26 | # print(name, end=", ") 27 | 28 | # print("vartannan") 29 | # print(", ".join(attendees[::2])) 30 | # print(*attendees[::2], sep=", ") 31 | # 32 | # print("tre sista:") 33 | # for name in attendees[-3:]: 34 | # print(name, end=", ") 35 | # 36 | # print("plats 3 och 4:") 37 | # for name in attendees[2:4]: 38 | # print(name, end=", ") 39 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom03/assignment3.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skapa en lista och fyll den men valfria siffror mellan 0 och 20. 3 | Använd sen random modulen för att slumpa fram två tal mellan 0 och 20. 4 | 5 | Använd .index() funktionen på din lista för att kolla om talen finns som värden i listan. 6 | Om de gör det byt plats på dem, annars skriv ut vilket/vilka av talen som inte finns i listan. 7 | """ 8 | import random 9 | l = [0, 15, 1, 6, 8, 2, 4, 7] 10 | 11 | number = random.randint(0, 10) 12 | number2 = random.randint(0, 10) 13 | print(l) 14 | found = False 15 | try: 16 | i1 = l.index(number) 17 | except ValueError: 18 | print(number, "finns inte i listan") 19 | found = True 20 | try: 21 | i2 = l.index(number2) 22 | except ValueError: 23 | print(number2, "finns inte i listan") 24 | found = True 25 | 26 | if not found: 27 | tmp = l[i1] 28 | l[i1] = l[i2] 29 | l[i2] = tmp 30 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom03/search_list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Different ways to search a list 3 | """ 4 | movies = [ 5 | "Spider-Man: Far From Home", 6 | "Dora and the Lost City of Gold", 7 | "John Wick: Chapter 3 - Parabellum", 8 | "Zombieland: Double Tap", 9 | "Captain Marvel", 10 | "Star Wars: The Rise of Skywalker" 11 | ] 12 | movie = input("Enter movie: ") 13 | # Manuella sättet, inte jätte bra. 14 | # found = False 15 | # for list_movie in movies: 16 | # if movie == list_movie: 17 | # print("Movie already exist!") 18 | # found = True 19 | # break 20 | 21 | # bästa sättet 22 | if movie in movies: 23 | print("Movie already exist!") 24 | else: 25 | movies.append(movie) 26 | 27 | # sämsta sättet. Så vida man inte vill ha dess index värde för något 28 | # try: 29 | # movies.index(movie) 30 | # print("Movie already exist!") 31 | # except ValueError: 32 | # movies.append(movie) 33 | # print(movies) 34 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom03/slicing.py: -------------------------------------------------------------------------------- 1 | """ 2 | How slicing works with step 3 | """ 4 | numbers = [0, 1, 2, 3, 4] 5 | 6 | START = 0 7 | END = 5 8 | STEP = 3 9 | print(numbers[START:END:STEP]) 10 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom03/sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implementation of bubblesort 3 | """ 4 | l = [2, 5, 1, 0, 3] 5 | print(l) 6 | n = len(l) 7 | for j in range(n-1): 8 | for i in range(n-1): 9 | if l[i] > l[i+1]: 10 | tmp = l[i] 11 | l[i] = l[i+1] 12 | l[i+1] = tmp 13 | print(l) 14 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom04/arguments.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example of arguments, default arguments and named arguments 3 | """ 4 | def pets(species, name="Kim", number_of_legs=4): 5 | """ 6 | Prints about pets 7 | """ 8 | print( 9 | f"My pet is a {species} and it is called {name} it has {number_of_legs} legs" 10 | ) 11 | 12 | pets("dog", "Buster", 4) 13 | pets("dog") 14 | pets(species="cat", name="Martin", number_of_legs=5) 15 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom04/execution_flow.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example of execution flow and global variables 3 | """ 4 | 5 | """ numbers = "" 6 | def f1(): 7 | # 3 8 | global numbers 9 | numbers += "3" 10 | 11 | def f2(): 12 | global numbers 13 | f3() 14 | numbers += "2" 15 | f1() 16 | 17 | def f3(): 18 | global numbers 19 | numbers += "1" 20 | 21 | 22 | f2() """ 23 | 24 | 25 | def f1(numbers): 26 | """append""" 27 | numbers.append("3") 28 | 29 | def f2(numbers): 30 | """append""" 31 | f3(numbers) 32 | numbers.append("2") 33 | f1(numbers) 34 | 35 | def f3(numbers): 36 | """append""" 37 | numbers.append("1") 38 | 39 | 40 | def main(): 41 | """ 42 | Start everyting, needed to not get validation errors. 43 | """ 44 | numbers = [] 45 | f2(numbers) 46 | print(numbers) 47 | 48 | if __name__ == "__main__": 49 | main() 50 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom04/executionflow_assignment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Assignment 3 3 | """ 4 | def f1(numbers): 5 | """append""" 6 | numbers.append(4) 7 | 8 | def f2(numbers): 9 | """append""" 10 | numbers.append(2) 11 | f4(numbers) 12 | 13 | def f3(numbers): 14 | """append""" 15 | numbers.append(1) 16 | f2(numbers) 17 | f1(numbers) 18 | 19 | def f4(numbers): 20 | """append""" 21 | numbers.append(3) 22 | 23 | def main(): 24 | """ star program """ 25 | numbers = [] 26 | f3(numbers) 27 | print(numbers) 28 | 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom04/layer_cake.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example for argument, default arguments and named arguments 3 | """ 4 | 5 | def layer_cake(color="petrol blue", filling="passion fruit", filling2="daim", layers=3): 6 | """ 7 | Prints about cake 8 | """ 9 | print( 10 | f"My cake is {color} with the fillings {filling} and {filling2}. It rocks {layers} layers!" 11 | ) 12 | 13 | layer_cake() 14 | layer_cake("black") 15 | layer_cake("black", "chocolate") 16 | layer_cake("black", "chocolate", "fudge") 17 | layer_cake("black", "chocolate", "fudge", 5) 18 | layer_cake(layers=10) 19 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom04/message_changer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Assigment 2 3 | """ 4 | import string_modifier 5 | 6 | def take_message(): 7 | """ 8 | Switch uppers and lowers in a string 9 | """ 10 | msg = input("Enter a crasy case message: ") 11 | new_msg = "" 12 | for letter in msg: 13 | new_msg += string_modifier.case_switch(letter) 14 | print(new_msg) 15 | 16 | if __name__ == "__main__": 17 | take_message() 18 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom04/string_modifier.py: -------------------------------------------------------------------------------- 1 | """ 2 | COntain functions for modifying strings 3 | """ 4 | def case_switch(letter): 5 | """ 6 | Change uppers to lowers and lowers to uppers 7 | """ 8 | if letter.isupper(): 9 | return letter.lower() 10 | return letter.upper() 11 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom05/find_movies.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tuple assignment 3 | """ 4 | def find(search, movies): 5 | """ 6 | Search tuple for value 7 | """ 8 | match = [] 9 | for movie in movies: 10 | if search in movie: 11 | match.append(movie) 12 | return match 13 | 14 | def search_movies(movies): 15 | """ 16 | Search for movies 17 | """ 18 | search = input("Enter something to search for: ") 19 | matches = find(search, movies) 20 | sorted_matches = sorted(matches) 21 | print(sorted_matches) 22 | 23 | 24 | if __name__ == "__main__": 25 | movies_tuple = ( 26 | ("Baby Driver", "2017", "Edgar Wright"), 27 | ("Scott Pilgrim vs. the world", "2010", "Edgar Wright"), 28 | ("Thor: Ragnarok", "2017", "Taika Waititi"), 29 | ("What we do in the shadows", "2014", "Taika Waititi"), 30 | ("Tucker and Dale vs Evil", "2010", "Eli Craig"), 31 | ) 32 | search_movies(movies_tuple) 33 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom05/movies.txt: -------------------------------------------------------------------------------- 1 | ( 2 | ("Baby Driver", "2017", "Edgar Wright"), 3 | ("Scott Pilgrim vs. the world", "2010", "Edgar Wright"), 4 | ("Thor: Ragnarok", "2017", "Taika Waititi"), 5 | ("What we do in the shadows", "2014", "Taika Waititi"), 6 | ("Tucker and Dale vs Evil", "2010", "Eli Craig"), 7 | ) 8 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom05/shoe_sizes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dictionary assignment 3 | """ 4 | from operator import itemgetter 5 | 6 | def gather_data(): 7 | """ 8 | Gather names and show sizes in dictionary 9 | """ 10 | done = False 11 | data = {} 12 | while not done: 13 | try: 14 | name, shoesize = tuple(input("Enter name and shoesize, sperated by space: ").split(" ")) 15 | data[name] = shoesize 16 | except ValueError: 17 | done = True 18 | 19 | return data 20 | 21 | def sort_data(data): 22 | """ 23 | Sort and print dictionary on shoesize 24 | """ 25 | avg = 0 26 | for name, shoesize in sorted(data.items(), key=itemgetter(1)): 27 | print(f"{name}:{shoesize}") 28 | avg += int(shoesize) 29 | print(avg/len(data)) 30 | 31 | 32 | def main(): 33 | """ 34 | Start of program 35 | """ 36 | name_size = gather_data() 37 | sort_data(name_size) 38 | 39 | if __name__ == "__main__": 40 | main() 41 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom05/tupler.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tuple example 3 | """ 4 | from operator import itemgetter 5 | 6 | def create_tuple(string): 7 | """ 8 | Create tuple with word and word len 9 | """ 10 | return string, len(string) 11 | 12 | 13 | def sort_by_length(words): 14 | """ 15 | sort and print words base on length 16 | """ 17 | tuples = [] 18 | for string in words: 19 | tuples.append(create_tuple(string)) 20 | print(tuples) 21 | tuples.sort(key=itemgetter(1)) 22 | print(tuples) 23 | 24 | 25 | 26 | if __name__ == "__main__": 27 | strings = ["ko", "get", "elefant", "hund", "orm"] 28 | sort_by_length(strings) 29 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom06/A5.py: -------------------------------------------------------------------------------- 1 | """ 2 | How assignment A5 in marvin can be solved with dictionary 3 | """ 4 | def transform_value(player, score): 5 | """ 6 | Transform value to negative in if player is upper 7 | """ 8 | if player.isupper(): 9 | return -int(score) 10 | return int(score) 11 | 12 | 13 | def calculate_score(results): 14 | """ 15 | calculate score for all players 16 | """ 17 | counter = 0 18 | tot_players = {} 19 | 20 | while counter < len(results): 21 | player = results[counter] 22 | score = results[counter+1] 23 | score = transform_value(player, score) 24 | 25 | player = player.lower() 26 | tot_players[player] = tot_players.get(player, 0) + score 27 | 28 | counter += 2 29 | print(tot_players) 30 | 31 | 32 | 33 | if __name__ == "__main__": 34 | calculate_score("a2b4A5s3B1") 35 | calculate_score("g3l1H5l2G3l1") 36 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom06/data.txt: -------------------------------------------------------------------------------- 1 | My name is {}! 2 | I am {} years old. 3 | Hej på dig {} -------------------------------------------------------------------------------- /example/lectures/2020/kmom06/manifesto.txt: -------------------------------------------------------------------------------- 1 | Beautiful is better than ugly. 2 | Explicit is better than implicit. 3 | Simple is better than complex. 4 | Complex Is better than complicated. 5 | Flat is better than nested. 6 | Sparse Is better than dense. 7 | Readability counts. 8 | Special cases are not special enough to break the rules. 9 | Although practicality beats purity. 10 | Errors should never pass silently. 11 | Unless explicitly silenced. 12 | In the face of ambiguity, refuse the temptation to guess. 13 | There should be one -- and preferably only one -- obvious way to do it. 14 | Although that way may not be obvious at first unless you are Dutch. 15 | Now is better than never. 16 | Although never is often better than right now. 17 | If the implementation is hard to explain, it is a bad idea. 18 | If the implementation is easy to explain, it may be a good idea. 19 | Namespaces are one honking great idea -- let us do more of those! -------------------------------------------------------------------------------- /example/lectures/2020/kmom06/read.py: -------------------------------------------------------------------------------- 1 | """ 2 | Read format strings from a file and inject words 3 | """ 4 | def read_file(fd): 5 | """ 6 | Itterate over file content and inject new words 7 | """ 8 | for line in fd: 9 | print(line) 10 | word = input("enter new word: ") 11 | print(line.format(word)) 12 | 13 | 14 | def open_file(): 15 | """ 16 | Read file content 17 | """ 18 | try: 19 | # fd = open("data.txt", "r") 20 | with open("data.txt", "r") as fd: 21 | read_file(fd) 22 | except FileNotFoundError: 23 | print("You are missing the file") 24 | return 25 | 26 | 27 | if __name__ == "__main__": 28 | open_file() 29 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom06/read_assignment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Read X number of lines from a file 3 | """ 4 | 5 | def print_lines(lines): 6 | """ 7 | Iterate over file content and print X lines 8 | """ 9 | nr = int(input("How many lines do you want to see? ")) 10 | 11 | for line in lines[:nr]: 12 | print(line) 13 | print("------") 14 | 15 | counter = 0 16 | while counter < nr: 17 | print(lines[counter]) 18 | counter += 1 19 | print("------") 20 | 21 | # Sämst sätt att lösa på 22 | for indx, line in enumerate(lines): 23 | if indx == nr: 24 | break 25 | print(line) 26 | 27 | 28 | def read_file(): 29 | """ 30 | Read file content 31 | """ 32 | try: 33 | with open("manifesto.txt", "r") as fd: 34 | print_lines(fd.read().split("\n")) 35 | except FileNotFoundError: 36 | print("You are missing the file") 37 | return 38 | 39 | 40 | if __name__ == "__main__": 41 | read_file() 42 | -------------------------------------------------------------------------------- /example/lectures/2020/kmom06/shopping.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbwebb-se/python/ee7c85cfd6db49592b98fe5b1126a40e9b4d6a6a/example/lectures/2020/kmom06/shopping.txt -------------------------------------------------------------------------------- /example/lectures/2020/kmom06/shoppinglist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Add items to a shoppinglist 3 | """ 4 | # pylint: disable=inconsistent-return-statements 5 | 6 | def read_file(filename): 7 | """ 8 | Read content from file 9 | """ 10 | try: 11 | with open(filename, "r") as fd: 12 | return fd.read() 13 | except FileNotFoundError: 14 | print("You are missing the file") 15 | return "" 16 | 17 | 18 | 19 | def write_to_file(filename, content, mode): 20 | """ 21 | write to file, mode should be "a" or "w" 22 | """ 23 | with open(filename, mode) as fd: 24 | fd.write(content) 25 | 26 | 27 | 28 | def main(): 29 | """ 30 | Meny for program 31 | """ 32 | filename = "shopping.txt" 33 | while True: 34 | inp = input("Enter things to buy or shop: ") 35 | if inp == "shop": 36 | print(read_file(filename)) 37 | write_to_file(filename, "", "w") 38 | else: 39 | write_to_file(filename, inp+"\n", "a") 40 | 41 | 42 | 43 | if __name__ == "__main__": 44 | main() 45 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom01/candy.py: -------------------------------------------------------------------------------- 1 | """ 2 | Allowance uppgift 3 | """ 4 | allowance = int(input("Vad är din månadspeng? ")) 5 | cost_of_candy = int(input("Hur mycket handlar du godis för? ")) 6 | 7 | left_of_allowance = allowance - cost_of_candy 8 | 9 | print(str(left_of_allowance) + " kr") 10 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom01/money_converter.py: -------------------------------------------------------------------------------- 1 | """ 2 | inmatning antal svenska kronor från användaren. 3 | omvandla till Japanska Yen, kurs: 1 SKR = 10.81 YEN. 4 | 5 | skriva ut hur många YEN, 6 | samt 10 och 100 gånger så mycket 7 | """ 8 | sek = float(input("Skriv in hur många svenska kronor: ")) 9 | 10 | sek_to_yen_course = 10.81 11 | yen = sek * sek_to_yen_course 12 | 13 | print(f"{sek} svenska kronor är {yen} yen") 14 | print(f"{sek * 10} svenska kronor är {yen * 10} yen") 15 | print(f"{sek*100} svenska kronor är {yen*100} yen") 16 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom01/time_converter.py: -------------------------------------------------------------------------------- 1 | """ 2 | Omvandla sek to timmar och sek 3 | """ 4 | secs = int(input("Enter seconds: ")) 5 | hours = secs // (60*60) 6 | secs_left = secs % (60*60) 7 | 8 | print(str(secs) + " seconds is " + str(hours) + " hours and " + str(secs_left) + " seconds!") 9 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom01/variables.py: -------------------------------------------------------------------------------- 1 | """ 2 | Vad är variabler 3 | """ 4 | name = input("Skriv in ditt namn: ") 5 | age = int(input("Skriv in din ålder: ")) 6 | 7 | print(type(name)) 8 | print(type(age)) 9 | 10 | print(age) 11 | 12 | print(name + " är " + str(age) + " år gammal") 13 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-1/for.py: -------------------------------------------------------------------------------- 1 | """ 2 | Examples of for-loops 3 | """ 4 | for i, letter in enumerate("python snake"): 5 | print(letter, "has the position ", i) 6 | 7 | string = "" 8 | for number in "python": 9 | string = str(number) + string 10 | print(string) 11 | 12 | ROWS = 4 13 | COLS = 4 14 | for nr in range(ROWS): 15 | for nr2 in range(COLS): 16 | print("*", end="") 17 | print() 18 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-1/for_assignment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som med hjälp av en for-loop plockar bort 3 | alla mellanslag från strängen "Python är det bästa programmeringsspråket!" 4 | 5 | När programmet är klart ska 6 | strängen bli "Pythonärdetbästaprogrammeringsspråket!" 7 | 8 | Tips. mellanslag är en egen karaktär, " ", vi kan jämföra mot. 9 | """ 10 | 11 | string = "Python är det bästa programmeringsspråket!" 12 | msg = "" 13 | for char in string: 14 | if char != " ": 15 | msg += char 16 | print(msg) 17 | 18 | 19 | # mindre bra lösning 20 | msg = "" 21 | for char in string: 22 | if char == " ": 23 | pass 24 | else: 25 | msg += char 26 | print(msg) 27 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-1/if.py: -------------------------------------------------------------------------------- 1 | """ 2 | If statement 3 | """ 4 | number_of_apples = 60 5 | number_of_pears = 30 6 | 7 | if number_of_apples > 10 and number_of_pears > 10: 8 | print("lots of apples and pears") 9 | else: 10 | print("få frukter") 11 | print("after if") 12 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-1/if_assignment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Check if input integers follow criteria 3 | """ 4 | first = int(input("Enter an integer")) 5 | second = int(input("Enter another integer")) 6 | 7 | # Non validating solution 8 | # message = "Rejected" 9 | # if (first > 10 and first < 100) and (second > 10 and second < 100): 10 | # if first < 50 or second < 50: 11 | # if first > 40 or second > 40: 12 | # message = "Approved" 13 | # 14 | # print(message) 15 | 16 | 17 | # Best solution 18 | # message = "Rejected" 19 | # if 10 < first < 100 and 10 < second < 100: 20 | # if first < 50 or second < 50: 21 | # if first > 40 or second > 40: 22 | # message = "Approved" 23 | # print(message) 24 | 25 | # Less good solution 26 | if 10 < first < 100 and 10 < second < 100: 27 | if first < 50 or second < 50: 28 | if first > 40 or second > 40: 29 | print("Approved") 30 | else: 31 | print("Rejected") 32 | else: 33 | print("Rejected") 34 | else: 35 | print("Rejected") 36 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-1/problem.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som räknar på sparande. Programmet ska ta emot tre värden: 3 | start kapital, ränta och slutvärde. 4 | Programmet ska sedan räkna ut hur många år pengarna ska 5 | stå på kontot innan vi har kommit upp i minst slutvärdet. 6 | 7 | Värdet efter 1 år med ränta kan räknas ut som: 8 | new_value = old_value * (1 + interest / 100) 9 | 10 | Exempel: värdena 1000 i startkapital, 1200 i slutvärde och 5% ränta anges. 11 | Efter 1 år: 1000 * (1 + 5 / 100) = 1050 12 | Efter 2 år: 1050 * (1 + 5 / 100) = 1102.5 13 | Efter 3 år: 1102.5 * (1 + 5 / 100) = 1157.625 14 | Efter 4 år: 1157.625 * (1 + 5 / 100) = 1215.50625 - Dvs 4 år på kontot. 15 | """ 16 | 17 | amount_of_mouney = int(input("How much money do you have? ")) 18 | interest = int(input("What is your expected interest? ")) 19 | goal = int(input("What is your goal value? ")) 20 | 21 | years = 0 22 | while amount_of_mouney < goal: 23 | amount_of_mouney = amount_of_mouney * (1 + interest / 100) 24 | years += 1 25 | print("After", years, "years you have", round(amount_of_mouney, 5), "money") 26 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-1/string.py: -------------------------------------------------------------------------------- 1 | """ 2 | "" vs '' in strings 3 | """ 4 | string = '"I licked it, so it\'s mine"' 5 | print(string) 6 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-1/while.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example of while-loop 3 | """ 4 | total_sum = 0 5 | while True: 6 | number = int(input("Enter a number: ")) 7 | if number % 2 == 0: 8 | continue 9 | 10 | total_sum += number 11 | print("new sum is", total_sum) 12 | if total_sum > 21: 13 | break 14 | 15 | print(total_sum) 16 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/factorial.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calculate factorial up to an input 3 | """ 4 | try: 5 | number = int(input("Skriv in en siffra: ")) 6 | 7 | if number > 0: 8 | factorial = 1 9 | 10 | while number: 11 | factorial *= number 12 | number -= 1 13 | 14 | print(factorial) 15 | else: 16 | print("Fakultet är bara definierat för n > 0") 17 | except ValueError: 18 | print("Du skrev inte i en siffra") 19 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/fixed.py: -------------------------------------------------------------------------------- 1 | """ 2 | Fixed - variable with constant/fixed value, does not change during execution. 3 | """ 4 | PI = 3.14 5 | 6 | radius = input("Enter the radius") 7 | area = int(radius) * int(radius) * PI 8 | 9 | print("Area of circle: ", area) 10 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/follower.py: -------------------------------------------------------------------------------- 1 | """ 2 | Follower - Variable with a previous value. Can be used to compare old and new values 3 | """ 4 | previous = input("Enter a word: ") # follwer 5 | current = input("Enter a word: ") # most recent holder 6 | 7 | while True: 8 | if len(current) > len(previous): 9 | print("Current word is longer") 10 | else: 11 | print("Previous word is longer") 12 | 13 | previous = current 14 | current = input("Enter a word: ") 15 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/gatherer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Gatherer - Variable that gathers data or values from inputs. 3 | """ 4 | number = 0 # most recent holder 5 | total = 0 # gatherer 6 | counter = 0 # stepper/counter 7 | while number != -999: 8 | try: 9 | number1 = int(input("Enter a number, -999 to quit: ")) 10 | except ValueError: 11 | print("Inte ett heltal") 12 | continue 13 | 14 | if number != -999: 15 | counter += 1 16 | total += number 17 | 18 | print("Average: ", total/counter) 19 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/one_way_flag.py: -------------------------------------------------------------------------------- 1 | """ 2 | One way flag - Variable that change it's value from True/False to False/True once. 3 | """ 4 | loop = True 5 | while loop: 6 | word = input("A word: ") 7 | if "e" in word: 8 | loop = False 9 | print("e was entered") 10 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/recent_holder.py: -------------------------------------------------------------------------------- 1 | """ 2 | Most recent holder - Variable with the last thing inserted by user 3 | or latest value that is read from a sequence. 4 | """ 5 | WORD = "Elephant" # most recent holder 6 | for letter in WORD: 7 | print(letter) 8 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/stepper.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stepper/Counter - Stepps or counts through a sequence of values. 3 | Often heads to wards a certain value 4 | """ 5 | counter = 0 6 | result = 26 7 | ADD = 7 8 | MAX = 33 9 | while counter < MAX: 10 | result += ADD 11 | counter += 1 12 | print(result) 13 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/truthiness-exercise.py: -------------------------------------------------------------------------------- 1 | """ 2 | Check if password validates 3 | """ 4 | 5 | password = input("Input a password: ") 6 | 7 | validated_password = False 8 | 9 | if password: 10 | if len(password) <= 10: 11 | for letter in password: 12 | if letter.isdigit(): 13 | validated_password = True 14 | 15 | if validated_password: 16 | print("Wohooo we have a validated password") 17 | else: 18 | print("Buhuhuu the password did not validate") 19 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/truthiness.py: -------------------------------------------------------------------------------- 1 | """ 2 | Shuffles word, uses truthiness 3 | """ 4 | 5 | import random 6 | 7 | word = "elephant" 8 | shuffle_word = "" 9 | 10 | while word: 11 | letter_index = random.randint(0, len(word) - 1) 12 | 13 | shuffle_word = shuffle_word + word[letter_index] 14 | 15 | word = word[0:letter_index] + word[letter_index + 1:] 16 | 17 | print(shuffle_word) 18 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/try-except-assignment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som tar emot input från användaren. Beroende på inputens data typ gör en av två saker: 3 | 4 | En sträng: Konkatenera ihop med tidigare stränger. 5 | En siffra: Skriv ut den konkatenerade strängen det antal gånger, som siffran är. 6 | """ 7 | 8 | inp = "" 9 | string = "" 10 | while inp != "done": 11 | inp = input("Enter string or number: ") 12 | try: 13 | print(string * int(inp)) 14 | except ValueError: 15 | string += inp 16 | print(string) 17 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/try-except.py: -------------------------------------------------------------------------------- 1 | """ 2 | try except exempel 3 | """ 4 | number = 10 5 | 6 | try: 7 | number2 = int(input("Skriv in en siffra: ")) 8 | except ValueError: 9 | print("number2 är inte en siffra, fy!") 10 | 11 | try: 12 | x = number / number2 13 | print(x) 14 | except ZeroDivisionError: 15 | print("number2 är 0, inte OK!") 16 | print("Hej") 17 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom02-2/wanted_holder.py: -------------------------------------------------------------------------------- 1 | """ 2 | Most wanted holder - Variable with a value we are looking for. 3 | """ 4 | smallest = 9999999999# wanted holder 5 | 6 | while True: 7 | content = input("Enter a number: ") 8 | if content == "q": 9 | break 10 | else: 11 | number = int(content) 12 | if number < smallest: 13 | smallest = number 14 | print(smallest) 15 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom03/cake.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skapa en fil med namnet cake.py. 3 | I filen skapa en funktion layer_cake() som skriver ut en formaterat 4 | strang. 5 | Funktionen ska ta emot 4 argument: 6 | farg, 2 sorters fyllning och antal lager. 7 | Alla argument ska ha ett förifylld värde. 8 | Anropa sedan funktionen med 0, 1, 2, 3 och 4 argument samt med 9 | bara sista argumentet (antal lager) med hjalp av argument=varde 10 | """ 11 | 12 | def layer_cake( 13 | color="Petrol Blue", 14 | filling1="Passion fruit", 15 | filling2="Sugar", 16 | layers=4): 17 | """ 18 | Print info about cake 19 | """ 20 | print(f"My cake has the color {color} with the fillings {filling1} and {filling2}. It also has {layers} layers!") 21 | 22 | if __name__ == "__main__": 23 | layer_cake() 24 | layer_cake("yellow") 25 | layer_cake("orange", "strawberry") 26 | layer_cake("orange", "pear", "apple") 27 | layer_cake("green", "pear", "grape", 10) 28 | layer_cake(layers=100) 29 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom03/calc_many_squares.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show module, if name main and return 3 | """ 4 | from module import calc_square 5 | 6 | def calc_many_square(): 7 | """ 8 | Calc squar for many numbers 9 | """ 10 | for number in range(4): 11 | print(calc_square(number, number+1)) 12 | 13 | if __name__ == "__main__": 14 | calc_many_square() 15 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom03/calc_square.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calc a weird square 3 | """ 4 | def calc_square(a, b): 5 | """ 6 | Kvadreringsregeln 7 | """ 8 | square = a**2 + b**2 + 2*a*b 9 | return square 10 | # result = calc_square(2, 4) 11 | print(calc_square(2, 4)) 12 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom03/default_arguments.py: -------------------------------------------------------------------------------- 1 | """ 2 | argument, parameters and default values 3 | """ 4 | def pets(species, name="Kim", number_of_legs=4): 5 | """ 6 | Print pet information 7 | """ 8 | print(f"My pet is a {species}, it is called {name} and has {number_of_legs} legs.") 9 | 10 | pets("dog", "buster", 2) 11 | pets("dog", "buster") 12 | pets("cat") 13 | pets("cat", "Emil") 14 | pets("snake", number_of_legs=0) 15 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom03/greeters.py: -------------------------------------------------------------------------------- 1 | """ 2 | Several greeters 3 | """ 4 | 5 | def greeter(): 6 | """ 7 | Greets person 8 | """ 9 | print("hello") 10 | 11 | def goodbyer(): 12 | """ 13 | Says goodbye 14 | """ 15 | print("goodbye") 16 | 17 | if __name__ == "__main__": 18 | greeter() 19 | goodbyer() 20 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom03/main.py: -------------------------------------------------------------------------------- 1 | """ 2 | Main program using cake.py 3 | """ 4 | import cake 5 | 6 | cake.layer_cake("blue", "strawberries", "chocolate", 7) 7 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom03/main_for_greeter.py: -------------------------------------------------------------------------------- 1 | """ 2 | Imports greeters and calls functions. 3 | """ 4 | 5 | import greeters 6 | 7 | greeters.greeter() 8 | greeters.goodbyer() 9 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom03/praktiskt_problem/conversions.py: -------------------------------------------------------------------------------- 1 | """ 2 | conversion functions 3 | """ 4 | def km_to_miles(km): 5 | """ calc km to miles """ 6 | return km * 0.621371 7 | 8 | 9 | def c_to_f(celsius): 10 | """ convert celsius to farenheit""" 11 | return celsius * (9/5) + 32 12 | 13 | if __name__ == "__main__": 14 | print(km_to_miles(10)) 15 | print(c_to_f(10)) 16 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom03/praktiskt_problem/output.py: -------------------------------------------------------------------------------- 1 | """ 2 | Funktions for printing data 3 | """ 4 | 5 | def print_start_to_destination(start, destination): 6 | """ 7 | Print start and destination 8 | """ 9 | print("Going from " + 10 | start + 11 | " to " + 12 | destination 13 | ) 14 | 15 | 16 | def print_distance(distance, destination): 17 | """ 18 | print distance to destination 19 | """ 20 | print(str(distance) + 21 | " miles to " + 22 | destination 23 | ) 24 | 25 | def print_weather(degrees, weather, destination): 26 | """ 27 | print weather and temp at destination 28 | """ 29 | print(str(degrees) + 30 | " degrees and " + 31 | weather + 32 | " in " + 33 | destination 34 | ) 35 | 36 | if __name__ == "__main__": 37 | print_start_to_destination("karlskrona", "osby") 38 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom04/bubble_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bubble sort implementation 3 | """ 4 | 5 | def bubble_sort(items): 6 | """ 7 | Sorts list 8 | """ 9 | for i in range(len(items)): 10 | for j in range(len(items) - 1 - i): 11 | if items[j] > items[j + 1]: 12 | items[j], items[j + 1] = items[j + 1], items[j] 13 | 14 | print(items) 15 | 16 | if __name__ == "__main__": 17 | numbers_list = [8, 12, 48, 3, 15, 6463, 19] 18 | 19 | bubble_sort(numbers_list) 20 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom04/instruments.py: -------------------------------------------------------------------------------- 1 | """ 2 | slciing 3 | """ 4 | instruments = ["Triangle", "Drums", "Accordion", 5 | "Saxophone", "Banjo", "Guitar", 6 | "Synthesizer", "Keyboard"] 7 | 8 | # print(instruments[0]) 9 | # print(instruments[2:4]) 10 | # print(instruments[:4]) 11 | # print(instruments[-2:]) 12 | # print(instruments[:-1]) 13 | print(instruments[::2]) 14 | print(instruments[::-2]) 15 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom04/list_as_argument.py: -------------------------------------------------------------------------------- 1 | """ 2 | Hur mutable datatyper funkar som argument 3 | """ 4 | import pprint 5 | movies_part1 = [ 6 | "Spider-Man: Far From Home", 7 | "Dora and the Lost City of Gold", 8 | "John Wick: Chapter 3 - Parabellum", 9 | "Zombieland: Double Tap", 10 | "Captain Marvel", 11 | "Star Wars: The Rise of Skywalker" 12 | ] 13 | 14 | def add_part(movies): 15 | """ 16 | Lägg till "part 2" på varje sträng i listan 17 | """ 18 | #movies[0] += " part 2" 19 | #movies_part2 = [] 20 | for index, _ in enumerate(movies): 21 | # movies_part2.append(movie + " part 2") 22 | movies[index] += " part2" 23 | pprint.pprint(movies) 24 | # return movies 25 | 26 | add_part(movies_part1) 27 | # new_list = add_part(movies_part1) 28 | pprint.pprint(movies_part1) 29 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom04/movies_with_me.py: -------------------------------------------------------------------------------- 1 | """ 2 | Come to the movies with me 3 | """ 4 | 5 | def output_movie_goers(goers): 6 | """ 7 | Prints nice list of people going to the movies 8 | """ 9 | print() 10 | for goer in goers: 11 | print(goer) 12 | 13 | def add_movie_goers(): 14 | """ 15 | Add movie goers 16 | """ 17 | movie_goers = [] 18 | while True: 19 | name_or_done = input("Write a name you want to bring to the movies (done to exit): ") 20 | 21 | if name_or_done == "done": 22 | break 23 | else: 24 | movie_goers.append(name_or_done) 25 | 26 | output_movie_goers(movie_goers) 27 | output_movie_goers(movie_goers[::2]) 28 | output_movie_goers(movie_goers[-3:]) 29 | output_movie_goers(movie_goers[2:4]) 30 | 31 | if __name__ == "__main__": 32 | add_movie_goers() 33 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom04/zero_to_twenty.py: -------------------------------------------------------------------------------- 1 | """ 2 | Checks if numbers are in list and swaps 3 | """ 4 | from random import randint 5 | 6 | def zero_to_twenty(items, random_one, random_two): 7 | """ 8 | gets two random numbers 9 | checks if they are in list 10 | """ 11 | index_one = -1 12 | index_two = -1 13 | 14 | try: 15 | index_one = items.index(random_one) 16 | except ValueError: 17 | print(str(random_one) + " finns inte i listan") 18 | 19 | try: 20 | index_two = items.index(random_two) 21 | except ValueError: 22 | print(str(random_two) + " finns inte i listan") 23 | 24 | if index_one >= 0 and index_two >= 0: 25 | tmp = items[index_one] 26 | items[index_one] = items[index_two] 27 | items[index_two] = tmp 28 | 29 | print(items) 30 | 31 | if __name__ == "__main__": 32 | numbers_list = [8, 12, 7, 3, 15, 4, 19] 33 | 34 | zero_to_twenty(numbers_list, randint(0, 20), randint(0, 20)) 35 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom05/movies.py: -------------------------------------------------------------------------------- 1 | """ 2 | Program that allows for searching in movies 3 | """ 4 | def search_movies(query): 5 | """ 6 | Searches for movies 7 | """ 8 | all_movies = ( 9 | ("Baby Driver", "2017", "Edgar Wright"), 10 | ("Scott Pilgrim vs. the world", "2010", "Edgar Wright"), 11 | ("Thor: Ragnarok", "2017", "Taika Waititi"), 12 | ("What we do in the shadows", "2014", "Taika Waititi"), 13 | ("Tucker and Dale vs Evil", "2010", "Eli Craig"), 14 | ) 15 | 16 | result_movies = [] 17 | for movie in all_movies: 18 | title, year, director = movie 19 | if query in (title, year, director): 20 | result_movies.append(movie) 21 | 22 | print() 23 | print("Results: ") 24 | for title, year, director in sorted(result_movies): 25 | print(title + " " + year + " " + director) 26 | 27 | if __name__ == "__main__": 28 | query_str = input("What do you want to search for: ") 29 | search_movies(query_str) 30 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom05/shoes.py: -------------------------------------------------------------------------------- 1 | """ 2 | shoe assignment. calc average show size 3 | """ 4 | def get_data(): 5 | """ 6 | Get names and sizes from user 7 | """ 8 | data = {} 9 | inp = input("Enter 'name, shoesize':") 10 | while inp != "done": 11 | name, size = inp.split(", ") 12 | data[name] = int(size) 13 | inp = input("Enter 'name, shoesize':") 14 | return data 15 | 16 | def print_data(data): 17 | """ 18 | calc average and print data 19 | """ 20 | tot = 0 21 | for name, size in data.items(): 22 | print(f"{name}: {size}") 23 | tot += size 24 | print(f"average size is {tot/len(data)}") 25 | 26 | if __name__ == "__main__": 27 | name_size = get_data() 28 | print_data(name_size) 29 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom05/tuples.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tuples 3 | """ 4 | t = 1, 58, "hejsan", "b", ("a", "c") 5 | print(t) 6 | print(t[4][1]) 7 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom06/dogs.txt: -------------------------------------------------------------------------------- 1 | Labrador Retriever 2 | French Bulldog 3 | German Shepherd 4 | Golden Retriever 5 | BulldogPoodle 6 | Beagle 7 | Rottweiler -------------------------------------------------------------------------------- /example/lectures/2021/kmom06/line_reader.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reads specific lines from file 3 | """ 4 | 5 | def read_specific_lines_from_file(filename, number_of_lines): 6 | """ 7 | Reads specified lines from file specified as first argument 8 | """ 9 | with open(filename, "r") as fh: 10 | lines = fh.readlines() 11 | 12 | for line in lines[:number_of_lines]: 13 | print(line.rstrip()) 14 | 15 | 16 | if __name__ == "__main__": 17 | specified_lines = int(input("How many lines do you want to print: ")) 18 | read_specific_lines_from_file("manifesto.txt", specified_lines) 19 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom06/manifesto.txt: -------------------------------------------------------------------------------- 1 | heeeeeeeejis better than ugly. 2 | Explicit is better than implicit. 3 | Simple is better than complex. 4 | Complex Is better than complicated. 5 | Flat is better than nested. 6 | Sparse Is better than dense. 7 | Readability counts. 8 | Special cases are not special enough to break the rules. 9 | Although practicality beats purity. 10 | Errors should never pass silently. 11 | Unless explicitly silenced. 12 | In the face of ambiguity, refuse the temptation to guess. 13 | There should be one -- and preferably only one -- obvious way to do it. 14 | Although that way may not be obvious at first unless you are Dutch. 15 | Now is better than never. 16 | Although never is often better than right now. 17 | If the implementation is hard to explain, it is a bad idea. 18 | If the implementation is easy to explain, it may be a good idea. 19 | Namespaces are one honking great idea -- let us do more of those!dslkdjdsaldjalksjdlk -------------------------------------------------------------------------------- /example/lectures/2021/kmom06/points.py: -------------------------------------------------------------------------------- 1 | """ 2 | Solve A5 in marvin1 using dicts 3 | """ 4 | def calculate_points(point_str): 5 | """ 6 | Calculated points for each player 7 | """ 8 | player_dict = {} 9 | 10 | for index in range(0, len(point_str), 2): 11 | if point_str[index].isupper(): 12 | current_points = int(point_str[index + 1]) * -1 13 | else: 14 | current_points = int(point_str[index + 1]) 15 | 16 | if point_str[index].lower() in player_dict: 17 | player_dict[point_str[index].lower()] += current_points 18 | else: 19 | player_dict[point_str[index].lower()] = current_points 20 | 21 | result_list = [] 22 | 23 | for key, value in player_dict.items(): 24 | result_list.append(key + " " + str(value)) 25 | 26 | result_string = ", ".join(result_list) 27 | 28 | print(result_string) 29 | 30 | if __name__ == "__main__": 31 | calculate_points("g3l1H5l2G3l1") 32 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom06/read.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reads from file 3 | """ 4 | def read_from_file(filename): 5 | """ 6 | Reads from file specified as argument 7 | """ 8 | with open(filename, "r") as fh: 9 | for line in fh.readlines(): 10 | for letter in line: 11 | print(letter) 12 | 13 | if __name__ == "__main__": 14 | read_from_file("read_from.txt") 15 | -------------------------------------------------------------------------------- /example/lectures/2021/kmom06/read_from.txt: -------------------------------------------------------------------------------- 1 | hej jag 2 | heter 3 | Emil och 4 | bredvid mig sitter 5 | Andreas -------------------------------------------------------------------------------- /example/lectures/2021/kmom06/shopping.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbwebb-se/python/ee7c85cfd6db49592b98fe5b1126a40e9b4d6a6a/example/lectures/2021/kmom06/shopping.txt -------------------------------------------------------------------------------- /example/lectures/2021/kmom06/shoppinglist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Add items to a shoppinglist 3 | """ 4 | 5 | def read_file(filename): 6 | """ 7 | Read content from file 8 | """ 9 | try: 10 | with open(filename, "r") as fd: 11 | return fd.read() 12 | except FileNotFoundError: 13 | print("You are missing the file") 14 | return "" 15 | 16 | 17 | 18 | def write_to_file(filename, content, mode): 19 | """ 20 | write to file, mode should be "a" or "w" 21 | """ 22 | with open(filename, mode) as fd: 23 | fd.write(content) 24 | 25 | 26 | 27 | def main(): 28 | """ 29 | Meny for program 30 | """ 31 | filename = "shopping.txt" 32 | while True: 33 | inp = input("Enter things to buy or shop: ") 34 | if inp == "shop": 35 | print(read_file(filename)) 36 | write_to_file(filename, "", "w") 37 | else: 38 | write_to_file(filename, inp+"\n", "a") 39 | 40 | 41 | 42 | if __name__ == "__main__": 43 | main() 44 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom01/candy.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Uppgift 1 3 | ''' 4 | 5 | # Input, get allowance and cost_of_candy 6 | # https://docs.python.org/3.10/library/functions.html?highlight=built%20functions 7 | allowance = int(input("Vad är din månadspeng? ")) 8 | cost_of_candy = int(input("Hur mycket handlar du godis för? ")) 9 | 10 | # Calculation 11 | left_of_allowance = allowance - cost_of_candy 12 | 13 | # Output, print out what is left of allowance 14 | print("Du har " + str(left_of_allowance) + " kr kvar av din månadspeng.") 15 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom01/candy_sol1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Uppgift 1 3 | ''' 4 | 5 | # Input (or assign variable), get allowance and cost_of_candy 6 | 7 | # Calculation 8 | 9 | # Output, print out what is left of allowance 10 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom01/candy_sol2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Uppgift 1 3 | ''' 4 | 5 | # Step 1 6 | # Input, get allowance and cost_of_candy 7 | allowance = 100 8 | cost_of_candy = 30 9 | 10 | # Calculation 11 | #left_of_allowance = allowance - cost_of_candy 12 | 13 | # Output, print out what is left of allowance 14 | print("Du har " + str(allowance) + " kr i månadspeng innan du handlat godis.") 15 | #print("Du har " + str(left_of_allowance) + " kr kvar av din månadspeng.") 16 | 17 | # Step 2 18 | # Input, get allowance and cost_of_candy 19 | allowance = 100 20 | cost_of_candy = 30 21 | 22 | # Calculation 23 | left_of_allowance = allowance - cost_of_candy 24 | 25 | # Output, print out what is left of allowance 26 | print("Du har " + str(left_of_allowance) + " kr kvar av din månadspeng.") 27 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom01/cast.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Cast and input/output 3 | ''' 4 | 5 | # Step 1 6 | # Input 7 | vehicle = "bil" 8 | no_of_wheels = 4 9 | 10 | # Type 11 | print(type(vehicle)) 12 | print(type(no_of_wheels)) 13 | 14 | # Output 15 | print(vehicle) 16 | print(no_of_wheels) 17 | 18 | 19 | # Step 2 20 | # Input 21 | vehicle = input("Vilket fordon? ") 22 | no_of_wheels = input("Hur många hjul? ") 23 | 24 | # Type 25 | print(type(vehicle)) 26 | print(type(no_of_wheels)) 27 | 28 | # Output 29 | print("En " + vehicle + " har " + no_of_wheels + " hjul.") 30 | 31 | 32 | # Step 3 33 | # Input 34 | vehicle = input("Vilket fordon? ") 35 | no_of_wheels = int(input("Hur många hjul? ")) 36 | 37 | # Type 38 | print(type(vehicle)) 39 | print(type(no_of_wheels)) 40 | 41 | # Output 42 | # Forget to cast no_of_wheels 43 | print("En " + vehicle + " har " + no_of_wheels + " hjul.") 44 | #print("En " + vehicle + " har " + str(no_of_wheels) + " hjul.") 45 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom01/types.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Types 3 | ''' 4 | 5 | # Numbers 6 | print(type(42)) 7 | print(type(4.2)) 8 | 9 | # String 10 | print(type("Hello world!")) 11 | 12 | # Booleans 13 | print(type(True)) 14 | print(type(False)) 15 | 16 | # None 17 | # The None keyword is used to define a null value, or no value at all. 18 | # None is not the same as 0, False, or an empty string. None is a data type of its own 19 | # (NoneType). 20 | print(type(None)) 21 | 22 | # Multiline 23 | hello = """ 24 | Hello 25 | World! 26 | """ 27 | print(type(hello)) 28 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom01/variables.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Variables 3 | ''' 4 | 5 | # int - integer (heltal) 6 | x = 42 7 | print(x) 8 | 9 | # float (decimaltal) 10 | y = 4.2 11 | print(y) 12 | 13 | # str - string (sträng) 14 | text = "Hello world!" 15 | print(text) 16 | 17 | # Multiline 18 | hello = """ 19 | Hello 20 | World! 21 | """ 22 | print(hello) 23 | 24 | # bool (booleans) 25 | sun = False 26 | print(sun) 27 | 28 | a, b = 4, 2 29 | print(a) 30 | print(b) 31 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom02/for_task.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example with for-statement 3 | """ 4 | 5 | # Input or assign 6 | message = "Python är det bästa programmeringsspråket!" 7 | 8 | # Task 9 | new_message = "" 10 | 11 | # Sämre lösning 12 | # for character in message: 13 | # if character == ' ': 14 | # pass 15 | # else: 16 | # new_message += character 17 | 18 | for character in message: 19 | if character != ' ': 20 | new_message += character 21 | 22 | 23 | 24 | # Output 25 | print(new_message) 26 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom02/for_task_start.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example with for-statement 3 | """ 4 | 5 | # Input or assign 6 | message = "Python är det bästa programmeringsspråket!" 7 | 8 | # Task 9 | for character in message: 10 | print(character) 11 | # if character == ' ': 12 | # print('*') 13 | 14 | # Output 15 | print(message) 16 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom02/problem.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som beräknar sparande. 3 | Input: startkapital, ränta och slutvärde 4 | Output: antal år 5 | """ 6 | 7 | # Step last - the whole solution 8 | 9 | # Input or assign 10 | capital = float(input("Ange ditt startkapital: ")) 11 | interest = float(input("Ange din ränta i procent: ")) 12 | goal = float(input("Vilket slutvärde önskar du? ")) 13 | 14 | # Calculation, new_value = old_value * (1 + interest / 100)1000 15 | no_of_years = 0 16 | while capital < goal: 17 | capital = capital * (1 + interest / 100) 18 | no_of_years += 1 19 | 20 | # Output 21 | print("\nDu behöver spara i " + str(no_of_years) + " år.") 22 | print("Då har du " + str(round(capital, 2)) + " kr på kontot.") 23 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom02/problem_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som beräknar sparande. 3 | Input: startkapital, ränta och slutvärde 4 | Output: antal år 5 | """ 6 | 7 | # Step 1 - assign variables and do output 8 | 9 | # Input or assign 10 | capital = 1000 11 | interest = 5 12 | goal = 1200 13 | 14 | # Calculation 15 | 16 | # Output 17 | print("Du har " + str(capital) + " kr på kontot.") 18 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom02/problem_2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som beräknar sparande. 3 | Input: startkapital, ränta och slutvärde 4 | Output: antal år 5 | """ 6 | 7 | # Step 2 - add calculation for one year 8 | 9 | # Input or assign 10 | capital = 1000 11 | interest = 5 12 | goal = 1200 13 | 14 | # Calculation, new_value = old_value * (1 + interest / 100) 15 | new_capital = capital * (1 + interest / 100) 16 | 17 | # Output 18 | print("Du har " + str(capital) + " kr på kontot.") 19 | print("Med ränta har du " + str(new_capital) + " kr på kontot.") 20 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom02/problem_3.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som beräknar sparande. 3 | Input: startkapital, ränta och slutvärde 4 | Output: antal år 5 | """ 6 | 7 | # Step 3 - add calculation for several years. Since we do not know how many years we will iterate, 8 | # we will use a while-loop. The counter no_of_years is set to 0 before the loop and increased at the 9 | # end of the loop. A print is added in the loop for tracking the variables capital and no_of_years 10 | 11 | # Input or assign 12 | capital = 1000 13 | interest = 5 14 | goal = 1200 15 | 16 | # Calculation, new_value = old_value * (1 + interest / 100) 17 | no_of_years = 0 18 | while capital < goal: 19 | new_capital = capital * (1 + interest / 100) 20 | capital = new_capital 21 | no_of_years += 1 22 | print("Efter " + str(no_of_years) + " år har du " + str(round(capital, 2)) + " kr på kontot.") 23 | 24 | # Output 25 | print("\nDu behöver spara i " + str(no_of_years) + " år.") 26 | print("Då har du " + str(round(capital, 2)) + " kr på kontot.") 27 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom02/problem_4.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skriv ett program som beräknar sparande. 3 | Input: startkapital, ränta och slutvärde 4 | Output: antal år 5 | """ 6 | 7 | # Step 4 - add input and cast to float 8 | 9 | # Input or assign 10 | capital = float(input("Ange ditt startkapital: ")) 11 | interest = float(input("Ange din ränta i procent: ")) 12 | goal = float(input("Vilket slutvärde önskar du? ")) 13 | 14 | # Calculation, new_value = old_value * (1 + interest / 100) 15 | no_of_years = 0 16 | while capital < goal: 17 | new_capital = capital * (1 + interest / 100) 18 | capital = new_capital 19 | no_of_years += 1 20 | print("Efter " + str(no_of_years) + " har du " + str(round(capital, 2)) + " kr på kontot.") 21 | 22 | # Output 23 | print("\nDu behöver spara i " + str(no_of_years) + " år.") 24 | print("Då har du " + str(round(capital, 2)) + " kr på kontot.") 25 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom02/string.py: -------------------------------------------------------------------------------- 1 | """ 2 | "" vs '' in strings 3 | """ 4 | 5 | string1 = 'This is a string with single quotes.' 6 | print(string1) 7 | 8 | string2 = "This is a string with double quotes." 9 | print(string2) 10 | 11 | string3 = '"This is a string with double quotes within single quotes."' 12 | print(string3) 13 | 14 | string4 = "String with apostrophe, it's mine." 15 | print(string4) 16 | 17 | string5 = 'String with apostrophe, it\'s mine. (with backslash before the apostrophe)' 18 | print(string5) 19 | 20 | string6 = '"String with apostrophe, it\'s mine. (with backslash before the apostrophe)"' 21 | print(string6) 22 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom02_2/truthiness_int.py: -------------------------------------------------------------------------------- 1 | """ 2 | Examples of truthiness with integers and floats 3 | """ 4 | 5 | # Number 0 is False but all the other numbers are True 6 | number_zero = bool(0) 7 | number_true = bool(10) 8 | print(f"\n0 is {number_zero} and 10 is {number_true}\n") 9 | 10 | # Negative numbers are not 0 and are True 11 | number_neg = bool(-10) 12 | print(f"-10 is {number_neg}\n") 13 | 14 | # Number 0 is False but all the other numbers are True, work the same with float 15 | number_zero = bool(0.00) 16 | number_true = bool(10.123) 17 | print(f"0.00 is {number_zero} and 10.123 is {number_true}\n") 18 | 19 | # Use this with if-statements 20 | value = 3.14 21 | if value: 22 | print(f"{value} is True\n") 23 | 24 | value = 0 25 | if value: 26 | print(f"{value} is True\n") 27 | else: 28 | print(f"{value} is False\n") 29 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom03/cake.py: -------------------------------------------------------------------------------- 1 | """ 2 | Skapa en fil med namnet cake.py. 3 | I filen skapa en funktion layer_cake() som skriver ut en formaterat 4 | strang. 5 | Funktionen ska ta emot 4 argument: 6 | farg, 2 sorters fyllning och antal lager. 7 | Alla argument ska ha ett förifylld värde. 8 | Anropa sedan funktionen med 0, 1, 2, 3 och 4 argument samt med 9 | bara sista argumentet (antal lager) med hjalp av argument=varde 10 | """ 11 | 12 | def layer_cake( 13 | color="Petrol Blue", 14 | filling1="Passion fruit", 15 | filling2="Sugar", 16 | layers=4): 17 | """ 18 | Print info about cake 19 | """ 20 | print(f"My cake has the color {color} with the fillings {filling1} and {filling2}. It also has {layers} layers!") 21 | 22 | if __name__ == "__main__": 23 | layer_cake() 24 | layer_cake("yellow") 25 | layer_cake("orange", "strawberry") 26 | layer_cake("orange", "pear", "apple") 27 | layer_cake("green", "pear", "grape", 10) 28 | layer_cake(layers=100) 29 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom03/greeters.py: -------------------------------------------------------------------------------- 1 | """ 2 | Several greeters 3 | """ 4 | 5 | def greeter(): 6 | """ 7 | Greets person 8 | """ 9 | print("Hello ") 10 | 11 | def goodbyer(): 12 | """ 13 | Says goodbye 14 | """ 15 | print("Good bye ") 16 | 17 | if __name__ == "__main__": 18 | greeter() 19 | goodbyer() 20 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom03/main.py: -------------------------------------------------------------------------------- 1 | """ 2 | Main program using cake.py 3 | """ 4 | import cake 5 | # import cake as c 6 | # or 7 | # from cake import layer_cake 8 | 9 | cake.layer_cake("blue", "strawberries", "chocolate", 7) 10 | # c.layer_cake("blue", "strawberries", "chocolate", 7) 11 | # or 12 | # layer_cake("blue", "strawberries", "chocolate", 7) 13 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom03/main_for_greeters.py: -------------------------------------------------------------------------------- 1 | """ 2 | Imports greeters and calls functions. 3 | """ 4 | 5 | import greeters 6 | from persons import print_person 7 | 8 | greeters.greeter() 9 | print_person() 10 | greeters.goodbyer() 11 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom03/persons.py: -------------------------------------------------------------------------------- 1 | """ 2 | Person register 3 | """ 4 | 5 | person = "Marie" 6 | 7 | def print_person(): 8 | """ 9 | Prints the name of person 1 10 | """ 11 | print(person) 12 | 13 | 14 | if __name__ == "__main__": 15 | print_person() 16 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom03/praktisk_problemlosning/calculations.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module for calculations 3 | """ 4 | 5 | def cel_to_fahr(degrees): 6 | """ 7 | Converts from Celsius to Fahrenheit and returns degrees in Fahrenheit 8 | """ 9 | return degrees * (9/5) + 32 10 | 11 | def km_to_miles(distance): 12 | """ 13 | Converts from km to miles and returns the distance in miles 14 | """ 15 | d = distance * 0.621371 16 | return d 17 | 18 | if __name__ == "__main__": 19 | print(cel_to_fahr(13)) 20 | print(km_to_miles(141)) 21 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom03/praktisk_problemlosning/destination_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | Data for spaghetty module 3 | """ 4 | # All these variabels are hardcoded constanst and should be in capital letters 5 | # but I am using the same variable names as in the original file. 6 | 7 | # Starting point 8 | starting_point = "Karlskrona" 9 | 10 | # Data for first destination 11 | first_destination = "Osby" 12 | km_to_first_destination = 136 13 | degrees_celsius_at_first_destination = 13 14 | weather_at_first_destination = "Raining" 15 | 16 | # Data for seconde destionation 17 | second_destination = "Hillerød" 18 | km_to_second_destination = 141 19 | degrees_celsius_at_second_destination = 16 20 | weather_at_second_destination = "Sunny" 21 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom06/file_reader_task.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reads specified lines from file 3 | """ 4 | 5 | def read_specified_lines_from_file(filename, number_of_lines): 6 | """ 7 | Reads specified lines from file specified as first argument 8 | """ 9 | with open(filename, "r") as fh: 10 | lines = fh.readlines() 11 | 12 | for line in lines[:number_of_lines]: 13 | print(line.rstrip()) # rstrip removes whitespaces to the right, such as 14 | # space ' ', tab '\t', newline '\n' etc 15 | 16 | 17 | if __name__ == "__main__": 18 | specified_lines = int(input("How many lines do you want to print: ")) 19 | read_specified_lines_from_file("manifesto.txt", specified_lines) 20 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom06/manifesto.txt: -------------------------------------------------------------------------------- 1 | heeeeeeeejis better than ugly. 2 | Explicit is better than implicit. 3 | Simple is better than complex. 4 | Complex Is better than complicated. 5 | Flat is better than nested. 6 | Sparse Is better than dense. 7 | Readability counts. 8 | Special cases are not special enough to break the rules. 9 | Although practicality beats purity. 10 | Errors should never pass silently. 11 | Unless explicitly silenced. 12 | In the face of ambiguity, refuse the temptation to guess. 13 | There should be one -- and preferably only one -- obvious way to do it. 14 | Although that way may not be obvious at first unless you are Dutch. 15 | Now is better than never. 16 | Although never is often better than right now. 17 | If the implementation is hard to explain, it is a bad idea. 18 | If the implementation is easy to explain, it may be a good idea. 19 | Namespaces are one honking great idea -- let us do more of those!dslkdjdsaldjalksjdlk -------------------------------------------------------------------------------- /example/lectures/2022/kmom06/points_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Solve A5 in marvin1 using dictionaries 3 | """ 4 | def calculate_points(point_str): 5 | """ 6 | Calculated points for each player 7 | """ 8 | 9 | # loop in step of 2, [index] <=> player and [index + 1] <=> its points 10 | for index in range(0, len(point_str), 2): 11 | # Count the points, if upper subtract the points and if lower add the points 12 | print("Player " + point_str[index] + " with points: " + point_str[index + 1]) 13 | 14 | 15 | if __name__ == "__main__": 16 | calculate_points("g3l1H5l2G3l1") 17 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom06/points_2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Solve A5 in marvin1 using dictionaries 3 | """ 4 | def calculate_points(point_str): 5 | """ 6 | Calculated points for each player 7 | """ 8 | 9 | # loop in step of 2, [index] <=> player and [index + 1] <=> its points 10 | for index in range(0, len(point_str), 2): 11 | # Count the points, if upper subtract the points and if lower add the points 12 | if point_str[index].isupper(): 13 | current_points = int(point_str[index + 1]) * -1 14 | else: 15 | current_points = int(point_str[index + 1]) 16 | print("Player " + point_str[index].lower() + " with points: " + str(current_points)) 17 | 18 | 19 | if __name__ == "__main__": 20 | calculate_points("g3l1H5l2G3l1") 21 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom06/points_3.py: -------------------------------------------------------------------------------- 1 | """ 2 | Solve A5 in marvin1 using dictionaries 3 | """ 4 | def calculate_points(point_str): 5 | """ 6 | Calculated points for each player 7 | """ 8 | player_dict = {} 9 | 10 | # loop in step of 2, [index] <=> player and [index + 1] <=> its points 11 | for index in range(0, len(point_str), 2): 12 | # Count the points, if upper subtract the points and if lower add the points 13 | if point_str[index].isupper(): 14 | current_points = int(point_str[index + 1]) * -1 15 | else: 16 | current_points = int(point_str[index + 1]) 17 | 18 | # Fill the dictionary with player and score 19 | if point_str[index].lower() in player_dict: # if player exists in the dictionary 20 | player_dict[point_str[index].lower()] += current_points 21 | else: 22 | player_dict[point_str[index].lower()] = current_points 23 | 24 | print(player_dict) 25 | 26 | if __name__ == "__main__": 27 | calculate_points("g3l1H5l2G3l1") 28 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom06/read_from.txt: -------------------------------------------------------------------------------- 1 | Hej jag 2 | heter 3 | Marie och 4 | bredvid mig sitter 5 | Andreas 6 | Så här ser åäö ut -------------------------------------------------------------------------------- /example/lectures/2022/kmom06/read_from_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reads from file 3 | """ 4 | 5 | def read_from_file(filename): 6 | """ 7 | Reads from file specified as argument 8 | """ 9 | # with opens the file, reads and closes the file with the statement is finished 10 | #with open(filename, "r") as filehandler: # read is default, add "r" to clarify 11 | # print(filehandler.read()) # read(10), only the 10 first characters are read 12 | 13 | with open(filename, "r", encoding='utf8') as filehandler: 14 | content = filehandler.readlines() 15 | 16 | return content 17 | 18 | if __name__ == "__main__": 19 | line_list = read_from_file("read_from.txt") 20 | print(line_list) 21 | -------------------------------------------------------------------------------- /example/lectures/2022/kmom06/write_to_file.py: -------------------------------------------------------------------------------- 1 | def open_file(): 2 | """ 3 | read file content 4 | """ 5 | try: 6 | # fd = open("data.txt", "r") 7 | with open("manifesto.txt", "r") as fd: 8 | return fd.read() 9 | except FileNotFoundError: 10 | print("You are missing the file") 11 | return None 12 | 13 | 14 | def add_line(): 15 | """ 16 | add new line to file 17 | """ 18 | new_line = input("Enter new line: ") 19 | with open("data.txt","a") as fd: 20 | fd.write("\n" + new_line) 21 | 22 | 23 | def menu(): 24 | """ 25 | Main menu for program 26 | """ 27 | while True: 28 | inp = input("""Enter option: 29 | 1. Read replace 30 | 2. insert new line 31 | 3. remove line 32 | """) 33 | if inp == "1": 34 | print(open_file()) 35 | elif inp == "2": 36 | add_line() 37 | elif inp == "3": 38 | pass 39 | else: 40 | exit() 41 | 42 | 43 | if __name__ == "__main__": 44 | menu() 45 | -------------------------------------------------------------------------------- /example/marvin/format.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Example of how to use format on a string that contains placeholders {} 4 | """ 5 | 6 | import random 7 | 8 | with open("format.txt") as fhand: 9 | line = fhand.readline() 10 | 11 | moods = ["happy", "sad", "depressed", "angry", "annoyed", "bored", "confused", "excited", "lonely"] 12 | mood = random.choice(moods) 13 | smilies = [":)", ":(", ":D", ":/", ":|", ":'(", ":O", ":@", ":P", ":3"] 14 | smiley = random.choice(smilies) 15 | 16 | print(line.format(mood=mood, smiley=smiley)) 17 | -------------------------------------------------------------------------------- /example/marvin/format.txt: -------------------------------------------------------------------------------- 1 | Hello. I'm feeling {mood} {smiley}. -------------------------------------------------------------------------------- /example/marvin/quotes_lgtg.txt: -------------------------------------------------------------------------------- 1 | Life? Don't talk to me about life! 2 | Incredible... it's even worse than I thought it would be. 3 | Not that anyone cares what I say, but the restaurant is at the *other* end of the Universe. 4 | I've calculated your chance of survival, but I don't think you'll like it. 5 | Here I am, brain the size of a planet, and they ask me to take you to the bridge. Call that job satisfaction, 'cause I don't. 6 | I have a million ideas, but, they all point to certain death. 7 | Do you want me to sit in a corner and rust or just fall apart where I'm standing? 8 | You think you've got problems. What are you supposed to do if you are a manically depressed robot? No, don't even bother answering. I'm 50,000 times more intelligent than you and even I don't know the answer. 9 | I ache, therefore I am. 10 | My capacity for happiness you could fit into a matchbox without taking out the matches first. 11 | I'd give you advice, but you wouldn't listen. No one ever does. -------------------------------------------------------------------------------- /example/module_lecture/data.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbwebb-se/python/ee7c85cfd6db49592b98fe5b1126a40e9b4d6a6a/example/module_lecture/data.txt -------------------------------------------------------------------------------- /example/module_lecture/edit.py: -------------------------------------------------------------------------------- 1 | """ 2 | Edit content in file 3 | """ 4 | def menu(): 5 | """ 6 | Print menu for program 7 | """ 8 | print(""" 9 | a: Lägg till formatrad 10 | s: Radera innehåll 11 | q: quit 12 | """) 13 | 14 | def add(): 15 | """ 16 | Add to file 17 | """ 18 | line = input("Skriv en formatrad: ") 19 | with open("data.txt", "a") as fd: 20 | fd.write(line) 21 | 22 | def remove(): 23 | """ 24 | remove from file 25 | """ 26 | line = input("Vill du verkligen ta bort allt: ") 27 | if line == "ja": 28 | with open("data.txt", "w") as fd: 29 | fd.write("") 30 | 31 | def main(): 32 | """ 33 | Starting point of program 34 | """ 35 | while True: 36 | menu() 37 | choice = input("Gör ett val: ") 38 | if choice == "q": 39 | break 40 | elif choice == "a": 41 | add() 42 | elif choice == "d": 43 | remove() 44 | else: 45 | print("Not an option!") 46 | 47 | 48 | if __name__ == "__main__": 49 | main() 50 | -------------------------------------------------------------------------------- /example/module_lecture/formatted_lines.txt: -------------------------------------------------------------------------------- 1 | Ut Andreas ad minim veniam, 2 | Lorem Emil dolor sit amet 3 | -------------------------------------------------------------------------------- /example/module_lecture/random_lines.txt: -------------------------------------------------------------------------------- 1 | Lorem {} dolor sit amet 2 | consectetur {} elit 3 | sed do {} tempor incididunt 4 | ut labore et {} magna aliqua. 5 | Ut {} ad minim veniam, 6 | quis nostrud {} 7 | -------------------------------------------------------------------------------- /example/module_lecture/shop.py: -------------------------------------------------------------------------------- 1 | """ 2 | Work with file by adding a shoppinglist 3 | """ 4 | def add(choice): 5 | """ 6 | Add to file 7 | """ 8 | with open("shopping_list.txt", "a") as fd: 9 | fd.write(choice + "\n") 10 | 11 | def remove(): 12 | """ 13 | Empty file 14 | """ 15 | with open("shopping_list.txt", "w") as fd: 16 | fd.write("") 17 | 18 | def print_shopping_list(): 19 | """ 20 | print lines from file 21 | """ 22 | with open("shopping_list.txt", "r") as fd: 23 | print(fd.read()) 24 | 25 | remove() 26 | 27 | def main(): 28 | """ 29 | Starting point of program 30 | """ 31 | while True: 32 | choice = input("Skriv en vara, avsluta med shop: ") 33 | if choice == "shop": 34 | print_shopping_list() 35 | break 36 | else: 37 | add(choice) 38 | 39 | if __name__ == "__main__": 40 | main() 41 | -------------------------------------------------------------------------------- /example/module_lecture/shopping_list.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbwebb-se/python/ee7c85cfd6db49592b98fe5b1126a40e9b4d6a6a/example/module_lecture/shopping_list.txt -------------------------------------------------------------------------------- /example/module_lecture/start/clothes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module concerned with clothes 3 | """ 4 | 5 | 6 | print("This is my name", __name__) 7 | print() 8 | -------------------------------------------------------------------------------- /example/module_lecture/start/shoes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module concerned with shoes 3 | """ 4 | -------------------------------------------------------------------------------- /example/module_lecture/work/clothes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module concerned with clothes 3 | """ 4 | 5 | def jeans(): 6 | """ 7 | Function that prints about relaxed footwear 8 | """ 9 | print("My workmans pants that has turned high fashion") 10 | 11 | def rain_coat(): 12 | """ 13 | Function that prints about clothes for rainy days 14 | """ 15 | print("I'm singing in the rain, because I wear a raincoat") 16 | 17 | def suit(): 18 | """ 19 | Function that prints about formal wear 20 | """ 21 | print("My name is Bond, James Bond!") 22 | 23 | if __name__ == "__main__": 24 | jeans() 25 | rain_coat() 26 | suit() 27 | -------------------------------------------------------------------------------- /example/module_lecture/work/main.py: -------------------------------------------------------------------------------- 1 | """ 2 | Main program that calls a lot of functions 3 | """ 4 | import shoes 5 | from clothes import jeans 6 | from clothes import rain_coat 7 | from clothes import suit 8 | 9 | def main(): 10 | """ 11 | Starting point of program 12 | """ 13 | print("I will now print information about shoes and clothes:") 14 | print() 15 | 16 | jeans() 17 | shoes.sneakers() 18 | rain_coat() 19 | shoes.high_heels() 20 | shoes.galosh() 21 | shoes.slippers() 22 | suit() 23 | 24 | print(__name__) 25 | 26 | if __name__ == "__main__": 27 | main() 28 | -------------------------------------------------------------------------------- /example/module_lecture/work/shoes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module concerned with shoes 3 | """ 4 | 5 | def sneakers(): 6 | """ 7 | Function that prints about relaxed footwear 8 | """ 9 | print("Uhhhhhhh, nice comfy feel") 10 | 11 | def slippers(): 12 | """ 13 | Function that prints about the most relaxed footwear 14 | """ 15 | print("Ahhhhhhh, this is the best") 16 | 17 | def high_heels(): 18 | """ 19 | Function that prints about formal footwear 20 | """ 21 | print("Ohhhhhhh, my feet hurts") 22 | 23 | def galosh(): 24 | """ 25 | Function that prints about something in between 26 | """ 27 | print("Clothes or shoes, thats the question") 28 | -------------------------------------------------------------------------------- /example/old_exams/lp1-2018/.dbwebb/correct.bash: -------------------------------------------------------------------------------- 1 | dbwebb test lp1-2018 -------------------------------------------------------------------------------- /example/old_exams/lp1-2018/README.md: -------------------------------------------------------------------------------- 1 | 2 | Lösningsförlsag för try1 i lp1 2018 3 | ==================================== 4 | 5 | För att öva på denna examinationen, kopiera denna mappen in i `me/kmom10/`. Om du står i pythons root map, kör `cp -r example/old_exams/lp1-2018 me/kmom10/`. 6 | 7 | För att köra programmet med testerna: 8 | 9 | ```bash 10 | dbwebb test lp1-2018 11 | ``` -------------------------------------------------------------------------------- /example/old_exams/lp1-2018/exam.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Write your code in this file. Fill out the defined functions with your solutions. 4 | You are free to write additional functions and modules as you see fit. 5 | """ 6 | 7 | 8 | def analyze_text(): 9 | """ 10 | Assignment 1 11 | """ 12 | return True 13 | 14 | 15 | 16 | def validate_mobile(number): 17 | """ 18 | Assignment 2 19 | """ 20 | return number 21 | 22 | 23 | 24 | def verify_credit_card(number): 25 | """ 26 | Assignment 3 27 | """ 28 | return number 29 | 30 | 31 | 32 | def find_difference(items, items2): 33 | """ 34 | Assignment 4 35 | """ 36 | return items, items2 37 | 38 | 39 | 40 | def validate_date_time(): 41 | """ 42 | Assignment 5 43 | """ 44 | return True 45 | 46 | 47 | 48 | if __name__ == '__main__': 49 | analyze_text() 50 | validate_mobile("") 51 | verify_credit_card("") 52 | find_difference([], []) 53 | validate_date_time() 54 | -------------------------------------------------------------------------------- /example/old_exams/lp1-2018/value-of-time.txt: -------------------------------------------------------------------------------- 1 | Once, a king and a lazy man named Haria were very good friends. At precisely 08:00 on 2018-10-30, the king said, 'Why don't you do work to earn some money?' 2 | 3 | 4 | Haria said, 'No one gives me job at 9 in the morning. My enemies told everyone that I never do any work in time by 2019-9-10.' 5 | 6 | 7 | The kind king said, 'You can go into my treasury and collect as much wealth as you can, till 21:03.' 8 | 9 | 10 | Haria rushed home to tell this to his wife. She said, 'Go and get the gold coins and gems before 21:3.' 11 | 12 | 13 | 'I cannot go now. Give me lunch first at 12:15.' 14 | 15 | 16 | After 13:100, he took a nap for until 13:15. Then in the late afternoon on 2018-11:30 at 16:30, he picked some bags and went to the palace. On the way, he felt hot so he sat under a tree to rest. Then, two hours later at 18:30, he got up to go but saw a man showing some magic tricks. He stopped to watch for an until 21:04. 17 | 18 | 19 | When he reached the palace it was already after 21:03. The palace gates had been shut. So Haria had lost a golden chance because he had not learned the value of time on the 2018-13-01, a beautiful day. -------------------------------------------------------------------------------- /example/old_exams/lp1-2019/README.md: -------------------------------------------------------------------------------- 1 | 2 | Lösningsförlsag för try1 i lp1 2019 3 | ==================================== 4 | 5 | För att öva på denna examinationen, kopiera denna mappen in i `me/kmom10/`. Om du står i pythons root map, kör `cp -r example/old_exams/lp1-2019 me/kmom10/`. 6 | 7 | I `solution.py` hittar du ett lösningsförslag. 8 | 9 | För att köra programmet med testerna: 10 | 11 | ```bash 12 | dbwebb test lp1-2019 13 | ``` -------------------------------------------------------------------------------- /example/old_exams/lp1-2019/exam.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Write your code in this file. Fill out the defined functions with your solutions. 4 | You are free to write additional functions and modules as you see fit. 5 | """ 6 | 7 | def find_replace(): 8 | """ 9 | Assignment 1 10 | """ 11 | return None 12 | 13 | def count_animals(animals): 14 | """ 15 | Assignment 2 16 | """ 17 | return animals 18 | 19 | 20 | def validate_isbn(numbers): 21 | """ 22 | Assignment 3 23 | """ 24 | return numbers 25 | 26 | def decide_winners(matches): 27 | """ 28 | Assignment 4 29 | """ 30 | return matches 31 | 32 | 33 | 34 | def validate_bookings(bookings): 35 | """ 36 | Assignment 5 37 | """ 38 | return bookings 39 | 40 | 41 | 42 | if __name__ == '__main__': 43 | find_replace() 44 | count_animals({}) 45 | validate_isbn("") 46 | decide_winners([]) 47 | validate_bookings([]) 48 | -------------------------------------------------------------------------------- /example/old_exams/lp1-2019/manifesto.txt: -------------------------------------------------------------------------------- 1 | Beautiful is better than ugly. 2 | Explicit is better than implicit. 3 | Simple is better than complex. 4 | Complex Is better than complicated. 5 | Flat is better than nested. 6 | Sparse Is better than dense. 7 | Readability counts. 8 | Special cases are not special enough to break the rules. 9 | Although practicality beats purity. 10 | Errors should never pass silently. 11 | Unless explicitly silenced. 12 | In the face of ambiguity, refuse the temptation to guess. 13 | There should be one -- and preferably only one -- obvious way to do it. 14 | Although that way may not be obvious at first unless you are Dutch. 15 | Now is better than never. 16 | Although never is often better than right now. 17 | If the implementation is hard to explain, it is a bad idea. 18 | If the implementation is easy to explain, it may be a good idea. 19 | Namespaces are one honking great idea -- let us do more of those! -------------------------------------------------------------------------------- /example/old_exams/lp1-2020/.dbwebb/correct.bash: -------------------------------------------------------------------------------- 1 | dbwebb test lp1-2020 -------------------------------------------------------------------------------- /example/old_exams/lp1-2020/README.md: -------------------------------------------------------------------------------- 1 | 2 | Lösningsförlsag för try1 i lp1 2020 3 | ==================================== 4 | 5 | För att öva på denna examinationen, kopiera denna mappen in i `me/kmom10/`. Om du står i pythons root map, kör `cp -r example/old_exams/lp1-2020 me/kmom10/`. 6 | 7 | I `solution.py` hittar du ett lösningsförslag. 8 | 9 | För att köra programmet med testerna: 10 | 11 | ```bash 12 | dbwebb test lp1-2020 13 | ``` -------------------------------------------------------------------------------- /example/old_exams/lp1-2020/analyze_functions_solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module 3 | """ 4 | 5 | def title(data): 6 | """ 7 | find non-matching titles 8 | """ 9 | for row in data: 10 | cells = row.split(",") 11 | 12 | if cells[1] != cells[2]: 13 | print(cells[1], end=":") 14 | get_with_key(cells[0], 1) 15 | 16 | def year(data): 17 | """ 18 | year input 19 | """ 20 | i_year = input("What i_year? ") 21 | for row in data: 22 | cells = row.split(",") 23 | 24 | if cells[3] == i_year: 25 | print(cells[2], end=":") 26 | get_with_key(cells[0], -1) 27 | 28 | def get_with_key(key, column): 29 | """ 30 | get column value with key 31 | """ 32 | with open("title.ratings.csv") as fd: 33 | rows = fd.read().split("\n") 34 | for row in rows: 35 | cells = row.split(",") 36 | if cells[0] == key: 37 | print(cells[column]) 38 | -------------------------------------------------------------------------------- /example/old_exams/lp1-2020/exam.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Write your code in this file. Fill out the defined functions with your solutions. 4 | You are free to write additional functions and modules as you see fit. 5 | """ 6 | 7 | def analyze_text(): 8 | """ 9 | Assignment 1 10 | """ 11 | return None 12 | 13 | def reversed_sum(numbers, operator): 14 | """ 15 | Assignment 2 16 | """ 17 | return numbers, operator 18 | 19 | 20 | 21 | def repeating_letter_distance(string): 22 | """ 23 | Assignment 3 24 | """ 25 | return string 26 | 27 | 28 | 29 | def find_word(line, n, option=None): 30 | """ 31 | Assignment 4 32 | """ 33 | return line, n, option 34 | 35 | 36 | def frequency_sort(sequence): 37 | """ 38 | Assignment 5 39 | """ 40 | return sequence 41 | 42 | 43 | 44 | if __name__ == '__main__': 45 | analyze_text() 46 | reversed_sum([], "") 47 | frequency_sort("") 48 | find_word("", 0) 49 | repeating_letter_distance([]) 50 | -------------------------------------------------------------------------------- /example/old_exams/lp1-2020/title.ratings.csv: -------------------------------------------------------------------------------- 1 | id,averageRating,numVotes 2 | tt0000001,5.6,1654 3 | tt0000002,6.1,199 4 | tt0000003,6.5,1365 5 | tt0000004,6.2,121 6 | tt0000005,6.2,2149 7 | tt0000006,5.3,115 8 | tt0000007,5.5,659 9 | tt0000008,5.4,1821 10 | tt0000009,5.9,156 11 | tt0000010,6.9,6072 12 | tt0000011,5.2,266 13 | tt0000012,7.4,10394 14 | tt0000013,5.7,1583 15 | tt0000014,7.1,4646 16 | tt0000015,6.1,825 17 | tt0000016,5.9,1211 18 | tt0000017,4.6,243 19 | tt0000018,5.3,481 20 | tt0000019,5.3,20 21 | tt0000020,5,268 22 | tt0000022,5.1,895 23 | tt0000023,5.7,1150 24 | tt0000024,4.5,54 25 | tt0000025,4.2,29 26 | tt0000026,5.7,1317 27 | tt0000027,5.6,934 28 | tt0000028,5.1,861 29 | tt0000029,5.9,2878 30 | tt0000030,5.2,690 31 | tt0000031,5.5,842 32 | tt0000032,5.1,341 33 | tt0000033,5.6,859 34 | tt0000034,5.3,135 35 | tt0000035,5.6,59 36 | tt0000036,4.4,495 37 | tt0000037,4.7,44 38 | tt0000038,4.1,150 39 | tt0000039,3.7,15 40 | tt0000040,4.3,40 41 | tt0000041,6.7,1468 42 | tt0000042,4.8,24 43 | tt0000043,4,15 44 | tt0000044,4.7,30 45 | tt0000045,4.9,19 46 | tt0000046,4.6,19 47 | tt0000047,4,18 48 | tt0000048,4.8,129 49 | tt0000050,4.5,16 -------------------------------------------------------------------------------- /example/old_exams/lp1-2021/.dbwebb/correct.bash: -------------------------------------------------------------------------------- 1 | dbwebb test try1 -------------------------------------------------------------------------------- /example/old_exams/lp1-2021/exam.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Write your code in this file. Fill out the defined functions with your solutions. 4 | You are free to write additional functions and modules as you see fit. 5 | """ 6 | 7 | def count_elements(formula): 8 | """ 9 | Assignment 1 10 | """ 11 | return formula 12 | 13 | 14 | def fotball_results(teams, matches): 15 | """ 16 | Assignment 2 17 | """ 18 | return teams, matches 19 | 20 | 21 | 22 | def subset_zero(): 23 | """ 24 | Assignment 3 25 | """ 26 | 27 | 28 | 29 | def jolly(numbers): 30 | """ 31 | Assignment 4 32 | """ 33 | return numbers 34 | 35 | 36 | 37 | def compare_banks(): 38 | """ 39 | Assignment 5 40 | """ 41 | 42 | 43 | if __name__ == '__main__': 44 | count_elements("") 45 | fotball_results((), []) 46 | subset_zero() 47 | jolly([]) 48 | compare_banks() 49 | -------------------------------------------------------------------------------- /example/old_exams/lp1-2021/numbers.txt: -------------------------------------------------------------------------------- 1 | 1, 2, 3 2 | 1, 2, 3, 0 3 | -5, -3, -1, 2, 4, 6 4 | -97364, -71561, -69336, 19675, 71561, 97863 5 | -53974, -39140, -36561, -23935, -15680, 0 6 | 1, 2, 3, 23 7 | -1, 1 8 | -1, 10, 4, 24 -------------------------------------------------------------------------------- /example/old_exams/lp1-2021/savingscentral_solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | saving central savings 3 | """ 4 | 5 | def money_growth(amount, years=10): 6 | """ 7 | Calculates the money growth 8 | Returns the amount 9 | """ 10 | if years < 0: 11 | raise ValueError("Can't turn back time") 12 | interest = 0.0078 13 | 14 | growth = amount * interest * years 15 | 16 | return round(growth, 2) 17 | -------------------------------------------------------------------------------- /example/old_exams/lp1-2021/stockbank_solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | stock bank savings 3 | """ 4 | def money_growth(amount, years=10): 5 | """ 6 | Calculates the money growth 7 | Returns the amount 8 | """ 9 | if years < 0: 10 | raise ValueError("Can't turn back time") 11 | interest = 0.051 12 | fee = 0.1 13 | 14 | growth = amount * interest * years 15 | return round(growth - fee * growth, 2) 16 | -------------------------------------------------------------------------------- /example/old_exams/prep/.dbwebb/correct.bash: -------------------------------------------------------------------------------- 1 | dbwebb test prep -------------------------------------------------------------------------------- /example/old_exams/prep/README.md: -------------------------------------------------------------------------------- 1 | 2 | Lösningsförlsag för övningstentan 3 | ==================================== 4 | 5 | För att öva på denna examinationen, kopiera denna mappen in i `me/kmom10/`. Om du står i pythons root map, kör `cp -r example/old_exams/prep me/kmom10/`. 6 | 7 | I `solution.py` hittar du ett lösningsförslag. 8 | 9 | För att köra programmet med testerna: 10 | 11 | ```bash 12 | dbwebb test prep 13 | ``` -------------------------------------------------------------------------------- /example/old_exams/prep/analyze_functions_solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module for analyze functions 3 | """ 4 | def vowels(): 5 | """ 6 | vowels 7 | """ 8 | vowels_ = "aeiouy" 9 | text = read_file().lower() 10 | counter = 0 11 | for c in text: 12 | if c in vowels_: 13 | counter += 1 14 | return counter 15 | 16 | def periods(): 17 | """ 18 | Persiods 19 | """ 20 | return read_file().count(".") 21 | 22 | def uppers(): 23 | """ 24 | Uppers 25 | """ 26 | text = read_file() 27 | counter = 0 28 | for c in text: 29 | if c.isupper(): 30 | counter += 1 31 | return counter 32 | 33 | def read_file(): 34 | """ 35 | Read file 36 | """ 37 | with open("manifesto.txt", "r") as fh: 38 | return fh.read() 39 | -------------------------------------------------------------------------------- /example/old_exams/prep/exam.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Write your code in this file. Fill out the defined functions with your solutions. 4 | You are free to write additional functions and modules as you see fit. 5 | """ 6 | 7 | def analyze_text(): 8 | """ 9 | Assignment 1 updated 10 | """ 11 | return True 12 | 13 | def validate_email(email): 14 | """ 15 | Assignment 2 updated 16 | """ 17 | return email 18 | 19 | def list_median(values): 20 | """ 21 | Assignment 3 updated 22 | """ 23 | return values 24 | 25 | def find_duplicates(values): 26 | """ 27 | Assignment 4 updated 28 | """ 29 | return values 30 | 31 | def types(items): 32 | """ 33 | Assignment 5 updated 34 | """ 35 | return items 36 | 37 | if __name__ == '__main__': 38 | analyze_text() 39 | list_median([]) 40 | find_duplicates([]) 41 | types([]) 42 | validate_email("") 43 | -------------------------------------------------------------------------------- /example/old_exams/prep/manifesto.txt: -------------------------------------------------------------------------------- 1 | Beautiful is better than ugly. 2 | Explicit is better than implicit. 3 | Simple is better than complex. 4 | Complex is better than complicated. 5 | Flat is better than nested. 6 | Sparse is better than dense. 7 | Readability counts. 8 | Special cases aren't special enough to break the rules. 9 | Although practicality beats purity. 10 | Errors should never pass silently. 11 | Unless explicitly silenced. 12 | In the face of ambiguity, refuse the temptation to guess. 13 | There should be one-- and preferably only one --obvious way to do it. 14 | Although that way may not be obvious at first unless you're Dutch. 15 | Now is better than never. 16 | Although never is often better than *right* now. 17 | If the implementation is hard to explain, it's a bad idea. 18 | If the implementation is easy to explain, it may be a good idea. 19 | Namespaces are one honking great idea -- let's do more of those! -------------------------------------------------------------------------------- /example/ping/ping.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Example of how to ping a webpage for a status code, basically just 6 | to check that the page is there and the webserver is replying with 7 | a positive code, such as 200. 8 | 9 | More information: http://stackoverflow.com/a/13641613 10 | 11 | The module requests needs to be installed with pip 12 | http://docs.python-requests.org/en/latest/ 13 | pip install requests 14 | """ 15 | 16 | import time 17 | import requests 18 | 19 | print(__doc__) 20 | 21 | url = "https://dbwebb.se/humans.txt" 22 | 23 | 24 | try: 25 | 26 | # Get current time 27 | rTime = time.ctime(time.time()) 28 | 29 | # Request header from url 30 | print("Ready to send HTTP request to ", url, "\n(press return)", end='') 31 | input() 32 | req = requests.head(url) 33 | 34 | # Print result 35 | print("Request to ", url, " sent at ", rTime) 36 | print("Recieved status code: ", req.status_code) 37 | print("Page was last modified: ", req.headers["Last-Modified"]) 38 | 39 | 40 | except requests.ConnectionError: 41 | 42 | print("Failed to connect") 43 | -------------------------------------------------------------------------------- /example/pylint/generate.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Read pylint error codes to md-file. 4 | 5 | echo "# Pylint error codes" > messages.md 6 | echo 'This is the messages given from the command `pylint --list-msgs` with Pylint version 1.6.5' >> messages.md 7 | pylint --list-msgs | while read line ; 8 | 9 | do 10 | if [[ $line == :* ]];then 11 | echo "___" 12 | printf "### " 13 | echo "$line"|awk '{print $1}' | cut -c2- 14 | printf "###### " 15 | echo "$line"|awk '{$1=""; print $0}' 16 | else 17 | echo $line 18 | fi; 19 | done >> messages.md 20 | -------------------------------------------------------------------------------- /example/quote/get-quote.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Get a random quote from a webservice and print it out. 6 | 7 | The webservice in the example is: 8 | http://dbwebb.se/javascript/lekplats/get-marvin-quotes-using-ajax/quote.php 9 | """ 10 | 11 | import requests 12 | 13 | 14 | 15 | print(__doc__) 16 | input("Press enter to continue. ") 17 | 18 | 19 | url = "http://dbwebb.se/javascript/lekplats/get-marvin-quotes-using-ajax/quote.php" 20 | 21 | 22 | try: 23 | 24 | print("\nReady to send HTTP request to ", url, "\nPress enter to continue. ", end='') 25 | input() 26 | req = requests.get(url) 27 | 28 | print("\nThe response status code is:\n", req.status_code) 29 | 30 | print("\nThe response body is:\n", req.text) 31 | 32 | json = req.json() 33 | print(f"\nQuote of today is:\n\"{json['quote']}\"\n") 34 | 35 | 36 | except requests.ConnectionError: 37 | 38 | print("Failed to connect.") 39 | -------------------------------------------------------------------------------- /example/real_path/real_path.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | How to get absolute path for current directory 4 | """ 5 | import os 6 | dir_path = os.path.dirname(os.path.realpath(__file__)) 7 | print(dir_path) 8 | -------------------------------------------------------------------------------- /example/redovisa/img/marvin.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dbwebb-se/python/ee7c85cfd6db49592b98fe5b1126a40e9b4d6a6a/example/redovisa/img/marvin.jpg -------------------------------------------------------------------------------- /example/redovisa/js/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * JavaScript code to be included 3 | */ 4 | -------------------------------------------------------------------------------- /example/redovisa/om.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Om kursen | python 6 | 7 | 8 | 9 | 10 | 11 | 16 | 17 |
18 | 19 |

Om

20 |

Denna webbplatsen är en del av kursen python.

21 | 22 |
23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /example/redovisa/style/style.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Style 3 | */ 4 | body { 5 | margin: 8px auto; 6 | color: #333; 7 | max-width: 600px; 8 | overflow-y: scroll; 9 | } 10 | 11 | h1 { 12 | border-bottom: 1px solid #666; 13 | } 14 | 15 | h2 { 16 | border-bottom: 1px solid #ccc; 17 | } 18 | 19 | pre { 20 | white-space: pre-wrap; 21 | } 22 | -------------------------------------------------------------------------------- /example/scrape/irc-from-dbwebb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Show off how to scrape information from a webpage. 6 | """ 7 | 8 | from bs4 import BeautifulSoup 9 | import requests 10 | 11 | 12 | 13 | print(__doc__) 14 | input("Press enter to continue. ") 15 | 16 | 17 | 18 | # Get webpage 19 | url = "https://dbwebb.se/irclog/" 20 | print("\nReady to send HTTP request to ", url, "\nPress enter to continue. ", end='') 21 | input() 22 | req = requests.get(url) 23 | print("\nThe response status code is:\n", req.status_code) 24 | 25 | 26 | 27 | # Get the webpage content as a soup 28 | #soup = BeautifulSoup(req.text, "html5lib") 29 | soup = BeautifulSoup(req.text) 30 | 31 | # Find the intresting parts in the soup 32 | ircLog = soup.find("table") 33 | logText = [element.text for element in ircLog.tr.findAll("td")] 34 | 35 | # Print out the content 36 | formatString = "{} <{}> {}" 37 | print("\nLast entry in IRC-log:") 38 | print(formatString.format(*logText)) 39 | -------------------------------------------------------------------------------- /example/text/lorum.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae aliquet dolor. 2 | Vivamus neque dui, varius in iaculis a, imperdiet at ligula. 3 | Donec dapibus urna. -------------------------------------------------------------------------------- /example/try-except/input-integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Show how exceptions and try catch can be used 6 | to handle troubles when reading integer variabels 7 | using input. 8 | 9 | """ 10 | 11 | print(__doc__) 12 | 13 | msg1 = "The integer value is {value}." 14 | msg2 = "The type of the variabel is {type}." 15 | 16 | # Read as string 17 | aValue = input("Enter a integer value: ") 18 | 19 | aType = type(aValue) 20 | 21 | print(msg1.format(value=aValue)) 22 | print(msg1.format(value=aType)) 23 | 24 | 25 | 26 | # Read as integer 27 | while True: 28 | aValue = input("Enter a integer value: ") 29 | try: 30 | aValue = int(aValue) 31 | except Exception: 32 | print("FAIL: You did not enter a integer.") 33 | continue 34 | break 35 | 36 | aType = type(aValue) 37 | 38 | print(msg1.format(value=aValue)) 39 | print(msg1.format(value=aType)) 40 | -------------------------------------------------------------------------------- /example/typing/easy.txt: -------------------------------------------------------------------------------- 1 | I fear Not the man who 2 | has practiced Ten thousand 3 | kicks once but I Fear 4 | the man who has Practiced 5 | one Kick ten thousand times -------------------------------------------------------------------------------- /example/typing/hard.txt: -------------------------------------------------------------------------------- 1 | And when they saw that the 1 pool 2 | had changed from a cup-of_sweet 3 | waters into 7 , 4 | they loosened the 36 (green) tresses 5 | of their hair & cried to the 6 | pool and said; `We do not wonder 7 | that you should mourn in this 8 | manner for Narcissus, so beautiful 9 | was he.' "But was Narcissus 10 | beautiful?' said the pool! 11 | *Who should know that better than you?: 12 | answered the 95 [Oreads]. -------------------------------------------------------------------------------- /example/typing/medium.txt: -------------------------------------------------------------------------------- 1 | One day 4 little Monsters 2 | were going to their 6 Beds 3 | There Were 2 Birds on their beds 4 | 10 minutes Later 9 cars 5 | passd by And 7 monsters Jumped 6 | Out of the Cars Then 82 typhoons 7 | blew 1 trees Fell down 8 | and 37 typhoons came -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "course-repo-validation-tools", 3 | "version": "1.0.0", 4 | "private": true, 5 | "devDependencies": { 6 | "clean-css": "^3.4.12", 7 | "csslint": "^0.10.0", 8 | "html-minifier": "^0.8.0", 9 | "htmlhint": "0.9.12", 10 | "js-yaml": "^3.6.1", 11 | "jscs": "^3.0.7", 12 | "jshint": "^2.9.5", 13 | "jsonlint": "^1.6.2", 14 | "uglify-js": "^2.6.2", 15 | "eslint": "^4.5.0", 16 | "eslint-plugin-react": "^7.3.0" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tutorial/for.md: -------------------------------------------------------------------------------- 1 | for 2 | ============================== 3 | Examples in Python 3 4 | 5 | 6 | ```python 7 | """ 8 | Loop through list of items 9 | """ 10 | my_list = [1,2,3] 11 | for x in my_list: 12 | print(x) 13 | 14 | my_list = ["one", "two", "three"] 15 | for x in my_list: 16 | print(x) 17 | 18 | 19 | """ 20 | Loop through the characters in a string 21 | """ 22 | my_str = "Hello" 23 | for x in my_str: 24 | print(x) 25 | 26 | 27 | ``` 28 | 29 | 30 | Reference and read more 31 | ------------------------------ 32 | 33 | [for Statements](https://docs.python.org/3/tutorial/controlflow.html#for-statements) 34 | 35 | [The for statement](https://docs.python.org/3/reference/compound_stmts.html#for) 36 | 37 | 38 | 39 | Revision history 40 | ------------------------------ 41 | 42 | 2014-07-17 (sylvanas) PA1 First try. 43 | -------------------------------------------------------------------------------- /tutorial/functions.md: -------------------------------------------------------------------------------- 1 | functions 2 | ============================== 3 | Examples in Python 3 4 | 5 | 6 | ```python 7 | """ 8 | Define a simple function 9 | """ 10 | def test(): 11 | print("This is a test") 12 | 13 | test() 14 | 15 | 16 | """ 17 | Define a function with a parameter 18 | """ 19 | def test2(someText): 20 | print("Parameter was: " + someText) 21 | 22 | test2("Hello world!") 23 | 24 | 25 | """ 26 | Define a function with a return 27 | """ 28 | def test3(someText, x): 29 | return someText * x 30 | 31 | test_return = test3("Hello", 3) 32 | print(test_return) 33 | 34 | 35 | ``` 36 | 37 | 38 | Reference and read more 39 | ------------------------------ 40 | 41 | [Function definitions](https://docs.python.org/3/reference/compound_stmts.html#function-definitions) 42 | 43 | [Defining Functions](https://docs.python.org/3/tutorial/controlflow.html#defining-functions) 44 | 45 | 46 | 47 | Revision history 48 | ------------------------------ 49 | 50 | 2014-07-17 (sylvanas) PA1 First try. 51 | -------------------------------------------------------------------------------- /tutorial/if.md: -------------------------------------------------------------------------------- 1 | If, elif, else 2 | ============================== 3 | Examples in Python 3 4 | 5 | 6 | ```python 7 | """ 8 | Do something if a variable has a certain value. 9 | """ 10 | val = True 11 | 12 | if val: 13 | print("YES") 14 | 15 | # Above is the same as this 16 | if val == True: 17 | print("YES") 18 | 19 | 20 | """ 21 | Add an else statement. 22 | """ 23 | if val: 24 | print("YES") 25 | else: 26 | print("NO") 27 | 28 | 29 | """ 30 | Use many if-tests. 31 | """ 32 | if val == True: 33 | print("TRUE") 34 | elif val == False: 35 | print("FALSE") 36 | elif val == None: 37 | print("NONE") 38 | else: 39 | print("NO") 40 | 41 | 42 | ``` 43 | 44 | 45 | 46 | Reference and read more 47 | ------------------------------ 48 | 49 | [if Statements](https://docs.python.org/3/tutorial/controlflow.html#if-statements) 50 | 51 | 52 | 53 | Revision history 54 | ------------------------------ 55 | 56 | 2014.07-15 (sylvanas) PA2 Second try, now with Python syntax. 57 | 58 | 2014-06-02 (mos) PA1 First try. 59 | 60 | -------------------------------------------------------------------------------- /tutorial/input.md: -------------------------------------------------------------------------------- 1 | input 2 | ============================== 3 | Examples in Python 3 4 | 5 | 6 | ```python 7 | """ 8 | Getting input and saving it to variable 9 | """ 10 | inp = input("Enter your name: ") 11 | print(inp) 12 | print(type(inp)) # Input is a string 13 | 14 | 15 | inp = input("Enter your age: ") 16 | print(inp) 17 | print(type(inp)) # Input is a string 18 | 19 | 20 | """ 21 | Wait for user to input any key 22 | """ 23 | input("Press any key to continue...") 24 | 25 | 26 | 27 | ``` 28 | 29 | 30 | Reference and read more 31 | ------------------------------ 32 | 33 | [input()](https://docs.python.org/3/library/functions.html?highlight=input#input) 34 | 35 | 36 | 37 | Revision history 38 | ------------------------------ 39 | 40 | 2014-07-16 (sylvanas) PA1 First try. 41 | -------------------------------------------------------------------------------- /tutorial/range.md: -------------------------------------------------------------------------------- 1 | range() 2 | ============================== 3 | Examples in Python 3 4 | 5 | 6 | ```python 7 | """ 8 | Simple range of 10 9 | """ 10 | # Notice that it will not include 10, and starts at 0 11 | print(range(10)) 12 | print("") 13 | 14 | 15 | """ 16 | Iterate over range 17 | """ 18 | for x in range(6): 19 | print(x, end=",") 20 | print("\n") 21 | 22 | 23 | """ 24 | Change start for range 25 | """ 26 | for x in range(5,10): 27 | print(x, end=",") 28 | print("\n") 29 | 30 | 31 | """ 32 | Add step to range 33 | """ 34 | # Only print even numbers 35 | for x in range(0, 10, 2): 36 | print(x, end=",") 37 | print("") 38 | 39 | 40 | ``` 41 | 42 | 43 | Reference and read more 44 | ------------------------------ 45 | 46 | [The range() Function](https://docs.python.org/3/tutorial/controlflow.html#the-range-function) 47 | 48 | [range()](https://docs.python.org/3/library/stdtypes.html#range) 49 | 50 | 51 | Revision history 52 | ------------------------------ 53 | 54 | 2014-07-17 (sylvanas) PA1 First try. 55 | -------------------------------------------------------------------------------- /tutorial/string-module.md: -------------------------------------------------------------------------------- 1 | String module - constants 2 | ============================== 3 | Examples in Python 3 4 | 5 | 6 | 7 | ```python 8 | # Need to import module to get access to string 9 | import string 10 | 11 | """ 12 | Letters 13 | """ 14 | # Upper and lower 15 | print(string.ascii_letters) 16 | 17 | # Lower 18 | print(string.ascii_lowercase) 19 | 20 | # Upper 21 | print(string.ascii_uppercase) 22 | 23 | 24 | """ 25 | Numbers 26 | """ 27 | # Normal 28 | print(string.digits) 29 | 30 | # Hex 31 | print(string.hexdigits) 32 | 33 | # Octonal 34 | print(string.octdigits) 35 | 36 | 37 | """ 38 | Other 39 | """ 40 | # Punctuation characters 41 | print(string.punctuation) 42 | 43 | 44 | ``` 45 | 46 | 47 | Reference and read more 48 | ------------------------------ 49 | 50 | [string — Common string operations](https://docs.python.org/3/library/string.html) 51 | 52 | 53 | Revision history 54 | ------------------------------ 55 | 56 | 2014-07-17 (sylvanas) PA1 First try. 57 | -------------------------------------------------------------------------------- /tutorial/string-translation.md: -------------------------------------------------------------------------------- 1 | String translation 2 | ============================== 3 | Examples in Python 3 4 | 5 | 6 | 7 | ```python 8 | # Need to import module to get access to string 9 | import string 10 | 11 | """ 12 | Translate some characters into numbers 13 | """ 14 | # Create a variable string with all numbers 0-9 15 | nrs = string.digits 16 | # Create a string which containts characters for each number in order 17 | # 0123456789 18 | chars = "olzeasgtbp" 19 | 20 | # Create a translation table, from and to as parameters 21 | trans = str.maketrans(chars, nrs) 22 | 23 | # Create a string to translate 24 | my_str = "hello world" 25 | # Use translate() and the table created to translate string 26 | x = my_str.translate(trans) 27 | print(x) 28 | 29 | 30 | 31 | ``` 32 | 33 | 34 | Reference and read more 35 | ------------------------------ 36 | 37 | [string — Common string operations](https://docs.python.org/3/library/string.html) 38 | 39 | 40 | Revision history 41 | ------------------------------ 42 | 43 | 2014-07-17 (sylvanas) PA1 First try. 44 | -------------------------------------------------------------------------------- /tutorial/types.md: -------------------------------------------------------------------------------- 1 | Types 2 | ============================== 3 | Examples in Python 3 4 | 5 | 6 | ```python 7 | """ 8 | Print out the type of some values 9 | """ 10 | # Numbers 11 | print(type(42)) 12 | print(type(4.2)) 13 | 14 | # String 15 | print(type("Hello world!")) 16 | 17 | # Booleans 18 | print(type(True)) 19 | print(type(False)) 20 | 21 | # None 22 | print(type(None)) 23 | 24 | # Multiline 25 | hello = """ 26 | Hello 27 | World! 28 | """ 29 | print(type(hello)) 30 | 31 | # Function 32 | def test(): 33 | print("test-function") 34 | print(type(test)) 35 | 36 | 37 | ``` 38 | 39 | 40 | 41 | Reference and read more 42 | ------------------------------ 43 | 44 | [type()](https://docs.python.org/3/library/functions.html#type) 45 | 46 | 47 | 48 | Revision history 49 | ------------------------------ 50 | 51 | 2014-07-16 (sylvanas) PA1 First try. 52 | -------------------------------------------------------------------------------- /tutorial/while.md: -------------------------------------------------------------------------------- 1 | while 2 | ============================== 3 | Examples in Python 3 4 | 5 | 6 | ```python 7 | """ 8 | Loop until x is certain value 9 | """ 10 | x = 0 11 | while x < 10: 12 | x += 3 13 | print(x) 14 | 15 | 16 | """ 17 | Loop until x is certain value with while True and break 18 | """ 19 | x = 0 20 | while True: 21 | x += 3 22 | print(x) 23 | if x > 10: 24 | break 25 | 26 | 27 | """ 28 | More useful while with break (nothing to iterate over) - take input until input is "done" 29 | """ 30 | my_str = "" 31 | while True: 32 | inp = input("> ") 33 | if inp == "done": 34 | break 35 | my_str += inp 36 | print(my_str) 37 | 38 | 39 | 40 | ``` 41 | 42 | 43 | Reference and read more 44 | ------------------------------ 45 | 46 | [The while statement](https://docs.python.org/3/reference/compound_stmts.html?highlight=while#while) 47 | 48 | [While loops](https://wiki.python.org/moin/WhileLoop) 49 | 50 | 51 | 52 | Revision history 53 | ------------------------------ 54 | 55 | 2014-07-17 (sylvanas) PA1 First try. 56 | -------------------------------------------------------------------------------- /tutorial/with-files.md: -------------------------------------------------------------------------------- 1 | Read files using with 2 | ============================== 3 | 4 | 5 | ```python 6 | """ 7 | Use with - as for reading and writing 8 | With closes file automatically after the code in the statement has finished 9 | """ 10 | 11 | # read all lines into list 12 | with open("test.txt") as fhand: 13 | all_lines = fhand.readlines() 14 | 15 | # write line into file 16 | with open("test.txt", "w") as fhand: 17 | fhand.write("This is a test.") 18 | 19 | ``` 20 | 21 | 22 | 23 | Reference and read more 24 | ------------------------------ 25 | 26 | [The with statement](https://docs.python.org/3/reference/compound_stmts.html#with) 27 | 28 | [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) 29 | --------------------------------------------------------------------------------