diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index fb7b99c4..efead2d0 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -8,13 +8,34 @@ on: pull_request: branches: [master] +env: + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} + +permissions: + contents: 'write' + id-token: 'write' + pull-requests: 'write' jobs: build: name: Build and Deploy Documentation runs-on: ubuntu-latest + steps: + - name: Checkout Branch + uses: actions/checkout@v3 + if: github.event_name == 'pull_request' + with: + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.ref }} + persist-credentials: false + - name: Checkout Master - uses: actions/checkout@v2 + uses: actions/checkout@v3 + + if: github.event_name == 'push' + with: + fetch-depth: 0 + persist-credentials: false - name: Set up Python 3.7 uses: actions/setup-python@v2 @@ -25,7 +46,11 @@ jobs: run: | python -m pip install --upgrade pip pip install mkdocs-material - + + - name: Check + run: | + pwd + ls -la - name: Deploy run: | git pull diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..9a49861c --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,9 @@ +{ + "cSpell.words": [ + "Mojhave", + "Trinkit", + "coderdojo", + "jupyter", + "randint" + ] +} \ No newline at end of file diff --git a/docs/advanced-python/01-intro.md b/docs/advanced-python/01-intro.md new file mode 100644 index 00000000..5bebe7ca --- /dev/null +++ b/docs/advanced-python/01-intro.md @@ -0,0 +1,7 @@ +# Advanced Python +Here are some suggested programs for doing more advanced Python programming. Here we define advanced as anything that is not covered under our Beginning Python class that usually runs between one and three hours. + +## Roll the Dice +This lab uses the random number function to generate dice rolls. It uses a while loop to continue to roll a pair of six-sided dice repeatedly. +[./02-roll-the-dice.md] + diff --git a/docs/advanced-python/02-roll-the-dice.md b/docs/advanced-python/02-roll-the-dice.md new file mode 100644 index 00000000..e3211869 --- /dev/null +++ b/docs/advanced-python/02-roll-the-dice.md @@ -0,0 +1,24 @@ +# Roll the Dice +In this game the program generates two random numbers between 1 and 6. The program then asks the user if they want to roll the dice again. If they answer y or yes then the pair of +dice are rolled again. + +```py +import random +min = 1 +max = 6 + +roll_again = "yes" + +while roll_again == "yes" or roll_again == "y": + print("Rolling the dice. The values are:") + print(random.randint(min, max)) + print(random.randint(min, max)) + roll_again = input("Roll the dices again?") +``` + +```sh +Rolling the dice. The values are: +4 +4 +Roll the dices again? +``` \ No newline at end of file diff --git a/docs/advanced-python/roll-dice.py b/docs/advanced-python/roll-dice.py new file mode 100644 index 00000000..59def009 --- /dev/null +++ b/docs/advanced-python/roll-dice.py @@ -0,0 +1,11 @@ +import random +min = 1 +max = 6 + +roll_again = "yes" + +while roll_again == "yes" or roll_again == "y": + print("Rolling the dice. The values are:") + print(random.randint(min, max)) + print(random.randint(min, max)) + roll_again = input("Roll the dices again?") \ No newline at end of file diff --git a/docs/img/coderdojo-logo.jpg b/docs/img/coderdojo-logo.jpg new file mode 100644 index 00000000..99f0ac07 Binary files /dev/null and b/docs/img/coderdojo-logo.jpg differ diff --git a/docs/img/night_sky.png b/docs/img/night_sky.png new file mode 100644 index 00000000..0b519bb5 Binary files /dev/null and b/docs/img/night_sky.png differ diff --git a/docs/img/plot-sin.png b/docs/img/plot-sin.png new file mode 100644 index 00000000..cea3a5d0 Binary files /dev/null and b/docs/img/plot-sin.png differ diff --git a/docs/img/porters-five-forces.png b/docs/img/porters-five-forces.png new file mode 100644 index 00000000..743177d0 Binary files /dev/null and b/docs/img/porters-five-forces.png differ diff --git a/docs/img/python-logo-label.jpeg b/docs/img/python-logo-label.jpeg new file mode 100644 index 00000000..4b3855c2 Binary files /dev/null and b/docs/img/python-logo-label.jpeg differ diff --git a/docs/img/python-logo-label.png b/docs/img/python-logo-label.png new file mode 100644 index 00000000..8dbeff3e Binary files /dev/null and b/docs/img/python-logo-label.png differ diff --git a/docs/img/python-logo.jpeg b/docs/img/python-logo.jpeg new file mode 100644 index 00000000..e37f9f66 Binary files /dev/null and b/docs/img/python-logo.jpeg differ diff --git a/docs/img/python_environment.png b/docs/img/python_environment.png new file mode 100644 index 00000000..4f482458 Binary files /dev/null and b/docs/img/python_environment.png differ diff --git a/docs/img/rocketpanda.png b/docs/img/rocketpanda.png new file mode 100644 index 00000000..7946a7c0 Binary files /dev/null and b/docs/img/rocketpanda.png differ diff --git a/docs/img/row-of-circles.png b/docs/img/row-of-circles.png new file mode 100644 index 00000000..b082b601 Binary files /dev/null and b/docs/img/row-of-circles.png differ diff --git a/docs/img/stop-sign.png b/docs/img/stop-sign.png new file mode 100644 index 00000000..504458ea Binary files /dev/null and b/docs/img/stop-sign.png differ diff --git a/docs/img/turtle-sine-wave.png b/docs/img/turtle-sine-wave.png new file mode 100644 index 00000000..a49a1c82 Binary files /dev/null and b/docs/img/turtle-sine-wave.png differ diff --git a/docs/index.md b/docs/index.md index 78afbb62..7dd08d13 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,30 +1,30 @@ # CoderDojo Twin Cities Python Resources -This GitHub repository is for sharing teaching resources to teach Python. This includes hints on getting your Python environments setup up and extensive lesson plans for serveral enviornments. +This GitHub repository is for sharing teaching resources to teach Python. This includes hints on getting your Python environments setup up and extensive lesson plans for several environments. -Our mentors have used several different envornments for teaching Python. They each have pros and cons. What our mentors like is getting new students started using a graphical programming environment such as turtle graphics libraries. Here are some of our favorite tools: +Our mentors have used several different environments for teaching Python. They each have pros and cons. What our mentors like is getting new students started using a graphical programming environment such as turtle graphics libraries. Here are some of our favorite tools: - [**Trinket.io**](http://trinket.io) is an easy-to use, kid friendly web-based turtle graphics for beginners. - [**Jupyter Notebooks**](https://jupyter.org/) also have some support for turtle graphics. Jupyter Notebooks can be tricky to setup for the first time, but they are the perfect on-ramp for teaching data literacy. - [**Raspberry Pi**](https://www.raspberrypi.org/documentation/usage/python/) - The Raspberry Pi foundation has selected Python as its primary tool for teaching programming. If you have a Raspberry Pi there are many resources for you. Trinket and Jupyter Notebooks will also run on many Raspberry Pi devices. - **Robots** Our students love robots. Python is also the preferred language in many robotics courses. Today we teach beginning robotics with Scratch and Arduino, but we continue to investigate systems like Raspberry Pi robots that can be programmed with Python. Let us know if you have any low-cost kid friendly ideas. We have tested the JetBot and other robots and we continue to look for solutions. -Now lets briefly go into the pros and cons of these systems. +Now let's briefly go into the pros and cons of these systems. ## Learning Python with Trinket -We use the [trinket.io](http://trinket.io) web site to teach our introduction to python. Trinket has a nice turtle graphics library which is ideal for fast visual feedback. Because it is a free and a pure web web based environment it meets the criteria for our courses. There is no complex setup and each student can continue to do development when they are at home. The downside of Trinket is it has limited functionality, only supports Python 2.X in the free version and you must have an internet connection to use Trinket. If you need Python 3.X web +We use the [trinket.io](http://trinket.io) web site to teach our introduction to python. Trinket has a nice turtle graphics library which is ideal for fast visual feedback. Because it is a free and a pure web-based environment it meets the criteria for our courses. There is no complex setup and each student can continue to do development when they are at home. The downside of Trinket is it has limited functionality, only supports Python 2.X in the free version and you must have an internet connection to use Trinket. If you need Python 3.X web version you can use the free [repl.id](https://repl.it/) web site. ## Learning Python with Jupyter Notebooks -You can also use Jupyter Notebooks to draw turtle graphics. The notebook will open a new window to draw your turtle graphis. Getting Jupyter Notebooks is a bit tricky to setup on many PCs. However, once it is setup it offers tens of thousands of sample programs to learn python coding. Jupyter Notebooks are also the preferred tool by many data science professionals. +You can also use Jupyter Notebooks to draw turtle graphics. The notebook will open a new window to draw your turtle graphics. Getting Jupyter Notebooks is a bit tricky to setup on many PCs. However, once it is setup it offers tens of thousands of sample programs to learn python coding. Jupyter Notebooks are also the preferred tool by many data science professionals. An example of a Jupyter Notebook that uses turtle graphs is [here](jupyter/draw-figure.ipynb) ## Learning Python with Raspberry Pi -If you have a Rasperry Pi there are many great ways to learn Python. One of first things is to try out one of the Python development environments for the Raspberry Pi. +If you have a Raspberry Pi there are many great ways to learn Python. One of first things is to try out one of the Python development environments for the Raspberry Pi. ## Learning Python with Robots -Right now we are continuing to try to find the right combination of easy-of-use and low-cost robots to teach python. If you hear of any good tools, please let us know. +Right now, we are continuing to try to find the right combination of easy-of-use and low-cost robots to teach python. If you hear of any good tools, please let us know. ## Target Audience Learning Python is ideal for students that have good keyboarding skills. If students have difficulty with doing functions like copy and pasting text we suggest they start with a block-programming language like Scratch. @@ -32,7 +32,7 @@ Learning Python is ideal for students that have good keyboarding skills. If stu ## List of Concepts Here are some of the concepts we will be learning in this course. If you are already familiar with these concepts you can skip over some of the labs. -- **importing libraries** We need to tell Pyhton what functions we want to use. We will use the import function to tell Python which functions we need to use in our programs. +- **importing libraries** We need to tell Python what functions we want to use. We will use the import function to tell Python which functions we need to use in our programs. - **drawing** Turtle graphs has a set of drawing functions. We will learn to use these to draw patterns on the screen. - **square walk** - teach your turtle to walk in a square and draw figures. - **variables** Variables make our programs easier to read and easier to understand. @@ -41,7 +41,7 @@ Here are some of the concepts we will be learning in this course. If you are al - **functions** Functions allow us to break large programs into chunks that we can give names and can call over and over. - **function parameters** Functions can also take parameters to change the behavior of a function. - **random numbers** Random number functions allow our programs to have the computer select new random number between a range of numbers. -- **lists** Lists alow us to create collections of names. +- **lists** Lists allow us to create collections of names. - **inputs** Inputs allow us to prompt the user for values. - **recursion** Recursion allows us to have programs call themselves to create repeating patterns. - **modules** Once you have a group of related functions you can put them all together into a module. This makes it easier for others to reuse your programs. diff --git a/docs/intermediate/01-intro.md b/docs/intermediate/01-intro.md new file mode 100644 index 00000000..98ba68be --- /dev/null +++ b/docs/intermediate/01-intro.md @@ -0,0 +1,21 @@ +# Introduction to Intermediate Python + +This course assumes you are familiar with beginning concepts in Python such as variables, loops, conditionals, random numbers, functions, function parameters, lists and basic recursion. We strongly suggest that you have completed the [CoderDoj Twin Cities Beginning Python Class](../trinket/00-introduction.md) BEFORE you do the intermediate labs. + +Note that you can do the first four lessons using web-based Python programming tools like Trinket.io or repl.it. Starting with lesson #5 on Files you will need to have Python installed on your local computer. Please visit the [Python.org](http://python.org) web site for the installation instructions on your operating systems. You can use the command-line version of Python from a Terminal or shell or you can install one of the Python Integrated Development Environments (IDEs). + +The concepts in this course include: + +1. [**Variables and Scope**](./01-variables-scope.md) - In this lab we learn that you can control what parts of your program can access a variable. This comes in handy when we write larger programs. +2. [**Data types**](./02-data-types.md) - This lab give you a tour of some of the data types in Python other than boring strings and integers. +3. [**Checking Data Types of Function Parameters**](./03-data-type-validation.md) - in the beginning course we learned how to pass parameters to functions. Now we learn how to make sure our functions get the data that they expect! +4. [**Maps**](./04-maps.md) - Maps or dictionaries are sets of key-value pairs that are crazy flexible. Unlike a list, where the index can only be fixed sequence of integers starting with 0, the keys in a map can be any integer or string in any order. +5. [**Files**](./05-files.md) - In this lesson we will learn how to open a file and read the data into our program with just a few lines. Not only can we read in data, but we can also write out data! So much power in a few lines of code! +6. [**Images**](./06-images.md) - In our CoderDojo AI Racing League we will be learning how to make a car drive autonomously. But first we need to be able to read in images and display them. In this lab we will show you how easy this is! +7. [**Defining Your Own Modules**](./07-modules.md) - In the Beginning Python class we learned how to create functions. Now we learn how to package them up so they are easy for others to use. +8. [**dir() function**](./08-dir.md) - If you ever want to know what functions you can throw at something we got this secret tool called "dir". It really takes the mystery out of what functions you can use and avoids trying to guess what function names are used. Not that guessing games aren't fun! +9. [**Regular expressions**](./09-regex.md) - You sometimes want a list of all the files in a folder that have a .jpg extension for images. This lesson will show you how we can use a shorthand notation to make it easy to specify what files to include and which ones to skip. +10. [**Debugging**](./10-debugging.md) - When we have a hard time understanding what our programs are doing we need to be able to peak in and see the results of small steps of our programs. This lesson will show you how to squash those little "bugs" or errors in our code. (not real bugs, that would be mean!) + + + diff --git a/docs/intermediate/01-variables-scope.md b/docs/intermediate/01-variables-scope.md new file mode 100644 index 00000000..ff24bad7 --- /dev/null +++ b/docs/intermediate/01-variables-scope.md @@ -0,0 +1,81 @@ +## Variables +If you've made it this far, you know a variable is a container for data in Python. Let's dive a little deeper into the world of variables! + +### Naming conventions +In the [Python community](https://www.python.org/dev/peps/pep-0008/#function-and-variable-names), the general accepted format for variable and function names is all lower case, with multiple words separated by underscores. For example: + +variable = 0 + +my_variable = 0 + +my_function_name() + +### Giving variables and functions meaningful names +Variable names should be meaningful to you as the programmer, to any other developers that may be collaborating with you and any developers that may look at your code in the future. Below are two instances of the same code using different variable and function names. Which is easier to read? + +```python +def my_first_function(arg): + variable1 = arg + 2 + return variable1 + +def my_second_function(arg): + variable = arg * 5 + return variable + +print(my_first_function(my_second_function(5))) +``` + + +```python +def plus_two(num): + two_more = num + 2 + return two_more + +def times_five(num): + five_times = num * 5 + return five_times + +print(plus_two(times_five(5))) +``` + +### Variable Scope +A variable's scope refers to where in your code you can access that variable. The scope of a variable defined within a function is limited to the function in which it is defined. This is an example of a local variable. For example, using the more legible code above: + +```python +def plus_two(num): + two_more = num + 2 + return two_more + +def times_five(num): + five_times = num * 5 + return five_times + +print(plus_two(times_five(5))) + +print(five_times) +``` + +Attempting to print the value of five_times within the global scope of the code will result in a NameError, because the scope of the variable five_times is limited to the times_five function. Conversely, a global variable is a variable that can be accessed anywhere within your code. Global variables are usually created within the main body of your code, that is outside of functions, as demonstrated below. You can see the my_name variable is accessible within the who_is_awesome function. + +```python + +my_name = "Zack" +def who_is_awesome(): + print(my_name + " is awesome!") + +``` + +You can make a variable used within a function globally accessible by using the 'global' keyword. For example, + +```python +def who_is_awesome(name): + global awesome_statement + awesome_statement = name + " is awesome!" + print("Variable Reference Within Function: " + awesome_statement) + +who_is_awesome("Zack") +print("Global Variable Use: " + awesome_statement) +``` + +## Food for Thought +When would it make sense to use the global keyword within a function to make a variable globally accessible, instead of returning the variable from the function? \ No newline at end of file diff --git a/docs/intermediate/02-data-types.md b/docs/intermediate/02-data-types.md new file mode 100644 index 00000000..33350235 --- /dev/null +++ b/docs/intermediate/02-data-types.md @@ -0,0 +1,149 @@ +## Data Types + +![Data GIF](https://media.giphy.com/media/4FQMuOKR6zQRO/giphy.gif) + +So we know that data is a piece of information, but there are of course different types of data! Let's illustrate the importance of data types... + +```python + +three_string = "3" +three_integer = 3 + +print(three_string*3) + +print(three_integer*3) +``` + +Notice the difference in the output when multiplying three_string and three_int by three. three_string * 3 returned 333, whereas three_integer * 3 returned 9. This is because the three_string variable is a string datatype. + +### What are the different data types + +**Text** + + - string: _str_ + - example: ```my_string = "this is a string"``` + +**Numeric** + + - integer: _int_ + - example: ```my_int = 3``` + - float: _float_ + - example: ```my_float = 3.14``` + + Both integers and floats can be negative. For example: ```my_negative_int = -3``` + +**Sequence** + + - List: _list_ — an unordered list of data / objects. + - example: ```my_list = [1, 2, my_float, 4, "Bananas"]``` + - Tuple: _tuple_ — an ordered and immutable list of of data / objects. Immutable means _unchangeable_, once you have defined a tuple you cannot change, remove or reorder elements— for any of these operations, use a list. + - example: ```my_tuple = (1, 2, my_float, 4, "Bananas")``` + +As you can see, elements in lists and tuples do not have to be the same data type. There are three integers, a variable and a string in both the list and tuple shown above. + +**Boolean** + +- Boolean: _bool_ — a binary data type that is either True or False + - example: ```my_bool = True``` + + +**None** + +-None: _NoneType_ — ```None``` is a keyword in Python used to indicate a null value. None differs from False or an empty string (```""```). A function that does not specify a return value will always return None. + +```python +def no_return(): + print("This function does not return anything.") + +no_return_response=no_return() + +print(no_return_response == None) +print(type(no_return_response)) +``` + +As you can see from the code above, when we assign the result of the _no_return()_ function call to the _no_return_response_ variable, the print statement in the function is executed. However, the value of _no_return_response_ is None, since there was no return statement in the _no_return_ function. + +**Mapping** + +-Dictionary: _dict_ — an unordered data type consisting of key, value pairs + + Creating a dictionary + + A dictionary is demarcated by curly braces around key:value pairs that are separated by commas. Keys and values do not need to be the same data types. + +```py +myDictionary = { + "dictionary" : "a book or electronic resource that lists the words of a language", + "int" : "short for integer. A whole number; a number that is not a fraction","float" : "for our purposes this means a decimal number— a number that consists of a whole number and a fractional part", + "bool" : "short for boolean; a binary, True or False value" + } +``` + + We'll learn more about dictionaries in the [maps section](04-maps.md) + +#### Type Casting +Strings consisting of digits can easily be converted to floats or integers + +```py +#ask the user to input a number +number=input("Type a number here and press 'enter' to proceed>>>") + +#side note: '\n' tells python to print a newline +#side note: we can use the the type keyword to determine what datatype a variable is +print("\nthe number variable is currently the " + str(type(number)) + " data type\n") + +#as you can see the number the user entered belongs to the str data type, that's because input always returns a string. + +#so if we wanted to see what two times the number the user entered is how would we do it? +print(number * 2) + +#that didn't do what we wanted, did it? + +#let's convert the number variable to the int data type: +number_as_int = int(number) + +print("\nthe number_as_int variable is currently the " + str(type(number_as_int)) + " data type") + +#okay now our number is an int! + +#as you know, division operation always returns a float, even if there is no remainder + +my_float= 8 / 4 + +print("\nmy_float is " + str(my_float)) + + +``` + +## You Try It! + +We know what type casting is and how to convert a string to an integer. We also know that a division operation in Python will always return a float, regardless of whether or not there's a remainder. Finally, we know using the modulo operator (_%_) in place of the division operator will return only the remainder—for example, ```7 % 4``` will return 3. Using these pieces of knowledge, implement a function that will convert a float to an int, but only if there is no remainder. Complete the function definition for float_converter below! We've put some test conditions below to check your function. + +```python +def float_converter(some_float): + #if some_float has a remainder return the original float + #else return the some_float as an int + +#test our function: +expecting_float = float_converter(7/3) +expecting_int = float_converter(4/2) + +test1 = expecting_float == 7/3 +test2 = expecting_int == 2 and type(expecting_int) == int +test3 = expecting_float != 2 + +if test1 and test2: + print("Congrats! You've properly implemented the float_converter function!") +elif test1: + print("It looks like you've properly returned the original float, but didn't return some_float as an integer when there's no remainder.") +elif test2 and test3: + print("It looks like you've properly type returned some_float as an integer when there's no remainder! But you still need to return the original float when there is a remainder.") +elif test2 and not test3: + print("It looks It looks like you may always be returning my_float as an integer regardless of whether or not there's a remainder.") +else: + print("It looks like you haven't properly implemented either of the requirements for float_converter.") + +``` + +## Food for Thought +When learning about the dictionary data type, we created _my_dict_, which contained data types and their definitions. Let's say in addition to the definitions of each data type, I wanted to add part of speech and store an example of each data type. How might we do this? Hint: it involves more dictionaries! \ No newline at end of file diff --git a/docs/intermediate/03-data-type-validation.md b/docs/intermediate/03-data-type-validation.md new file mode 100644 index 00000000..00ffa9db --- /dev/null +++ b/docs/intermediate/03-data-type-validation.md @@ -0,0 +1,69 @@ +# Checking Data Types of Function Parameters +In the beginning course we learned how to pass arguments to functions. Now we learn how to make sure our functions get the data that they expect! + +We saw in the data types lab we can use the type keyword to get the type of a variable (e.g. ```type(my_var)```). We can use this in combination with the _is equal to_ operator (```==```) to make sure a variable passed to a function is the right data type. + + +```python + +def validateType(expecting_string): + if type(expecting_string)==str: + print("You passed a string!") + else: + print("You passed something that wasn't a string!") + +``` + +As you may recall, during the data type labs we used the input function to solicit user input. The response from input is always a string! So if we ask the user to input a number, how do we confirm the input is in fact a number before type casting int on the user input? Remember type casting int on an alphabetic string will throw an error. Let's check it out. + +```python +def cast_to_int(): + user_input=input("Enter an int\n>") + user_input_as_int=int(user_input) + return user_input_as_int + +some_int=cast_to_int() +print(some_int) + +``` + +Let's try [running this on trinket.io](https://trinket.io/python/51fabe7c6c) and when asked to enter an int, let's enter a word! + +As you can see we get a type error, because we're trying to convert an alphabetic string to an integer: + +```python +ValueError: invalid literal for int +``` + +So what's the work around? Strings have some very useful methods (methods are functions that belong to objects. We'll take about objects in the advanced section), among them ```.isdigit()```! Let's see it in action! + +```python +def cast_to_int(): + user_input=input("Enter an int\n>") + if user_input.isdigit(): + user_input_as_int=int(user_input) + return user_input_as_int + else: + return "You did not input an integer!" + +some_int=cast_to_int() +print(some_int) + +``` + +Let's say the user input was critical to the program we're building and if the user does not input an integer we want to throw an error to the user. We can use the ```assert``` keyword to achieve this. The syntax for the assert keyword is as follows: ```assert some_conditional_statement, "Error message to output."``` Let's see it in action below! + +```python +def cast_to_int(): + user_input=input("Enter an int\n>") + assert user_input.isdigit(), "You did not input an integer!" + user_input_as_int=int(user_input) + return user_input_as_int + +some_int=cast_to_int() +print(some_int) + +``` + +## You try it! +Let's say we want to continously bug a user until they input an integer. How might we achieve this using the lesson above + what we know about while loops? \ No newline at end of file diff --git a/docs/intermediate/04-maps.md b/docs/intermediate/04-maps.md new file mode 100644 index 00000000..0d4adc40 --- /dev/null +++ b/docs/intermediate/04-maps.md @@ -0,0 +1,78 @@ +# Maps in Python + +-Dictionary: _dict_ — an unordered data type consisting of key, value pairs + + Creating a dictionary + + A dictionary is demarcated by curly braces around key:value pairs that are separated by commas. + +```python + my_dict = {"dictionary" : "a book or electronic resource that lists the words of a language", "int" : "short for integer. A whole number; a number that is not a fraction", "float" : "for our purposes this means a decimal number— a number that consists of a whole number and a fractional part", "bool" : "short for boolean; a binary, True or False value"} +``` + +Retrieving the value of a key from a dictionary: remember a dictionary consists of key, value pairs. To get a value for a given key we reference the key: + +```python +print(my_dict['integer']) +``` + +If we try to reference a key that does not exist in a dictionary a KeyError will be thrown. + +```python +print(my_dict['tuple']) +``` + +A quick way to avoid the KeyError is by using the _.get()_ method for dictionaries: + +```python +print(my_dict.get('tuple')) # this will print None because the key 'tuple' does not exist in my_dict. + +``` + + + +Another way to avoid the KeyError and determine if a key exists in a dictionary is to use the ```in``` keyword. + +```python + +if 'tuple' in my_dict: + print("'tuple' is a key in my_dict") +else: + print("'tuple' is NOT a key in my_dict") + +if 'int' in my_dict: + print("'int' is a key in my_dict") +else: + print("'int' is NOT a key in my_dict") + + +``` + +Adding or updating a key / value pair to a dictionary: + +```python + +my_dict['str']= "short for string; a text data type in Python defined using a pair of double or single quotes around the data" + +``` + + + + +## You try it! + +Using your knowledge of how dictionaries and conditional statements work, create a function that takes a key and a value as arguments and will either add the key/value pair and print "This key / value pair has been added to the dictionary" if the key does not exist in the dictionary, or prints "This key is already in the dictionary!" if the key already exists. Also important to keep in mind when doing this is what we just learned about variable scopes! + +``` + my_dict = {"dictionary" : "a book or electronic resource that lists the words of a language", "int" : "short for integer. A whole number; a number that is not a fraction", "float" : "for our purposes this means a decimal number— a number that consists of a whole number and a fractional part", "bool" : "short for boolean; a binary, True or False value"} + + def add_to_dict(key, value): + #Implement the function here! + + add_to_dict("int","an integer") + #This should print "This key is already in the dictionary!" + + add_to_dict("tuple","an ordered, immutable list of data / objects") + #This should add the key/value pair to the my_dict dictionary and print "This key / value pair has been added to the dictionary" + +``` \ No newline at end of file diff --git a/docs/intermediate/05-files.md b/docs/intermediate/05-files.md new file mode 100644 index 00000000..2204a95c --- /dev/null +++ b/docs/intermediate/05-files.md @@ -0,0 +1,122 @@ +# Reading and Writing Files in Python + +Most of the initial labs until now used the Trinket web site to teach you how to program Python. Although many of these labs use Trinket, some of the labs in the intermediate class need access to your local file system to learn how to open and manipulate files. To do this you must install Python on your local computer. + +To install Python on your computer visit the [Python.org](https://www.python.org) web site and follow the installation instructions for your computer operating system (Windows, Mac, Linux etc.) + +At this point you should now have python installed on your computer and no longer be using trinket.io. We recommend [installing Anaconda](https://www.anaconda.com/products/individual) and using the Spyder integrated development environment (IDE). + +Python makes it easy to read and write text files. The general syntax for opening a file is as follows: + +```file = open('/file/path/filename.txt', 'mode')``` + +The first argument is the path the file on your computer. If the file you're trying to open is in the same folder as your python script you can just input the filename, if not you'll need the path to file. For example, let's say you're using a Mac, your username is Bella, and you're trying to open a file called "myfile.txt" in your downloads folder. The path to that file would be: ```/Users/Bella/Downloads/myfile.txt``` + +Valid arguments for the mode parameter are: + +* 'w': writing to a file, this will overwrite a file if it already exists. +* 'a': append to a file, you can add new lines to a file that already exists, otherwise it will create the file. +* 'r': to read a file. + +### Reading Files + +For our example we're going to [download](https://www.gutenberg.org/files/2701/old/moby10b.txt) Herman Melville's _Moby-Dick_ from the Gutenberg Project to read. + +```python + f = open("/Users/Bella/Downloads/moby10b.txt","r") + + ### Let's take all the lines in Moby-Dick and store them in a list! + + lines = f.readlines() + + ### Close the file + + f.close() +``` + +Calling the ```.readlines()``` method on a file is very useful. If we wanted to do this manually, we would iterate over the lines in the file and add them one by one to a list. + +```python + + f = open("/Users/Bella/Downloads/moby10b.txt","r") + + lines = [] #define empty list + + for line in f: + lines.append(line) #we can use the .append() method to add new items to a list! + + f.close() +``` + +Let's say we needed to know exactly how many times each word appears in _Moby-Dick_: how might we do that? We'd have to account for things like punctuation, captalization and newline characters ('\n'). We'd also need to get every word by itself. + +```python +from string import punctuation #punctuation from the string library is a string that contains all punctuation marks +#you can run print(punctuation) to see what this looks like + +punctuation_list = list(punctuation) #convert string of punctuation marks to list + + +f = open("/Users/Bella/Downloads/moby10b.txt", "r") #open Moby-Dick file +lines = f.readlines() #put all lines from Moby-Dick into a list +f.close() #close the file + +clean_lines = [] #empty list for lines stripped of newline characters and all characters converted to lowercase + +for line in lines: #go through every line in the file + clean_line = line.strip("\n") #get rid of new-line characters + clean_line = clean_line.lower() #convert everything to lowercase + clean_lines.append(clean_line) #add cleaned line to clean_lines + +words={} #create empty dictionary for words + +for line in clean_lines: #go through every line in the file + for mark in punctuation_list: #go through every punctuation mark + line=line.replace(mark,"") #use replace method to replace each possible punctuation mark with an empty string + line_words=line.split(" ") #we're using the string split() method to separate each line by space character + #this converts the line to a list + #for example: "This is a sentence.".split(" ") --> ['This', 'is', 'a', 'sentence.'] + for word in line_words: #iterate over every word in the line + if word not in words: # if we haven't seen this word yet + words[word]=1 #add it to the words dictionary, and mark the count as 1 + else: + words[word]+=1 #we've already seen this word, so increment the count by 1 +``` + +The method we used above to remove punctuation characters from the lines is not the most computationally efficent. We're going to learn a better way to do this in the section on Regex expressions. + +One thing we left out from the mapping section is that you can iterate over a dictionary using the .items() method. Here's what that looks like: + +```python + +my_dict = {1:"one",2:"two",3:"three"} + +for key, value in my_dict.items(): + print(key, value) +#this prints: +#1 one +#2 two +#3 three +``` + +### You Try It! +If you recall, a dictionary is an unordered data structure. Use what we learned about iterating over items in a dictionary to determine what word occurs the most frequently in _Moby-Dick_! + +### Writing Files + +Let's say we wanted to write out _Moby-Dick_ with no capital letters. Here's how we could approach that: + +```python + +f = open("/Users/Bella/Downloads/moby10b.txt", "r") #open Moby-Dick file +lines = f.readlines() #put all lines from Moby-Dick into a list +f.close() #close the file + +new_file = open("/Users/Bella/Documents/moby-dick_lowercase.txt", "w") #write new file to Documents folder + +for line in lines: + new_file.write(line.lower()) + +new_file.close() + +``` \ No newline at end of file diff --git a/docs/intermediate/06-images.md b/docs/intermediate/06-images.md new file mode 100644 index 00000000..0b20b711 --- /dev/null +++ b/docs/intermediate/06-images.md @@ -0,0 +1,11 @@ +# Reading Images in Python + +Opening and displaying images in Python is pretty straightforward. It's a bit different than opening text files though. To open an image, let's use Python's built-in pil library. + +```python +from PIL import Image +my_image = Image.open("/path/to/image.jpg") +my_image.show() +``` + +The CoderDojo AI Racing League will explore more around working with image data. \ No newline at end of file diff --git a/docs/intermediate/06-object-classes.md b/docs/intermediate/06-object-classes.md new file mode 100644 index 00000000..c7cebe2b --- /dev/null +++ b/docs/intermediate/06-object-classes.md @@ -0,0 +1,63 @@ +# Object Classes in Python + +In the mid 1960s the term Object-Oriented Programming” (OOP) was coined by Alan Kay, one of the pioneers in computer science. Alan's idea was to group data structures and the functions that manipulate that data together in a unit called an object class. Although many Python programmers can be productive just writing simple functions, because there are many Python libraries that use objects, we think you should be familiar with these terms, even if you decide you don't want to deal with the complexities of building your own Python object classes. + +Python also has features that allow you dynamically probe the structure of object classes, even if you can't find the original source code used to create the object classes. If you can't recall how to do something with an object class these tools can provide you a quick reminder. + +## The dir() function + +```py +my_list=[1,2,3,4] + +dir(my_list) +``` + +returns: +```py +['__add__', + '__class__', + '__contains__', + '__delattr__', + '__delitem__', + '__dir__', + '__doc__', + '__eq__', + '__format__', + '__ge__', + '__getattribute__', + '__getitem__', + '__gt__', + '__hash__', + '__iadd__', + '__imul__', + '__init__', + '__init_subclass__', + '__iter__', + '__le__', + '__len__', + '__lt__', + '__mul__', + '__ne__', + '__new__', + '__reduce__', + '__reduce_ex__', + '__repr__', + '__reversed__', + '__rmul__', + '__setattr__', + '__setitem__', + '__sizeof__', + '__str__', + '__subclasshook__', + 'append', + 'clear', + 'copy', + 'count', + 'extend', + 'index', + 'insert', + 'pop', + 'remove', + 'reverse', + 'sort'] +``` \ No newline at end of file diff --git a/docs/intermediate/07-modules.md b/docs/intermediate/07-modules.md new file mode 100644 index 00000000..deb255ae --- /dev/null +++ b/docs/intermediate/07-modules.md @@ -0,0 +1,47 @@ +# Introduction to Intermediate Python + +# Modules +Modules are a way to store and install reusable Python code. You can create your own modules by defining a set of functions that may be useful to other developers, and packaging these functions in a specific way so the other developers can download and easily integrate your code into their projects. + +To define a module, lets create a new file called ```fibo.py``` in your current directory. Lets add the following code: + +```python +def fib(n): # write Fibonacci series up to n + a, b = 0, 1 + while a < n: + print(a, end=' ') + a, b = b, a+b + print() + +def fib2(n): # return Fibonacci series up to n + result = [] + a, b = 0, 1 + while a < n: + result.append(a) + a, b = b, a+b + return result +``` + +Now that we have some functions defined, how do we access them? Let's open the Python shell (or create a new file), and run/create: + +```python +import fibo + +fibo.fib(10) + +res = fibo.fib2(10) +print(res) +``` + +Now we have created and called our very own Python module! We can also import specific functions instead of the whole module, like this: + +```python +from fibo import fib + +fib(10) +``` + +In further labs, we will see how you can view the contents of a given module using the dir() functionality. + + +* Lab heavily inspired (code credited to): [https://docs.python.org/3/tutorial/modules.html](https://docs.python.org/3/tutorial/modules.html) \ No newline at end of file diff --git a/docs/intermediate/08-dir.md b/docs/intermediate/08-dir.md new file mode 100644 index 00000000..7faa1ff2 --- /dev/null +++ b/docs/intermediate/08-dir.md @@ -0,0 +1,89 @@ +# Python Objects and the dir() function + +In Python we have the ability to associate a group of functions with any object class. These functions when grouped together with an object are called *methods*. You can think of them *accessor methods* go get access to the data or behavior of an object class. + +For example, a dictionary object has the ```.items()``` method. So how do you know what methods are available to you? That's where the dir function comes in! Just pass whatever data or object you want to know about as an argument. + +```py + +my_list=[1,2,3,4] + +dir(my_list) + +['__add__', + '__class__', + '__contains__', + '__delattr__', + '__delitem__', + '__dir__', + '__doc__', + '__eq__', + '__format__', + '__ge__', + '__getattribute__', + '__getitem__', + '__gt__', + '__hash__', + '__iadd__', + '__imul__', + '__init__', + '__init_subclass__', + '__iter__', + '__le__', + '__len__', + '__lt__', + '__mul__', + '__ne__', + '__new__', + '__reduce__', + '__reduce_ex__', + '__repr__', + '__reversed__', + '__rmul__', + '__setattr__', + '__setitem__', + '__sizeof__', + '__str__', + '__subclasshook__', + 'append', + 'clear', + 'copy', + 'count', + 'extend', + 'index', + 'insert', + 'pop', + 'remove', + 'reverse', + 'sort'] + +``` + +You can see this returns a list of methods, a lot of which begin and end with ```__```, those are special methods that we won't worry about for the purposes of this lab. But the rest of them are methods we can use on a list object. For example, ```.pop()```. + +```python + +my_list=[1,2,3,4] + +last=my_list.pop() + +print(last) #prints 4 + +print(my_list) #prints [1,2,3] + +``` + +The pop() method will remove and return the last element from the list, that is if you call pop without passing in an argument, as we just did. Pop will accept one optional argument, that is index...you can pass the index of the item you want to remove from the list and return. With lists we start counting indices from 0. So in the list below 1 is at the 0th index and 6 is at the 5th index. + +```python + +my_list=[1,2,3,4,5,6] + +print(my_list[0]) # prints 1 + +print(my_list[5]) # prints 6 + +print(my_list.pop(2)) # removes and prints 3 + +print(my_list) # prints [1,2,4,5,6] +``` \ No newline at end of file diff --git a/docs/intermediate/09-regex.md b/docs/intermediate/09-regex.md new file mode 100644 index 00000000..47d5dcba --- /dev/null +++ b/docs/intermediate/09-regex.md @@ -0,0 +1,147 @@ +# Regular Expressions in Python + +A regular expression is a shorthand notation for describing a search pattern. Regular expressions are handy whenever you have one ore more strings and you want to detect if a specific patten of characters appears in that string. Regular expressions are mostly standardized so that if you use them other developers will quickly be able to read this the patten notation and understand the function of the pattern. + +## Finding four digits in an input string +Let's take a simple example. What if you want an input to to a function to contain four digits. The string ```\d``` matches a single digit. Here is the python program to check to see if there are four consecutive digits in an input string: + +```python +import re +my_input = '1234' + +# check to see if there are four consecutive digits somewhere in the input +digits_test = re.search('\d\d\d\d', my_input) + +if digits_test: + print("We have four digits!") +else: + print("Invalid data") +``` + +[Run the regex-01 program on Trinket.io](https://trinket.io/python3/780b1810ad) + +If you run the program as-is, it will tell you that the string **'1234'** will pass the test and the string **We have four digits**, but if you change the my_input to be **123x** then the **Invalid data** will be returned. + +The name of the regular expression module is just "re". We must have an import this line with the "re" module at the start of our program. The key line has **re.search()** function with two parameters. The first parameter is the regular expression and the second is the string to be tested. + +The exact way to read this line is: + + check to see if there are four consecutive digits somewhere in the input + +Note that if you put letters or spaces before or after the four digits the test will still pass. + +## Finding exactly four digits +What if you wanted **exactly** four digits? For example say you have a phone system that has exactly four-digit extensions. To do this you would need to also specify two additional characters: the start expression **"^"** and the end character **"$"**. + +Here is what that program would look like: + +```python +import re +my_input = '1234' + +# check to for exactly four digits +digits_test = re.search('^\d\d\d\d$', my_input) + +if digits_test: + print("We have exactly four digits!") +else: + print("Invalid data") +``` + +[Run the regex-02 program on Trinket.io](https://trinket.io/library/trinkets/ef0666e0d3) + +## Checking for one or more digits +Sometimes we don't know exactly how many digits an input field should contain. We might just want to say "look for one or more digits". We can do this by using the **'+'** expression which says "look for one or more of the previous expression". Here is a program that will check for one or more digits: + +```python +import re +my_input = '1' + +# check for one or more digits +digits_test = re.search('^\d+', my_input) + +if digits_test: + print("We have one or more digits!") +else: + print("Invalid data") +``` + +## Common regular expression characters for validating inputs +Now that you have seen several examples of regular expressions, lets list some of the most common ones we use to validate input data.: + +|Expression|Meaning|Example| +|---|---|---| +|\d|A single digit in the range 0 to 9|**'\d\d\d'** for validating **'123'**| +|^|The start of a string|**'^hello'**| +|$|The end of a string|**'hello'$**| +|[a-z]|Any lowercase character in the range of **'a'** to **'z'**|**'[a-z]\d\d'** will match **'x12'**| +|[A-Z]|Any uppercase character in the range **'A'** to **'Z'**|**'\d\d[A-Z]** will match **'47N'**| +|**.**|Zero or more occurrences of the previous expression|**'\d.'** would match an empty string, '1' or '12'| +|**+**|One or more occurrences of the previous expression|**'\d+'** would match '1' or '12' but would not match an empty string| +|**|**|Or|**'a|b|c\d'** will match **'a1'** or **'ab2'**| +|**\w**|Characters that typically make up words. This includes upper and lowercase charcters [a-z], [A-Z] and digits as well as the underscore|**\w** would match **'hello_world123'**| + +Note that there is an important difference between using the "dot" (period) and the "plus" characters. We use the dot when we want to check for an optional integer. We use the plus sign when we require an integer. When we are gathering information from users in a form, we often must be careful to specify what fields should require an integer input for the field to be valid. + + +## Combining Regular Expressions: Checking E-mail Address + +We can combine regular expressions to make more complicated expressions. For example here are some rules that form a simple e-mail address: + +1. a string of word characters +2. the ampersand character **'@'** +3. a string of additional word characters +4. the period character **'.'** +5. some additional characters such as 'com', 'edu' + +Here is a regular expression that does this: + +```python +re.search('^\w+@\w+\.\w+$', my_input) +``` + +Recall that the \w+ character looks for one or more word characters. +Note that we had to use a backslash in from of the period so it takes it as a literal period and not as a regular expression for zero-or-more of prior expression. + +Here is a program that prompts the user to input a valid e-mail: + +```python +import re +my_input = 'a@myco.com' + +# check for one or more digits +if re.search('^\w+@\w+\.\w+$', my_input): + print("E-mail address valid") +else: + print("Error: Invalid email address!") +``` + +## Finding The Right Regular Expression + +You often are confronted with validating complex fields like phone numbers, zip codes, and postal addresses. The good news is that many other people have also needed to do this and with a bit of searching you can probably find a regular expression that meets your needs. One of the best places to look for regular expressions is [RegExLib](ttps://www.regexlib.com/). You can not only search for a regular expression but you can test it on common patterns. Other users have also voted on which regular expressions are their favorites. There are also categories of regular expressions such as: + +1. E-mails +2. Dates and times +3. Strings +4. Numbers +5. URI +6. Addresses/Phone +7. Markup +8. Miscellaneous + +## From Search to + +The re module offers a set of functions that allows us to search a string for a match: + +Function Description +findall Returns a list containing all matches +search Returns a Match object if there is a match anywhere in the string +split Returns a list where the string has been split at each match +sub Replaces one or many matches with a string + + +## Python Regular Expression References + +[Python RegEx Cheat Sheet](https://www.debuggex.com/cheatsheet/regex/python) +[Python Regular Expressions HOWTO](https://docs.python.org/3/howto/regex.html#regex-howto) + diff --git a/docs/intermediate/10-debugging.md b/docs/intermediate/10-debugging.md new file mode 100644 index 00000000..89a99412 --- /dev/null +++ b/docs/intermediate/10-debugging.md @@ -0,0 +1,46 @@ +# Debugging in Python + +Uncaught errors in a Python script will cause it to abruptley hault. Utilizing the error output, also known as a stack trace will help us determine the root cause. The code below throws an error. + +```python + +import random + +my_list=[] #create empty list + +#get a random item from a list +def choose_random(some_list): + return random.choice(some_list) + + +for i in range(1,10): #(produces 1,2,3,4,5,6,7,8,9 over the 9 iterations of the loop) + my_list.append(i) #add the number to my_list + if i==1: #if the number of the current iteration of the loop is 1 + my_list.pop(0) #remove the first element from the list + random.choice(my_list) #randomly chose an element from the list + +``` + +This code throws an error and produces the following stack trace: + +``` +--------------------------------------------------------------------------- +IndexError Traceback (most recent call last) + in () + 7 if i==1: + 8 my_list.pop(0) +----> 9 random.choice(my_list) + +~/anaconda3/lib/python3.7/random.py in choice(self, seq) + 259 i = self._randbelow(len(seq)) + 260 except ValueError: +--> 261 raise IndexError('Cannot choose from an empty sequence') from None + 262 return seq[i] + 263 + +IndexError: Cannot choose from an empty sequence +``` + +You can see the actual error, an IndexError is being thrown in the code for the random module (line 261 in random.py). The output text is helpful, it's saying it can't choose a random item from an empty list. So why is our list empty? We now need to determine where in our code the error is occurring, if you look up line 9, that's referring to line 9 in our code. So we know that line's causing the error, so we then have to ask in what case we're passing an empty list into random.choice(). If we go through each iteration of the loop, we can see that it's on the first iteration when i==1, that we remove the first element from my_list, doing this leaves an empty list and passing it into random.choice() causes the error. + +The first step in debugging should always be to read the stack trace, if the source of the error is not self-evident, StackOverflow and Google are your next best bet. \ No newline at end of file diff --git a/docs/intermediate/11-advanced-trinket-libs.md b/docs/intermediate/11-advanced-trinket-libs.md new file mode 100644 index 00000000..0bda92ed --- /dev/null +++ b/docs/intermediate/11-advanced-trinket-libs.md @@ -0,0 +1,16 @@ +# Advanced Trinket Libs + +```py +import sys +import math +import matplotlib +import numpy +import processing +import pygal +import random +import re +import string +import time +import turtle +import urllib +``` \ No newline at end of file diff --git a/docs/intermediate/12-plot-sin.md b/docs/intermediate/12-plot-sin.md new file mode 100644 index 00000000..4046b6b5 --- /dev/null +++ b/docs/intermediate/12-plot-sin.md @@ -0,0 +1,68 @@ +# Using Trinket to Learn MatPlotLib +Python is notable for having a rich library of tools for viewing data. In this lesson we will use +Trinket to learn how to use the popular matplotlib - a Python library for plotting data. + +This example uses the trigonometry function Sine. Don't worry if you have not taken a trigonometry yet. It is just a simple function that generates a wave of vertical height that range between -1 and 1 as we move down the X axis. Imagine a circle rotating and the sin() function will reflect the angle of a point on the edge of the circle going up and down and the circle turns. + +See the [Wikipedia Article on Sine](https://en.wikipedia.org/wiki/Sine) for a description of the function. + +## How Matploglib works +In order to get a plot of any function on the screen we need to first generate a list of points. Each point has an x and y coordinate and the point (0,0) is usually on the middle left corner of the screen. + +Trinket has a plotting area of about 200 by 200 pixels. So we will generate 200 points and plot them to get our chart. + +One of the best ways to get started is to create two lists: one of x coordinates and one of y coordinates like this: + +```py +x_list = [] +y_list = [] +``` + +We then need to create a loop that has the x range change uniformly from 0 to 200 and then for each of these x values we will generate a y value and put them into the list. We will use the list.append() function to add these numbers in pairs to both the X and Y lists like this: + +```py +for p in range(0,200): # we will use 200 points + x_list.append(p/10) + y_list.append(math.sin(p/10)) +``` + +In this case "p" is just a temporary counter for each point we are going to add. We are also going to divide both the X and Y values by 10 so that we get the values from 0 to 20 (not 0 to 200). That way we can see how the sin() function varies in this range. + +Once we have our x and y points in two lists we are ready to plot. + +Here is how we use the matplot library: + +``` +import matplotlib.pyplot as plt +... +plt.plot(x_list,y_list) +plt.show() +``` +Each time we change the list values we need to run the plt.show() function to do the drawing. + +## Full Example +Here is a full working example. Note that we need to import the math library to use the sin() function. + +``` +import matplotlib.pyplot as plt +import math + +x_list = [] +y_list = [] +for p in range(0,200): # we will use 200 points + x_list.append(p/10) + y_list.append(math.sin(p/10)) + +plt.title('Using matploglib.pyplot to show the sin(x) function from x=0 to 20') +plt.xlabel('x') +plt.ylabel('sin(x)') +plt.plot(x_list,y_list) +plt.show() +``` + +![Plot Sin](../img/plot-sin.png) + +## Getting Fancy +We can also put a grid axis and color on the plot: + +plot.grid(True, which='both') diff --git a/docs/intermediate/20-installing-local-python.md b/docs/intermediate/20-installing-local-python.md new file mode 100644 index 00000000..cc9d8776 --- /dev/null +++ b/docs/intermediate/20-installing-local-python.md @@ -0,0 +1,69 @@ +# Installing a Local Desktop Python + +The next few labs are labs that must be run on your local computer because the will interact with the local operating system and local file system. You will not be able to use Trinket to run these programs. + +The main site for Python is here: +[https://www.python.org/](https://www.python.org/) + +If you go to that site there will be pages for Downloads and Documentation for each version of your desktop or PC. + +The best way to get detailed instructions or hints is to do a web search for a phrase such as: + +1. *"How do I install Python on my Windows 10 PC"* +2. *"How do I install Python on my Mac"* +2. *"How do I install Python on my Raspberry Pi"* + +You can also give a precise version of Python and your operating system such as: + +*"How to install Python 3 on MacOS Mojhave"* + +These tools usually give you command line access to Python using "Terminal" or "Shell". To use Python you will need to open a command line and type "python --version" to verify that Python is installed correctly. + +Here is an example of what this looks like from a command line: + +```sh +$ python --version +Python 2.7.16 +``` + +This indicates that python + +## You System Path +The system path is a key list that holds a set of sequential places that Python looks for functions. +```sys.path``` is a list of places to look for code and it will execute the first function that it matches in this path. + +```py +import sys +# The system path is a key list that holds a set of sequential places that Python +# looks for functions. +# sys.path returns a list of places to look for code and it will execute the +# first function that it matches +myPath = sys.path +for step in range(0, len(myPath)): + print(step+1, myPath[step]) +``` + +## Using Conda Environments +We use conda to keep all our Python projects separate. + +```sh +conda create -n coderdojo python=3 +conda activate coderdojo +``` + +## Installing Python in an Integrated Development Environment (IDE) + +## Dealing with Python Environments +If you are new to Python and you run into problems getting Python running on your desktop, you are not alone! This challenges was well captured by cartoon, XKCD: + +![Python XKCD](../img/python_environment.png) + +The root cause of this complexity is that there the Python community is a large sprawling mass of free-thinking developers that don't always play nicely together. They are always improving their own libraries and releasing new versions. They often depend on old libraries that conflict with the newer libraries on your local system. They use Python for many different things on different operating systems and to solve different types of problems. Some of them care deeply about compatibility with past version of Python and some of them need the latest version to be productive. + +Here are a few simple rules: + +1. Always be aware of the version of Python you are using. Use the ```python --version``` tool to see this. +2. Use different "environments" for different projects tasks that may need different version of different libraries. Be familiar with tools like ```conda``` to manage these environments. If you do use conda, make sure to activate these environments before you start. +3. Know how to see where Python is looking for it's libraries and know how to use the ```sys.path``` function +4. Use tools such as ```pyenv``` to control what Python environment you are using. +5. Beware of using the default Python environments. They are often out of date. \ No newline at end of file diff --git a/docs/intermediate/intro.md b/docs/intermediate/intro.md deleted file mode 100644 index 5c13f169..00000000 --- a/docs/intermediate/intro.md +++ /dev/null @@ -1,19 +0,0 @@ -# Introduction to Intermediate Python - -This course assumes you are familiar with beginning concepts in Python such as variables, loops, conditionals, random numbers, functions, function parameters, lists and basic recursion. - -The concepts in this course include: - -1. Variables and Scope -2. Data types -3. Checking Data Types of Function Parameters -4. Maps -5. Files -6. Images -7. Defining Your Own Modules -8. the dir() functions -9. Regular expressions -10. Debugging - - - diff --git a/docs/intermediate/regex-03.py b/docs/intermediate/regex-03.py new file mode 100644 index 00000000..50f707ff --- /dev/null +++ b/docs/intermediate/regex-03.py @@ -0,0 +1,10 @@ +import re +my_input = '1' + +# check for one or more digits +digits_test = re.search('^\d+', my_input) + +if digits_test: + print("We have one or more digits!") +else: + print("Invalid data") \ No newline at end of file diff --git a/docs/intermediate/regex-04.py b/docs/intermediate/regex-04.py new file mode 100644 index 00000000..d280d5b9 --- /dev/null +++ b/docs/intermediate/regex-04.py @@ -0,0 +1,10 @@ +import re +my_input = 'a2' + +# check for one or more digits +digits_test = re.search('^[a|b|c]\d$', my_input) + +if digits_test: + print("We a or b or c followed by a digit") +else: + print("Invalid data") \ No newline at end of file diff --git a/docs/intermediate/regex-05.py b/docs/intermediate/regex-05.py new file mode 100644 index 00000000..3c54f4b9 --- /dev/null +++ b/docs/intermediate/regex-05.py @@ -0,0 +1,8 @@ +import re +my_input = 'a@myco.com' + +# check for one or more digits +if re.search('^\w+@\w+\.\w+$', my_input): + print("E-mail address valid") +else: + print("Error: Invalid email address!") \ No newline at end of file diff --git a/docs/intermediate/regex.py b/docs/intermediate/regex.py new file mode 100644 index 00000000..952e60d8 --- /dev/null +++ b/docs/intermediate/regex.py @@ -0,0 +1,10 @@ +import re +my_input = '1234' + +# check to for exactly four digits +digits_test = re.search('^\d\d\d\d$', my_input) + +if digits_test: + print("We have exactly four digits!") +else: + print("Invalid data") \ No newline at end of file diff --git a/docs/jupyter/Python_Introduction.ipynb b/docs/jupyter/Python_Introduction.ipynb new file mode 100644 index 00000000..6d723b0c --- /dev/null +++ b/docs/jupyter/Python_Introduction.ipynb @@ -0,0 +1,258 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Object Oriented Programming (OOP) in Python" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Python follows all these - \n", + "- Functional Programming\n", + "- Object Oreinted Programming\n", + "- Procedural Oreinted Prgramming" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**OOP is based on the concept of objects**\n", + "\n", + "Objects are defined by their own properties or attributes\n", + "\n", + "Software is designed by using objects that interact with each other.\n", + "\n", + "**Various benefits which we see are below-**\n", + "- being faster and easier to execute\n", + "- providing a clear structure for a program\n", + "- making code easy to modify, debug and maintain\n", + "- making it easier to reuse code\n", + "\n", + "Some object oriented languages are - Java, C++, Python, Javascript\n", + "\n", + "Example -\n", + "Take an example of car\n", + "A car has model name, a colour, a year in which it was manufactured, an engine size and so on.\n", + "We would therefore ceate a Car object with name, colour, engine size and year as attributes\n", + "For every new car we use, we would use the car object. Either we have a 2019 Blue BMW or a 2017 red Audi. \n", + "In each instance, we could reuse the code contained in original object." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Main principles of OOP are -\n", + "\n", + "- Encapsulation\n", + "- Abstraction\n", + "- Inheritance\n", + "- Polymorphism\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Introduction to Python" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**What is coding?**\n", + "\n", + "Computer Programmers or coders are people who write step by step instructions that can make\n", + "a computer perform a task. Eg - We can get computers do addition,make music, edit pictures, fly a rocket to Mars.\n", + "\n", + "Computers are **dumb** boxes which can't do anything of it's own. We need to feed the inputs or instructions in order to get something done.\n", + "\n", + "**Programming Languages -**\n", + "\n", + "In order to tell a computer to do something, we need to learn a programming language.\n", + "Python is a text based programming language. A coder needs to code using words, abbrevaiations, numbers and symbols.\n", + "Eg -\n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "6" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "3+3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Anyone can code -\n", + "\n", + "Coding is very easy - you just need to keep some basic rules and commands in mind and\n", + "then start writing programs to suit your skills and interests\n", + "- think logically\n", + "- Pay attention to detail\n", + "\n", + "**Bugs -**\n", + "Bugs are errors in code that make programs behave in unexpected wways.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Python was first released in 1990s and now is used to build millions of apps, games and websites.\n", + "\n", + "**Why you should learn Python**\n", + "- Easy to read and write\n", + "- Works everywhere\n", + "- Batteries included\n", + "- Handy tools\n", + "- Great support" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Real world use cases of Python**\n", + "\n", + "- Crawling the web\n", + "- Serious business - banks, big stores, insurance, healthcare & **analytics**\n", + "- Medical marvels\n", + "- In the movies\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**First Program in Python**" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, World!\n" + ] + } + ], + "source": [ + "print(\"Hello, World!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Whether you want to play the game?Yes\n", + "Yes\n" + ] + } + ], + "source": [ + "student=input('Whether you want to play the game?')\n", + "print(student)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "str" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(student)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "pratham='I am a student \\\n", + "Good'" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I am a student Good\n" + ] + } + ], + "source": [ + "print(pratham)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs/jupyter/variables-and-strings.ipynb b/docs/jupyter/variables-and-strings.ipynb new file mode 100644 index 00000000..cce82816 --- /dev/null +++ b/docs/jupyter/variables-and-strings.ipynb @@ -0,0 +1,557 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Variables in Python" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you want to write a useful code you need to store and label pieces of information and that's what variables do.
\n", + "Variable needs a name and what you want to store in it
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Assign a value**" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "age cole=12" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Print Value**" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "20\n", + "12\n" + ] + } + ], + "source": [ + "print(age_cole)\n", + "print(AGE_cole)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**NAMING VARIABLES** :
\n", + "- Choose good names
\n", + "- Can contain letters,numbers,underscores but they should begin with letters\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**DO's and DON'Ts :**
\n", + "- Start name with letter
\n", + "- Any number or letter can be used
\n", + "- Symbols like -,/,# or @ are not allowed
\n", + "- Spaces can't be used
\n", + "- Underscore to be used instead of space
\n", + "- Uppercase & Lowercase are different
\n", + "- Avoid words python uses as commands
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TYPES :**
\n", + "- Whole numbers are Integers
\n", + "- Decimal points are floats
\n", + "- Programs usually count things in integers
\n", + "- Floats are used for measurement
" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "8\n", + "8\n", + "8\n" + ] + } + ], + "source": [ + "a=b=c=8\n", + "print(a)\n", + "print(b)\n", + "print(c)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n" + ] + } + ], + "source": [ + "a,b,c=1,2,3\n", + "print(a)\n", + "print(b)\n", + "print(c)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In python we have to initialize variables else we will get NOT DEFINED error" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'z' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mz\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mNameError\u001b[0m: name 'z' is not defined" + ] + } + ], + "source": [ + "print(z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Python Specialty**
\n", + "In some languages we have specify what type of data a variable may contain in it's declaration itself
\n", + "This reserves memory space and is called \"static typing\"
\n", + "In python no such limitations and it adjusts the memory allocation to suit the data values assigned to the variables
\n", + "This is called dynamic typing" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Simple Calculation :**" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "42\n" + ] + } + ], + "source": [ + "x=6\n", + "y=x*7\n", + "print(y)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "42\n" + ] + } + ], + "source": [ + "x=10\n", + "print(y)" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "70\n" + ] + } + ], + "source": [ + "x=10\n", + "y=x*7\n", + "print(y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Strings in Python" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Coders use word string for any data made up of a sequence of letters or other characters
\n", + "Words & sentences are stored as strings
\n", + "Almost all programs use strings at some point
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Strings in Variables :**
\n", + "Strings can be assigned to variables
\n", + "They must always have quotation marks ''" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Joela\n" + ] + } + ], + "source": [ + "name=\"Joela\"\n", + "print(name)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I like to code in Python\n" + ] + } + ], + "source": [ + "pratham='I like to code in Python'\n", + "print(pratham)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I like coding.\n", + "I want to learn Python.\n" + ] + } + ], + "source": [ + "pratham='''I like coding.\n", + "I want to learn Python.'''\n", + "print(pratham)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He said, Aren`t they learning coding in Python\n" + ] + } + ], + "source": [ + "silly_string='He said, Aren`t they learning coding in Python'\n", + "print(silly_string)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He said, \"Aren't they learning coding in Python\"\n" + ] + } + ], + "source": [ + "silly_string='''He said, \"Aren't they learning coding in Python\"'''\n", + "print(silly_string)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Adding backslash(\\) before each quotation mark in a string to avoid syntax error
\n", + "This is called Escaping" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He said, Aren't they learning coding in Python\n", + "He said, \"Aren't they learning coding in Python\"\n" + ] + } + ], + "source": [ + "silly_str1='He said, Aren\\'t they learning coding in Python'\n", + "print(silly_str1)\n", + "silly_str2=\"He said, \\\"Aren't they learning coding in Python\\\"\"\n", + "print(silly_str2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Combining Strings :**
\n" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome to Python Session, Joela\n" + ] + } + ], + "source": [ + "name='Joela'\n", + "greeting='Welcome to Python Session, '\n", + "message=greeting+name\n", + "print(message)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "***Extra Tips***
\n", + "You can count number of characters in a string by function **len()**" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "32" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len(message)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Embedding Values in Strings**" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I scored 95 points\n" + ] + } + ], + "source": [ + "score=95\n", + "msg=\"I scored %s points\"\n", + "print(msg % score)" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I scored 95 and 98 points in 2 games\n" + ] + } + ], + "source": [ + "msg=\"I scored %s and %s points in 2 games\"\n", + "print(msg % (95,98))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Multiplying Strings**" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a a a a a a a a a a \n" + ] + } + ], + "source": [ + "print(10*'a ')" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello World!!!\n", + " Hello World!!!\n", + " Hello World!!!\n", + " Hello World!!!\n" + ] + } + ], + "source": [ + "print(\"Hello World!!!\")\n", + "spaces=' '*25\n", + "print('%s Hello World!!!' % spaces)\n", + "spaces=' '*50\n", + "print('%s Hello World!!!' % spaces)\n", + "spaces=' '*75\n", + "print('%s Hello World!!!' % spaces)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs/repl/08-shape-function.md b/docs/repl/08-shape-function.md new file mode 100644 index 00000000..a25a6bf1 --- /dev/null +++ b/docs/repl/08-shape-function.md @@ -0,0 +1,25 @@ +# Repl Shape Function + +```py +import turtle +t = turtle.Turtle() +colorList = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink', 'brown', 'gray', 'gold'] + + +def shape(color, x, y, dist, edges): + t.penup() + t.goto(x,y) + t.pendown() + t.color(color) + t.begin_fill() + angle = 360 / edges + for i in range(edges): + t.fd(dist) + t.rt(angle) + t.end_fill() + + +shape('red', -100, 100, 50, 4) +shape('green', 50, 50, 50, 6) +shape('blue', 50, -50, 40, 8) +``` diff --git a/docs/strategy/index.md b/docs/strategy/index.md new file mode 100644 index 00000000..19f9a5e3 --- /dev/null +++ b/docs/strategy/index.md @@ -0,0 +1,5 @@ +# Teaching Strategies + +## Order of Concepts + +[Order of Concepts](oder-of-concepts.md) \ No newline at end of file diff --git a/docs/strategy/order-of-concepts.md b/docs/strategy/order-of-concepts.md new file mode 100644 index 00000000..bb443658 --- /dev/null +++ b/docs/strategy/order-of-concepts.md @@ -0,0 +1,123 @@ +# Order of Concepts + +## Intro + +What is the role of visual feedback in teaching beginning Python? + +## No Visual Feedback + + +``` +What are the key concepts in learning Python for a 9th +grade student in the US? List the concepts in the order +they should be taught and add justification for ordering. +``` + +1. Introduction to Programming and Python + +Justification: Begin by explaining what programming is and how it allows us to communicate instructions to a computer. Introducing Python's simplicity and readability sets a positive tone for beginners. +2. Setting Up the Development Environment + +Justification: Before coding, students need to install Python and set up an Integrated Development Environment (IDE) or use an online coding platform. This ensures they're ready to practice coding examples. +3. Basic Syntax and Output with print() + +Justification: Learning how to display information is fundamental. The print() function is simple and provides immediate visual feedback, which is motivating for new learners. +4. Variables and Data Types + +Justification: Variables store information that programs manipulate. Understanding data types like integers, floats, strings, and booleans is essential for handling different kinds of data. +5. Basic Operators and Expressions + +Justification: Operators allow students to perform calculations and manipulate data. This includes arithmetic operators (+, -, *, /) and logical operators (and, or, not). +6. User Input with input() + +Justification: Allowing programs to accept user input makes them interactive. Learning to use the input() function helps students understand how to receive and process external data. +7. Conditional Statements (if, elif, else) + +Justification: Conditionals introduce decision-making in programs. They allow the code to execute different actions based on certain conditions, which is critical for dynamic programming. +8. Loops (for and while Loops) + +Justification: Loops enable code to be executed repeatedly without redundancy. Understanding loops is key for tasks that require iteration, like processing items in a list. +9. Lists and Basic Data Structures + +Justification: Lists store collections of items. Introducing lists teaches students how to handle multiple pieces of data efficiently. +10. Functions and Modular Programming - Justification: Functions promote code reusability and better organization. Learning to write functions helps students break down complex problems into manageable pieces. + +11. Introduction to Modules and Libraries - Justification: Python's strength lies in its extensive libraries. Teaching how to import and use modules like math or random expands the functionality available to students. + +12. Basic File Input/Output - Justification: Reading from and writing to files allows programs to handle data persistence. This is important for applications that need to save or load data. + +13. Error Handling with try and except - Justification: Errors are inevitable in programming. Learning to handle exceptions makes programs more robust and helps students debug their code effectively. + +14. Dictionaries and Sets - Justification: These data structures are useful for storing data in key-value pairs (dictionaries) and for handling unique items (sets). They broaden the ways students can manage data. + +15. Introduction to Object-Oriented Programming (OOP) - Justification: OOP introduces classes and objects, allowing for more complex and scalable code. A basic introduction prepares students for advanced programming concepts. + +16. Developing a Simple Project - Justification: Applying learned concepts in a project reinforces understanding. It provides practical experience and a sense of accomplishment. + +17. Review and Next Steps - Justification: Reviewing consolidates knowledge. Discussing next steps keeps students motivated to continue learning, possibly introducing topics like web development or data science with Python. + +By following this progression, students build a strong foundation in Python programming. Each concept builds upon the previous ones, ensuring a smooth learning curve tailored for 9th-grade students. + + +## With Visual Feedback + +``` +Now assume that all students have access to the +trinket.io website that allows students to learn +using turtle graphics to get fast visual feedback. +Generate a list of the key Python concepts and the +order they should be taught. +``` + +1. Introduction to Programming and Python + +Justification: Start by explaining what programming is and introduce Python as an accessible language for beginners due to its readability and simplicity. +2. Setting Up the Development Environment on Trinket.io + +Justification: Guide students on how to use Trinket.io for writing and running Python code, specifically leveraging its support for turtle graphics to provide immediate visual feedback. +3. Introduction to Turtle Graphics + +Justification: Begin coding with turtle graphics to engage students visually. Drawing simple shapes helps them understand basic programming concepts in an enjoyable way. +4. Basic Syntax and Turtle Commands + +Justification: Teach fundamental Python syntax through turtle commands like forward(), backward(), left(), and right(), which illustrate function calls and parameters. +5. Variables and Data Types + +Justification: Introduce variables to store values that control turtle movements (e.g., distances, angles). Cover basic data types like integers and floats in this context. +6. Loops with Turtle Graphics (for and while Loops) + +Justification: Use loops to create patterns and complex shapes, demonstrating iteration in a visually engaging manner. +7. Functions and Code Reusability + +Justification: Teach how to define functions to encapsulate code for drawing specific shapes or patterns, promoting modular programming and code reuse. +8. Conditional Statements (if, elif, else) + +Justification: Introduce decision-making by changing turtle behavior based on conditions (e.g., drawing different shapes based on user input). +9. User Input with input() + +Justification: Make programs interactive by allowing users to influence turtle drawings, enhancing engagement and understanding of input handling. +10. Lists and Data Collections - Justification: Teach lists by storing sequences of colors, movements, or shapes for the turtle to use, illustrating how to manage collections of data. + +11. Randomness and the random Module - Justification: Use the random module to add unpredictability to turtle drawings, making programs more dynamic and fun. + +12. Advanced Turtle Graphics Techniques - Justification: Explore advanced features like setting pen size, colors, filling shapes, and using loops to create intricate designs. + +13. Error Handling with try and except - Justification: Introduce error handling to make programs more robust, especially when dealing with user input that affects turtle actions. + +14. Introduction to Object-Oriented Programming Concepts - Justification: Provide a basic understanding of objects and classes by explaining that the turtle itself is an object with methods and attributes. + +15. Basic File Input/Output (Optional based on Trinket.io capabilities) - Justification: If supported, teach how to read from and write to files to save or load data that influences turtle drawings. + +16. Developing a Comprehensive Turtle Graphics Project - Justification: Apply all learned concepts in a final project where students create their own complex drawing or simple animation, reinforcing their skills and creativity. + +17. Review and Next Steps - Justification: Summarize the key concepts covered and discuss how these skills can be applied to other areas of Python programming, encouraging continued learning. + +By incorporating turtle graphics early and throughout the curriculum, students benefit from immediate visual feedback that enhances understanding and keeps them engaged. This progression builds foundational Python skills while leveraging the interactive capabilities of Trinket.io, providing a tailored and effective learning experience for 9th-grade students. + + + + + + + +``` \ No newline at end of file diff --git a/docs/trinket/00-introduction.md b/docs/trinket/00-introduction.md index 907041a3..b106b414 100644 --- a/docs/trinket/00-introduction.md +++ b/docs/trinket/00-introduction.md @@ -4,25 +4,33 @@ These labs assume that you have internet access and a modern web browser such as Chrome. -We use the [Trinket web site](https://trinket.io/) because it has many of the basic turtle drawing libraries implemented in and easy-to-use web environment. It is appropriate for students just getting started with python programming but has limited libraries for our advanced data analysis and plotting labs. The free -version is limited to the older Python 2.X functionality. If you want to try another web-based system that support turtle graphics and Python 3.X we suggest the web site [repl.it](http://repl.it) +We use the [Trinket web site](https://trinket.io/) because it a kid-safe place that has many of the basic turtle drawing libraries implemented in and easy-to-use web environment. It is appropriate for students just getting started with python programming but has limited libraries for our advanced data analysis and plotting labs. The free version is limited to the older Python 2.X functionality, but this meets all the needs of our beginning python class. + +If you want to try another web-based system that support turtle graphics and Python 3.X we suggest the web site [repl.it](http://repl.it). Note that repl.it is not specifically designed for kids. + +## Beginning Python Journey Map + +![Beginning Python Journey Map](./beginning-python-journey-map.png) +The map above is a visual guide to our Introduction to Python course. Students start their journey in the upper left corner at the green start circle. They then journey through each of the lessons until they reach the finish line. Many of our courses give badges and laptop stickers for students that complete the journey from the start to the finish. ## List of Trinket Python Learning Labs For students that are new to programming, here are some sample programs (what we call learning labs) that you can try. You can learn by reading the sample programs, going to the Trinkit.io site and changing some values in the code. Each of the labs has experiments at the end you can do to extend to see if you have mastered the concepts before you go on to the next lab. -0. [Introduction](./00-introduction.md) - this file -1. [Turtle graphics](./01-turtle-graphics.md) - introduction to the Turtle Graphs library with list of drawing functions -2. [Simple square](./02-simple-square.md) - draw a square by moving and turning right four times +1. [Trinket Account](./01a-trinket-account.md) - introduction to the Turtle Graphs library with a list of drawing functions +2. [Turtle graphics](./01b-turtle-graphics.md) - introduction to the Turtle Graphs library with a list of drawing functions +3. [Simple square](./02-simple-square.md) - draw a square by moving and turning right four times 4. [Variables](./03-variables.md) - add variables for the move edge distance and angle 5. [Loops](./04-loops.md) - add a loop to make our code smaller 6. [Conditionals](./05-conditionals.md) - add an if statement to change the color 7. [Functions](./06-functions.md) - create a shape function 8. [Function parameters](./07-function-parameters.md) - add parameters to our function -9. [Random](./08-random.md) - generate random numbers -9. [Lists](./08-list.md) - store a list of colors -10. [Inputs](./11-input.md) - get some input from the user -11. [Recursion](./12-recursion.md) - create a function that calls itself - -## Journey Map +9. [Random](./08-random.md) - generate random numbers that are used do drive the turtle +10. [Lists](./08-list.md) - store a list of colors +11. [Inputs](./11-input.md) - get some input from the user +12. [Recursion](./12-recursion.md) - create a function that calls itself to draw a tree +13. [Shapes](./13-shape-module.md) - creating a separate module to draw shapes +14. [Color picker](./14-color-picker.md) - picking different colors +15. [Sine wave](./15-sine-wave.md) - creating a sine wave +16. [Changing Background](./16-changing-background.md) - changing background image and capturing keyboard +17. [Controlling MouseClicks](./17-controlling-mouseclicks.md) - Tracking mouse clicks -![Intermediate Python Journey Map](../img/intermediat-python-journey-map.png) diff --git a/docs/trinket/01a-trinket-account.md b/docs/trinket/01a-trinket-account.md new file mode 100644 index 00000000..4413a02c --- /dev/null +++ b/docs/trinket/01a-trinket-account.md @@ -0,0 +1,14 @@ +# Getting Starts With Trinket + +These labs assume that you have internet access and a modern web browser such as Chrome. + +We use the [Trinket web site](https://trinket.io/) because it a kid-save place that has many of the basic turtle drawing libraries implemented in and easy-to-use web environment. It is appropriate for students just getting started with python programming but has limited libraries for our advanced data analysis and plotting labs. The free version is limited to the older Python 2.X functionality, but this meets all the needs of our beginning python class. + +## What can you do on Trinket? + +1. You can save programs +1. You can rename programs +1. You can create folders of programs +1. You can run your program +1. You can make the program fill the screen (fullscreen) +1. Download your Python code \ No newline at end of file diff --git a/docs/trinket/01-turtle-graphics.md b/docs/trinket/01b-turtle-graphics.md similarity index 55% rename from docs/trinket/01-turtle-graphics.md rename to docs/trinket/01b-turtle-graphics.md index a0f9700c..5a74a925 100644 --- a/docs/trinket/01-turtle-graphics.md +++ b/docs/trinket/01b-turtle-graphics.md @@ -1,9 +1,9 @@ -# Turtle Graphics Library +# Turtle Graphics ## What is the turtle graphics library? -Turtle graphs have been around for almost [50 years](https://en.wikipedia.org/wiki/Turtle_graphics). A turtle is a drawing object that has position, direction and a pen to draw as it moves around a grid. Turtle graphic are the preferred way to teach many concepts in computer science because they give you fast feedback. +Turtle graphs have been around for almost [50 years](https://en.wikipedia.org/wiki/Turtle_graphics). A turtle is a drawing object that has position, direction, and a pen to draw as it moves around a grid. Turtle graphics are the preferred way to teach many concepts in computer science because they give you fast feedback. Fast feedback allows you to quickly see the errors in your code and correct them. -For many of our introductory python labs we will use the turtle python library. Although there are many different versions of the turtle library, most of the commands are similar. What you learn with the trinket python system will be useful in other systems also. +For many of our introductory python labs, we will use the turtle python library. Although there are many different versions of the turtle library, most of the commands are similar. What you learn with the trinket python system will be useful in other systems also. ## Initialization commands There are three lines that will appear at the top of these labs: @@ -23,7 +23,7 @@ sue.shape('turtle') Just make sure you change all the names in the file to reference your new name. ## Moving the Turtle -There a five basic ways to move your turtle around the screen. Our screen is approximatly 300 points wide and 400 points high. The point (0,0) is at the center of our screen. The first four are relative commands. The last one will move the turtle to the absolute x and y location. +There are five ways to move your turtle around the screen. Our screen is around 400 points wide and 400 points high. The point (0,0) is at the center of our screen. The first four are relative movement commands. The last one will move the turtle to the absolute x and y location. - t.forward(40) - t.back(40) @@ -32,12 +32,12 @@ There a five basic ways to move your turtle around the screen. Our screen is ap - t.goto(x,y) ## Drawing -There are several ways to draw virtual "ink" on the screen. The most common way is to just move your turtle around. It will draw a thin black line by default. +There are several ways to draw virtual "ink" on the screen. The most common way is to just move your turtle around. It will draw a thin black line by default, but you can also change the pen color and the width of drawing. -- t.penup() -- t.pendown() -- t.color('red') -- t.pensize(5) +- [t.penup()](https://docs.python.org/3/library/turtle.html#pen-control) - no drawing will happen when the pen is up +- t.pendown() - drawing will occur on the screen when the turtle moves +- t.color('red') - set the pen to a specific color +- t.pensize(5) - set the width of the pen from 1 to 20. 5 is a good size. - t.begin_fill() - begin filling a region you draw around - t.end_fill() - end the fill region @@ -48,7 +48,8 @@ There are also a few built-in drawing functions. The circle function that takes ## Misc There are also a few other miscellaneous things you can do. You can do some drawing and then clear the screen. -- t.clear() +- t.clear() - clears the screen of all drawing +- t.hideturtle() - hides the turtle on the screen You can see a full list of the turtle commands [here](https://trinket.io/docs/python). Just click on the turtle area and scroll down. @@ -60,4 +61,6 @@ import random # get a random number between -200 and 200 myNumber = random.randint(-200, 200) ``` -This will generate a random number from -200 to 200. You can use this number to randomly place items on the drawing canvas. \ No newline at end of file +This will generate a random number from -200 to 200. You can use this number to randomly place items on the drawing canvas. + +Now, let's get started doing some fun drawing! \ No newline at end of file diff --git a/docs/trinket/02-simple-square.md b/docs/trinket/02-simple-square.md index bcea516c..170e9f4d 100644 --- a/docs/trinket/02-simple-square.md +++ b/docs/trinket/02-simple-square.md @@ -1,5 +1,5 @@ ## Drawing a Square -The following code is an example of drawing a square using turtle graphics. In this example the turtle moves foward 100 units and then turns right. The angle for the right turn is 90 degrees. It repeats these two functions four times to make a square. +The following code is an example of drawing a square using turtle graphics. In this example the turtle moves forward 100 units and then turns right. The angle for the right turn is 90 degrees. It repeats these two functions four times to make a square. ## Sample Code ```python @@ -19,6 +19,7 @@ dan.right(90) dan.forward(100) dan.right(90) ``` + ## Drawing ![](../img/simple-square.png) @@ -27,11 +28,11 @@ Here is a link to the Trinket web site with this program running: [https://trinket.io/python/564899ffe9](https://trinket.io/python/564899ffe9) You can click on this link and then press the Run button. You should see the python code on the left side and the drawing on the right side of your screen. -## Explaination +## Explanation The first three lines will be the same for all our programs. They import the turtle library into our program, create a new turtle object and then assign the turtle a shape icon. Although almost all the turtle libraries work this way, there are some minor differences you will see in future examples. -## Reorinenting your turtle -Note that at the start, the turtle is facing to the right. After the last instruction, it is also facing to the right. This is a common best practice so that the turtle gets reoriented after some drawing function. If you remove the last right(90) function and run the program again you will see the turtle ends up facing upward. But if you rerun the progam you will still get the same square because the orientation of the turtle is not stored between runs. +## Reorienting your turtle +Note that at the start, the turtle is facing to the right. After the last instruction, it is also facing to the right. This is a common best practice so that the turtle gets reoriented after some drawing function. If you remove the last right(90) function and run the program again you will see the turtle ends up facing upward. But if you rerun the program you will still get the same square because the orientation of the turtle is not stored between runs. ## Experiments Can you change the distance and angle the turtle moves? What happens when you change the numbers for the forward and right functions? Can you go left as well as right? diff --git a/docs/trinket/04-loops.md b/docs/trinket/04-loops.md index 6417b82d..41bd796c 100644 --- a/docs/trinket/04-loops.md +++ b/docs/trinket/04-loops.md @@ -21,8 +21,12 @@ for i in range(4): dan.write('done with square') ``` -## Running the Demo -[Run Square With Loop](https://trinket.io/python/6cadd3c046) +## Running the Example on Trinket + +[Run Loop Program on Trinket](https://trinket.io/python/6cadd3c046) ## Experiments -Can you make the turtle draw a larger square? Hint: change the distance to be 80. How big can you make the square before the turtle goes off the screen? +1. Can you make the turtle draw a larger square? Hint: change the distance to be 80. How big can you make the square before the turtle goes off the screen? +2. Can you make a hexagon? This is a figure with six sides. Hint: the angle will need to be 60 and the range limit will need to be 6. +3. Can you make an octagon? An Octagon has eight sides. Hints: Try using an angle of 45. +4. Can you make a stop sign? You will need to use a dan.color('red'). a dan.beginfill() and a dan.endfill(). You can add the text of the word "stop" by using dan.moveto(x,y) and dan.write("STOP",None,None, "30pt bold"). You can also use the dan.hideturtle() so that the outline of the turtle is not displayed at the end. See: [Python Stop Sign Tutorial](https://www.youtube.com/watch?v=HhxYt9Lskrw) diff --git a/docs/trinket/04a-stop-sign.md b/docs/trinket/04a-stop-sign.md new file mode 100644 index 00000000..76511db6 --- /dev/null +++ b/docs/trinket/04a-stop-sign.md @@ -0,0 +1,44 @@ +# Python Turtle Graphics Stop Sign + +![](../img/stop-sign.png) + +In this lesson, we will use variables and for loop to draw a stop sign. +We will also show how to use the penup, pendown, color, begin_fill, end_fill and write functions. +Our write function will also change the font size using the ```font=("Arial", 30, "normal")``` parameter. + +## Sample Code + +```python +import turtle +dan = turtle.Turtle() +dan.shape('turtle') + +distance = 50 +sides = 8 +# The angle we turn is related to the number of sides by this formula +angle = 360 / sides +my_color = "red" + +dan.penup() +dan.goto(-50, 100) +dan.pendown() +dan.color(my_color) +dan.begin_fill() +# repeat the forward/right functions for each side +for i in range(sides): + dan.forward(distance) + dan.right(angle) + +dan.end_fill() +dan.hideturtle() + +dan.penup() +dan.right(110) +dan.forward(80) +dan.color('white') +dan.write('STOP', font=("Arial", 30, "normal")) +``` + +## Link to Trinket + +[Draw a Stop Sign on Trinket](https://trinket.io/python/7f9eee8b80) \ No newline at end of file diff --git a/docs/trinket/05-conditionals.md b/docs/trinket/05-conditionals.md index 306b4fce..02c5eff8 100644 --- a/docs/trinket/05-conditionals.md +++ b/docs/trinket/05-conditionals.md @@ -3,13 +3,51 @@ In this example program we will make the turtle draw different sides of the square using different colors. +There are two things we do with equations in Python. The first is to use the equal sign to **assign values** on the left side of the equal sign to the values on the right side. The second thing we do is to **compare** values to the left and right of an operator. The result of a comparison is always TRUE or FALSE. + +Here is the basic syntax of the Python conditional operator. + +```py +if (i > 2): + # do something if i is greater than 2 +else: + # do something else when i is exactly 2 or less than 2 +``` + +## Simple Conditionals +Here is a program that + +```py +import turtle +dan = turtle.Turtle() +dan.shape('turtle') + +distance = 100 +angle = 90 + +for i in range(1, 5): + # i modulo 2 is the remainder after we divide by 2 + dan.write(i, font=("arial", 16, "normal")) + if i > 2: # true if i greater than 2 + dan.color('red') + dan.pensize(5) + else: # if i is exactly 2 or less than 2 + dan.color('blue') + dan.pensize(3) + dan.forward(distance) + dan.right(angle) +``` + +[Link to Trinket with Simple Conditional](https://trinket.io/python/db5978a312) + +## Changing Odd and Even Edge Colors We would like every other side to change color. To do this we will add an if-then-else block of code to our example program. This block of code is called a conditional block. The condition is an expression that evaluates to be either TRUE for FALSE. In our example we will test to see if the index of our loop (the letter "i") is ODD or EVEN. We can do this by looking at the remainder after we divide by 2. Python has a handy operator called the modulo operator that uses the percent character which is above the number five on your keyboard. The test for ODD or EVEN is this: ```py i % 2 ``` -In our previous loop lesson, we created an index that started at 1 and then changed to 2, 3 and finally 4. For 1 and 3, the first and third edges the result of divid by 2 will return 1 which is the same as TRUE. For 2 and 4 (the vertical sides of the square), the expression will evaluate to 0 since the remainder of 2/2 and 4/2 is zero. +In our previous loop lesson, we created an index that started at 1 and then changed to 2, 3 and finally 4. For 1 and 3, the first and third edges the result of divide by 2 will return 1 which is the same as TRUE. For 2 and 4 (the vertical sides of the square), the expression will evaluate to 0 since the remainder of 2/2 and 4/2 is zero. ```py import turtle @@ -21,9 +59,9 @@ angle = 90 # repeat the forward/right functions four times for i in range(4): - if i % 2: + if i % 2: # This is equivalent to if (i % 2) == 0: (true for odd numbers) dan.color('red') - else: + else: # if i is even dan.color('blue') dan.forward(distance) dan.right(angle) @@ -31,9 +69,20 @@ for i in range(4): dan.write('done with square') ``` -[Conditinal Sqare](https://trinket.io/library/trinkets/5b18dc55c6) +[Conditional Square](https://trinket.io/library/trinkets/5b18dc55c6) Can you make the turtle use a larger pen size? Try dan.pensize(10) for the red and dan.pensize(3) for the blue. ## Experiments -Can you change the width of the pen with the dan.penwidth(20) function? +1. Can you change the width of the pen with the dan.penwidth(20) function? +2. Show i +```py +for i in range(4): + dan.write(i ,None,None, "16pt bold") + if i % 2: + dan.color('red') + else: + dan.color('blue') + dan.forward(distance) + dan.right(angle) +``` \ No newline at end of file diff --git a/docs/trinket/06-functions.md b/docs/trinket/06-functions.md index d2747fb0..4332ff38 100644 --- a/docs/trinket/06-functions.md +++ b/docs/trinket/06-functions.md @@ -27,8 +27,9 @@ for i in range(4): dan.write('done with square') ``` +## Run the Example on Trinket -[Function](https://trinket.io/library/trinkets/e3a8279a76) +[Run the Functions Program on Trinket](https://trinket.io/library/trinkets/e3a8279a76) diff --git a/docs/trinket/07-flower.md b/docs/trinket/07-flower.md index caf3d01f..f1766041 100644 --- a/docs/trinket/07-flower.md +++ b/docs/trinket/07-flower.md @@ -48,12 +48,13 @@ dan.write('done with flower') ## Drawing ![](../img/flower.png) -## Run the Example -[Function](https://trinket.io/python/0de967d3e2) +## Run the Example on Trinket + +[Run the Flower Example on Trinket](https://trinket.io/python/0de967d3e2) ## Experiments 1. Can you change the colors of the petals? 2. Can you change the width of the stem of the flower using the pensize() function? 3. Can you change the size of the petals? -4. Can you change the number of petals? \ No newline at end of file +4. Can you change the number of petals? Why is this problem harder? What assumptions did the original author of the program make? \ No newline at end of file diff --git a/docs/trinket/07-function-parameters.md b/docs/trinket/07-function-parameters.md index cf1eb8f5..0f912fc3 100644 --- a/docs/trinket/07-function-parameters.md +++ b/docs/trinket/07-function-parameters.md @@ -1,5 +1,6 @@ -## Function= Parameters +# Function Parameters +## Lesson Objective Now we will create a new function that draw a square with a specific color at a specific x and y point. The function will take three inputs: - the color - the horizontal x position on the grid @@ -32,9 +33,12 @@ square('blue', 70, -50) ## Drawing ![](../img/four-squares.png) -[Function](https://trinket.io/library/trinkets/83e78b10f5) +[Link to Function in Trinket](https://trinket.io/library/trinkets/83e78b10f5) ## Experiments -Can you change the name of the function to be "petal"? \ No newline at end of file + +1. Can you change the name of the function to be "petal"? +2. Can you change the function to include the ability to pass in one color for the border, and one color for the center fill? +[Sample of Border Square Program](https://trinket.io/python/3377b0fbd8) \ No newline at end of file diff --git a/docs/trinket/08-list.md b/docs/trinket/08-list.md index 3380a2e0..7db8653e 100644 --- a/docs/trinket/08-list.md +++ b/docs/trinket/08-list.md @@ -20,7 +20,8 @@ import random dan = turtle.Turtle() dan.shape('turtle') -colorList = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink', 'brown', 'gray', 'gold'] +colorList = ['red', 'orange', 'yellow', 'green', 'blue', + 'purple', 'pink', 'brown', 'gray', 'gold'] dan.begin_fill() dan.color(colorList[3]) @@ -28,6 +29,32 @@ dan.circle(20) dan.end_fill() ``` +## Iterating over many colors + +```py +import turtle +import random +dan = turtle.Turtle() +dan.shape('turtle') + +color_list = ['red', 'orange', 'yellow', 'green', 'blue', + 'purple', 'pink', 'brown', 'gray', 'gold', 'cyan', 'Gainsboro', 'gray', + 'dimgray', 'LightSlateGray','AliceBlue', 'LimeGreen', 'DarkKhaki', 'Khaki'] + +dan.penup() +dan.goto(-180, 160) +dan.begin_fill() +for myColor in color_list: + dan.color(myColor) + dan.pendown() + dan.begin_fill() + dan.circle(10) + dan.end_fill() + dan.penup() + dan.forward(20) +dan.hideturtle() +``` + ## Drawing ![](../img/green-circle.png) @@ -35,4 +62,9 @@ dan.end_fill() [Draw a Green Circle Using List](https://trinket.io/python/6b93c1711f) ## Experiments -Can you change the name of the function to be "petal"? \ No newline at end of file + +1. Can you change the name of the function to be "petal"? +1. What does ```print(len(colorList))``` return? +1. Go to the [Trinket colors page](https://trinket.io/docs/colors) and see the name of other colors you can use. +1. What happens if a list does not fit on a single line? Can a list span multiple lines? +1. Can you use double quotes and single quotes in the same list? \ No newline at end of file diff --git a/docs/trinket/08-random.md b/docs/trinket/08-random.md index f14134fe..1a371d0b 100644 --- a/docs/trinket/08-random.md +++ b/docs/trinket/08-random.md @@ -33,11 +33,14 @@ dan.goto(0,0) ## Drawing ![](../img/random-circle.png) -[Draw 10 circles example on Trinket](https://trinket.io/python/00e2353a96) +## Run the Example on Trinket + +[Run the Random Example on Trinket](https://trinket.io/python/00e2353a96) ## Experiments 1. Can you create a variable that is used to control the distance from the origin to wander? Right now the distance is set to be 200 on each extent. 2. Can you create a variable for the number of circles to draw? -3. Go to the [Trinket colors page](https://trinket.io/docs/colors) and see the name of other colors you can use. Note that you can use \ No newline at end of file +3. Go to the [Trinket colors page](https://trinket.io/docs/colors) and see the name of other colors you can use. Note that you can use any of these colors in your lists. +4. Right now, all the circles are 7 pixels in size. Can you make the circles have a random size from 3 to 20? \ No newline at end of file diff --git a/docs/trinket/08b-random-stars.md b/docs/trinket/08b-random-stars.md new file mode 100644 index 00000000..d93b9365 --- /dev/null +++ b/docs/trinket/08b-random-stars.md @@ -0,0 +1,59 @@ +## Random Circles + +In this exercise we will draw 5 stars of different colors: +The colors are randomly picked from the list of colors +``` +colorList = ['red', 'orange', 'green', 'blue', 'purple', 'pink', 'brown', 'gray', 'gold'] +mycolor = colorList[random.randint(0,len(colorList)-1)] +``` +After these line runs, the variable mycolor will be assigned some random color from the list of colors myColorList. We will then use this color to fill a star. +The stars are drawn at random locations selected in x = random.randint(-max_distance, max_distance) + y = random.randint(-max_distance, max_distance) + The size of star is also randomly picked size = random.randint(15, 30) + +## Sample Code +```python +import turtle +import random +# this is a list of colors +colorList = ['red', 'orange', 'green', 'blue', 'purple', 'pink', 'brown', 'gray', 'gold'] +dan = turtle.Turtle() +dan.shape('turtle') +dan.delay(1) +dan.clear() +dan.penup() + +max_distance = 160 + +# draw an eight sided star +def star(x, y, size, color): + dan.goto(x, y) + dan.color(colorList[random.randint(0,len(colorList)-1)]) + dan.pendown() + dan.begin_fill() + for i in range(1,8): + dan.forward(size) + dan.right(150) + dan.forward(size) + dan.left(100) + dan.end_fill() + dan.right(10) + dan.penup() + +# draw a pattern at a random location on the screen +for i in range(5): + x = random.randint(-max_distance, max_distance) + y = random.randint(-max_distance, max_distance) + size = random.randint(15, 30) + color_index = random.randint(0,8) + # draw a star with size and color + star(x,y,size, color_index) + +# hide so we have a nice drawing +dan.hideturtle() +``` + + +## Experiments +1. Can you create a variable for the number of circles to draw? +2. Go to the [Trinket colors page](https://trinket.io/docs/colors) and see the name of other colors you can use. Note that you can use any of these colors in your lists. diff --git a/docs/trinket/08c-turtle-shapes.md b/docs/trinket/08c-turtle-shapes.md new file mode 100644 index 00000000..a6a7c1d3 --- /dev/null +++ b/docs/trinket/08c-turtle-shapes.md @@ -0,0 +1,50 @@ +# Change the Turtle Shape + +With the turtle shape() method we can change your turtle shape to be any of the following shapes + +1. arrow +2. turtle +3. circle +4. square +5. triangle +6. classic + +```py +import turtle +dan = turtle.Turtle() +dan.shape('square') +``` + +The ```classic``` shape is a small arrow. + +## Using a List of Shapes +What if we want to use a list of shapes? + +```py +import turtle, time +dan = turtle.Turtle() + +myList = ["square", "circle", 'triangle', 'arrow', 'classic', 'turtle'] + +for index in range(0, len(myList)): + dan.shape(myList[index]) + time.sleep(1) +``` + +```py +import turtle, time +dan = turtle.Turtle() + +myList = ["square", "circle", 'triangle', 'arrow', 'classic', 'turtle'] + +for myShape in myList: + dan.shape(myShape) + time.sleep(1) +``` + + +##Sample program +[Sample](https://trinket.io/library/trinkets/c9924a123a) + +## Experiments +Can you use the new shapes to draw a star or any other shape of your chosing \ No newline at end of file diff --git a/docs/trinket/11-input.md b/docs/trinket/11-input.md index 7a23afb5..d1e7fd27 100644 --- a/docs/trinket/11-input.md +++ b/docs/trinket/11-input.md @@ -1,4 +1,4 @@ -## Input +# Getting Inputs from the User We can prompt the user to supply a number using the input() function. @@ -23,5 +23,11 @@ while colorIndexInt > -1: dan.write('done!') ``` -# Example on Trinket -[Run Example](https://trinket.io/python/a4a951eeab) \ No newline at end of file +## Example on Trinket + +[Run the Input Example on Trinket](https://trinket.io/python/a4a951eeab) + +## Experiments + +1. Write a program that will prompt the user to enter the number of shapes to draw, the size of the shapes, the color of the shapes and the range of the screen to draw them (50 to 200). +2. Add some additional code to check the range of your expected values. If the input is out of range, then continue to prompt the user to enter the correct number until they get a valid number. Use a ```while``` statement to continue prompting. \ No newline at end of file diff --git a/docs/trinket/12-recursion.md b/docs/trinket/12-recursion.md index fc6864df..6609df54 100644 --- a/docs/trinket/12-recursion.md +++ b/docs/trinket/12-recursion.md @@ -41,8 +41,9 @@ draw_branch(myTurtle, colorList[0], length, 4) ## Drawing ![](../img/fractle-tree.png) -## Link to Program on Trinket -[Link to Program on Trinket](https://trinket.io/python/0406ae2ac0) +## Run Sample Program on Trinket + +[Run Recursion Program on Trinket](https://trinket.io/python/0406ae2ac0) ## Explanation The first three lines will be the same for all our programs. They import the turtle library into our program, create a new turtle object and then assign the turtle a shape icon. diff --git a/docs/trinket/13-shape-module.md b/docs/trinket/13-shape-module.md index 1238f904..fa7b58a1 100644 --- a/docs/trinket/13-shape-module.md +++ b/docs/trinket/13-shape-module.md @@ -2,9 +2,23 @@ In this lab we will create a set of drawing function and put them together into a new file. We will then import this file into our main.py file. +Example code to import the module in main.py +``` py +import turtle +from shape import * +dan = turtle.Turtle() +dan.shape('turtle') + +draw_triangle(dan, 'red', 5, 20, 30) + +draw_circle(dan, 'orange', 10, 0, 30) -## Sample Code +draw_square(dan, 'orange', 15, -20, 30) ``` + + +## Sample Codeimited t +```py # This is a custom module we've made. # Modules are files full of code that you can import into your programs. # This one teaches our turtle to draw various shapes. diff --git a/docs/trinket/14-color-picker.md b/docs/trinket/14-color-picker.md index 453150df..0febf292 100644 --- a/docs/trinket/14-color-picker.md +++ b/docs/trinket/14-color-picker.md @@ -1,3 +1,32 @@ ## Color Picker -[Color Picker](https://projects.raspberrypi.org/en/projects/colourful-creations/1) \ No newline at end of file +You are not limited to the colors by name [Trinket Colors](https://trinket.io/docs/colors). +You can use Hex and RGB values and let your imagination run wild. + +[Color Picker](https://projects.raspberrypi.org/en/projects/colourful-creations/1) + +#Example code +```py + +import turtle + +#turtle.setup(400,500) +wn = turtle.Screen() +wn.setup(400,500) +#turtle.title("Tess becomes a traffic light!") +wn.bgcolor("A7E30E") +tess = turtle.Turtle() +tess.color('#FA057F') +style = ('Arial', 40, 'bold') +tess.write('Hello', font=style, align='Center') +tess.hideturtle() + +``` + +## Experiments +Can you try different colors? +Can you change font properties in style object? + +The font name can as 'Arial', 'Courier', or 'Times New Roman' +The font size in pixels. +The font type, which can be 'normal', 'bold', or 'italic' \ No newline at end of file diff --git a/docs/trinket/15-sine-wave.md b/docs/trinket/15-sine-wave.md new file mode 100644 index 00000000..8746f370 --- /dev/null +++ b/docs/trinket/15-sine-wave.md @@ -0,0 +1,36 @@ +# Sine Wave +We can also use turtle graphics to do math function plots. + +Here is an example of plotting a sine function with turtle goto() functions. We calculate the new vertical value with the following function: + +```py +y = math.sin(math.radians(x)) +dan.goto(x, y * 80) +``` + +And we loop through about 400 values from -200 to 200. We use the radians() function to convert the numbers into a a number that will give us a single sine in the X range. + +```py +import turtle +dan = turtle.Turtle() +dan.shape('turtle') +# needed for the sin function +import math + +dan.penup() +dan.goto(-200, 28) +dan.color('blue') +dan.pensize(3) +dan.pendown() +for x in range(-200, 200): + y = math.sin(math.radians(x)) + dan.goto(x, y * 80) +``` + +Here is the output of this function: + +![Turtle Sine Wave](../img/turtle-sine-wave.png) + +## Link to Working Trinket Program + +[Link to Turle Sine Wave](https://trinket.io/python/b6a5eaf8d1) diff --git a/docs/trinket/16-changing-background.md b/docs/trinket/16-changing-background.md new file mode 100644 index 00000000..4472b727 --- /dev/null +++ b/docs/trinket/16-changing-background.md @@ -0,0 +1,23 @@ +## Changing background and using keys to move the rocket + +We can use trinkets to change the background and change the shape of the turtle with a custom image. +Also we can control the screen with the mouse. It gives a starting point for how to create a game. + +The following blog lays out the steps for creating a rocket ship +https://blog.trinket.io/using-images-in-turtle-programs/ + + +The images have to be the same size as the the screen size. Here are some other images that have been resized. + +#Background +![Night Sky matching screen size](../img/night_sky.png) + +#Rocketpanda +![Rocket panda](../img/rocketpanda.png) + +## Sample Program +[Sample](https://trinket.io/library/trinkets/eacf1bc102) + +## Experiments +1. Can you map another keyboard key to take some other actions like jump, draw a circle. +2. Use different images and create backgrounds of your choice, like rocketpanda gliding through night sky diff --git a/docs/trinket/17-controlling-mouseclicks.md b/docs/trinket/17-controlling-mouseclicks.md new file mode 100644 index 00000000..d0850623 --- /dev/null +++ b/docs/trinket/17-controlling-mouseclicks.md @@ -0,0 +1,112 @@ +## Getting a handle of the mouse clicks + +We can use trinkets to change the background and control mouse clicks. +Also we have access to the exact position where the mouse was clicked. That creates a lot of possibilities +for creating different interactions with the screen. + +Code to change screen color + +Code to get co-ordinates of mouse click +```py + x=turtle.xcor() + y=turtle.ycor() +``` + +Here is an example of setting the screen color. We then draw a square in the center of the screen. +When the user clicks a circle is drawn within the circle. On next click the circle increases in diameter. When the circle touches the square, it stops increaing in size. + +If the user clicks the screen outside the square the screen is refreshed + +```py + + +#import packages +import turtle +import random + +# global colors +col = [ 'yellow', 'green', 'blue', + 'white', 'orange', 'pink'] +circlecol = [ 'red', 'magenta', 'purple', + 'black', 'brown', 'turqouise' ] +# method to call on screen click +tina = turtle.Turtle() +circlediameter=10 +squaresize = 200 + +def drawCircleOnMouseClick(x, y): + global circlecol + global circlediameter + print(" x={}, y={}".format(x,y)) + + ##If mouse is clicked within square increase size, if mouse clicked outside reset screen + if (isMouseClickWithinSquare(x,y)) : + ## Check if diameter is same size as square + if (circlediameter <= squaresize/2): + print(" circlediameter={}, squaresize={}".format(circlediameter,squaresize)) + ##If yes do not increase the size else increase the size + circlediameter += 10 +##If mouse is clicked outside the square, reset the screen - draw a new square + else: + screenreset() + + + draw_circle(tina, circlediameter, getCircleColor() ) + +def getBgColor(): + ind = random.randint(0, 5) + return col[ind] + +def getCircleColor(): + ind = random.randint(0, 5) + return circlecol[ind] + +def drawsquare(turtle, size, color, startx, starty): + turtle.penup() + turtle.goto(startx, starty) + turtle.pendown() + turtle.fillcolor(color) + turtle.color(color) + turtle.begin_fill() + for i in range(4): + turtle.forward(size) + turtle.left(90) + turtle.end_fill() + +def draw_circle(turtle, diameter, color): + turtle.penup() + turtle.goto(0, -diameter) + turtle.pendown() + turtle.fillcolor(color) + turtle.color(color) + turtle.begin_fill() + turtle.circle(diameter) + turtle.end_fill() + +def screenreset(): + tina.reset() + drawsquare(tina, squaresize, getBgColor(), -100, -100 ) + +def isMouseClickWithinSquare(x, y): + return (x >= -100 and x <= 100 and y >= -100 and y <= 100) +# set screen +sc = turtle.Screen() +sc.setup(400, 400) +sc.bgcolor('skyblue') +screenreset() + +##Screen can respond to mouseclick and we can tell it what action to take i.e. method to call + + +# call method on screen click +sc.onscreenclick(drawCircleOnMouseClick) +``` + +##Sample Program +[Sample](https://trinket.io/library/trinkets/0c79d0d02a) + +## Experiments +1. Can you draw different shapes +2. Can you add some more colors in the arrays +3. Can you change background color of the screen +4. Can you try some other [events](https://docs.python.org/2.7/library/turtle.html#methods-of-turtlescreen-screen) \ No newline at end of file diff --git a/docs/trinket/beginning-python-journey-map.png b/docs/trinket/beginning-python-journey-map.png new file mode 100644 index 00000000..16d7fd5e Binary files /dev/null and b/docs/trinket/beginning-python-journey-map.png differ diff --git a/docs/trinket/examples.md b/docs/trinket/examples.md new file mode 100644 index 00000000..017661c8 --- /dev/null +++ b/docs/trinket/examples.md @@ -0,0 +1,8 @@ +# Trinket Examples + +1. [Bullseye Dart Game](https://trinket.io/python/90130df21a) +2. [Tic Tac Toe Game](https://trinket.io/library/trinkets/3913dfe7af) +3. [How to Find Prime Numbers?](https://trinket.io/library/trinkets/aa9d51a7b9) +4. [Drawing an Elephant](https://trinket.io/library/trinkets/9202036e6a) + +Use the [Turtle API](https://docs.python.org/2.7/library/turtle.html) documentation to check out what else is available. diff --git a/mkdocs.yml b/mkdocs.yml index e2a59616..eac9e91f 100755 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -3,26 +3,51 @@ nav: - CoderDojo TC: https://coderdojotc.github.io/CoderDojoTC/ - Beginning Python - Trinket: - Introduction: trinket/00-introduction.md - - Turtle Graphics: trinket/01-turtle-graphics.md - - Simple Square: trinket/02-simple-square.md + - Setting Up Trinket: trinket/01a-trinket-account.md + - Turtle Graphics: trinket/01b-turtle-graphics.md + - Turtle Square: trinket/02-simple-square.md - Variables: trinket/03-variables.md - Loops: trinket/04-loops.md + - Stop Sign: trinket/04a-stop-sign.md - Conditional: trinket/05-conditionals.md - Functions: trinket/06-functions.md - Flower: trinket/07-flower.md - Function Parameters: trinket/07-function-parameters.md - Lists: trinket/08-list.md + - List of Turtle Shapes: trinket/08c-turtle-shapes.md - Random Numbers: trinket/08-random.md + - Random Stars: trinket/08b-random-stars.md - Input: trinket/11-input.md - Recursion: trinket/12-recursion.md + - Shape Module: trinket/13-shape-module.md + - Color Picker: trinket/14-color-picker.md + - Sine Wave: trinket/15-sine-wave.md + - Changing background: trinket/16-changing-background.md + - Controlling mouseclicks: trinket/17-controlling-mouseclicks.md + - Other examples: trinket/examples.m - Beginning Python - Repl.it: - Square: repl/02-square.md - Flower: repl/07-flower.md + - Shape Function: repl/08-shape-function.md - Recursion: repl/12-recursion.md - Intermediate Python: - - Introduction: intermediate/intro.md + - Introduction: intermediate/01-intro.md + - Variables and Scope: intermediate/01-variables-scope.md + - Data Types: intermediate/02-data-types.md + - Data Types & Function Parameters: intermediate/03-data-type-validation.md + - Maps: intermediate/04-maps.md + - Files (local file system): intermediate/05-files.md + - Images (local file system): intermediate/06-images.md + - JSON: intermediate/05-json.md + - Object Classes: intermediate/06-object-classes.md + - Modules: intermediate/07-modules.md + - Dir: intermediate/08-dir.md + - Regular Expressions: intermediate/09-regex.md + - Debugging: intermediate/10-debugging.md + - Plotting sine: intermediate/12-plot-sin.md - Maze Solving with BFS: intermediate/bfsMaze.md - Maze Solving with DFS: intermediate/dfsMaze.md + - Installing Python: intermediate/20-installing-local-python.md - Jupyter: - Setup Turtle on Jupyter: jupyter/01-setup.md - Drawing Box Labs: jupyter/02-draw-box.md @@ -34,7 +59,9 @@ nav: - Advanced Python: - Stock Ticker Analysis: advanced/stocks.md - MNIST Digit Prediction: advanced/mnist.md - + - Strategy: + - Introduction: strategy/index.md + - Order of Concepts: order-of-cocepts.,d - Contributing: - How to Contribute Examples: contribute.md - Contact: @@ -42,8 +69,10 @@ nav: site_description: 'Resources for teaching Python to CoderDojo Twin Cities students.' site_author: 'Dan McCreary' -repo_name: 'python' +repo_name: 'GitHub Repo' repo_url: 'https://github.com/CoderDojoTC/python' + +# CoderDojo Standards from here down edit_uri: 'blob/master/docs' theme: name: material @@ -58,11 +87,16 @@ theme: markdown_extensions: - admonition - footnotes + - pymdownx.highlight + - pymdownx.superfences - toc: permalink: true - - codehilite: - linenums: true plugins: - search -markdown_extensions: - - codehilite +# Google Analytics Site ID: G-EP38Z3PVD5 +extra: + analytics: + provider: google + # https://analytics.google.com/analytics/web/#/p368752593/reports/intelligenthome + property: G-EP38Z3PVD5 + diff --git a/src/Untitled.ipynb b/src/Untitled.ipynb deleted file mode 100644 index 9178bb36..00000000 --- a/src/Untitled.ipynb +++ /dev/null @@ -1,60 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "data": { - "application/vnd.jupyter.widget-view+json": { - "model_id": "44cd4b90bb0940d682af9142be102085", - "version_major": 2, - "version_minor": 0 - }, - "text/plain": [ - "Turtle()" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "from ipyturtle import Turtle\n", - "t = Turtle()\n", - "t.forward(100)\n", - "t.right(90)\n", - "t" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "turtle", - "language": "python", - "name": "turtle" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.10" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/src/Untitled1.ipynb b/src/Untitled1.ipynb deleted file mode 100644 index a5418b28..00000000 --- a/src/Untitled1.ipynb +++ /dev/null @@ -1,124 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], - "source": [ - "import turtle\n", - "bob = turtle.Turtle()\n", - "print(bob)" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "for i in range(8):\n", - " bob.fd(50)\n", - " bob.lt(45)\n", - "bob" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "t = turtle.Turtle()\n", - "t.clear()\n", - "t\n" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from ipyturtle import Turtle\n", - "t = turtle.Turtle()\n", - "t.clear()\n", - "t.color('blue')\n", - "t.pensize(5)\n", - "for i in range(8):\n", - " t.fd(50)\n", - " t.rt(45)\n", - "t" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "turtle", - "language": "python", - "name": "turtle" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.10" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/src/Untitled2.ipynb b/src/Untitled2.ipynb deleted file mode 100644 index 6ff9c7f0..00000000 --- a/src/Untitled2.ipynb +++ /dev/null @@ -1,52 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "2" - ] - }, - "execution_count": 1, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "1+1" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.2" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/src/draw-for-squares-input-colors.py b/src/draw-for-squares-input-colors.py new file mode 100644 index 00000000..c52d21f0 --- /dev/null +++ b/src/draw-for-squares-input-colors.py @@ -0,0 +1,36 @@ +# J.E. Tannenbaum +# Released: 11/10/2021 - Initial release +# 11/10/2021 - Cleaned up and added comments +# https://trinket.io/python/94326b4743 + +import turtle # Load the library +jet = turtle.Turtle() # Create the turtle object and name it +jet.shape("turtle") # Set the shape + +def drawIt(color, distance, angle): + jet.color(color) + jet.begin_fill() + jet.forward(distance) + jet.right(angle) + jet.forward(distance) + jet.right(angle) + jet.forward(distance) + jet.right(angle) + jet.forward(distance) + jet.end_fill() + +# Set the distance and angle variables +distance = 40 +angle = 90 + +colors = [] +for i in range(4): + color = input("Enter a color:") + colors = colors + [color] + +for color in colors: + drawIt(color, distance, angle) + +# We are done, so hide the turtle +jet.hideturtle() + diff --git a/src/intermediate/sine-plot.py b/src/intermediate/sine-plot.py new file mode 100644 index 00000000..3401c06c --- /dev/null +++ b/src/intermediate/sine-plot.py @@ -0,0 +1,23 @@ +import numpy as np +import matplotlib.pyplot as plot +# Get x values of the sine wave +time = np.arange(0, 10, 0.1); + +# Amplitude of the sine wave is sine of a variable like time +amplitude = np.cos(time) + +# Plot a sine wave using time and amplitude obtained for the sine wave +plot.plot(time, amplitude) + +# Give a title for the sine wave plot +plot.title('Sine wave') + +# Give x axis label for the sine wave plot +plot.xlabel('Time') + +# Give y axis label for the sine wave plot + +plot.ylabel('Amplitude = sin(time)') +plot.grid(True, which='both') +plot.axhline(y=0, color='k') +plot.show() diff --git a/src/ops/01-intro.md b/src/ops/01-intro.md new file mode 100644 index 00000000..e69de29b diff --git a/src/ops/README.md b/src/ops/README.md new file mode 100644 index 00000000..9e9ed90a --- /dev/null +++ b/src/ops/README.md @@ -0,0 +1,9 @@ +# Using Python Do Operations Management + +This directory is for teaching how to use Python to do Operations Management. This includes things like: + +1. Montoring the network +2. Getting notified if a remote computer is not working +3. Creating deploymnet scripts that install software on a remote system +4. Creating graphs that display response times to remote sites +5. Building notification systems that tell people when performance drops below a specfic value diff --git a/src/ops/ping-all-os.py b/src/ops/ping-all-os.py new file mode 100644 index 00000000..f06f6632 --- /dev/null +++ b/src/ops/ping-all-os.py @@ -0,0 +1,18 @@ +import platform # For getting the operating system name +import subprocess # For executing a shell command + +def ping(host): + """ + Returns True if host (str) responds to a ping request. + Remember that a host may not respond to a ping (ICMP) request even if the host name is valid. + """ + + # Option for the number of packets as a function of + param = '-n' if platform.system().lower()=='windows' else '-c' + + # Building the command. Ex: "ping -c 1 google.com" + command = ['ping', param, '1', host] + + return subprocess.call(command) == 0 + +ping(127.0.0.1) diff --git a/src/ops/ping.py b/src/ops/ping.py new file mode 100644 index 00000000..4c0fad81 --- /dev/null +++ b/src/ops/ping.py @@ -0,0 +1,11 @@ +import os +# sample code taken from: https://stackoverflow.com/questions/2953462/pinging-servers-in-python +# This will the Unix "ping" command which will work from most Mac and UNIX systems but not on Windows +hostname = "127.0.0.1" # example of pinging the loopback address +response = os.system("ping -c 1 " + hostname) + +#and then check the response... +if response == 0: + print(hostname, 'is up!') +else: + print(hostname, 'is down!') diff --git a/theme/partials/footer.html b/theme/partials/footer.html index 01205051..55c25d13 100755 --- a/theme/partials/footer.html +++ b/theme/partials/footer.html @@ -47,7 +47,7 @@ {{ config.copyright }} {% endif %} - built with the Micro-Site Builder + All content is covered under the Creative Commons Attribution-NonCommercial-ShareAlike. {% include "partials/social.html" %} diff --git a/trinket/Beginning-Python-Journey-Map.pptx b/trinket/Beginning-Python-Journey-Map.pptx new file mode 100644 index 00000000..4ffe17fc Binary files /dev/null and b/trinket/Beginning-Python-Journey-Map.pptx differ diff --git a/trinket/python_filed_of_flowers.py b/trinket/python_filed_of_flowers.py new file mode 100644 index 00000000..5b096eb9 --- /dev/null +++ b/trinket/python_filed_of_flowers.py @@ -0,0 +1,48 @@ + +import turtle +import random +dan = turtle.Turtle() +dan.shape('turtle') + + +colorList = ['red', 'orange', 'yellow', 'blue', 'purple', 'pink', 'gold','green','brown', 'gray'] + +# draw first flower +dan.color(colorList[random.randint(0,6)]) +def petal(): + distance = 30 + angle =120 + dan.left(30) + # draw a triangle and fill in the color + dan.begin_fill() + dan.forward(distance) + dan.right(angle) + dan.forward(distance) + dan.right(angle) + dan.forward(distance) + dan.end_fill() + dan.left(angle) +# start off 45 right +dan.right(45) +# repeat the forward/right functions four times +for i in range(4): + petal() + +# draw on the screen 25 nore flowers +for i in range(25): + x = random.randint(-150, 150) + y = random.randint(-150, 150) + dan.color(colorList[random.randint(0,6)]) + dan.penup() + dan.goto(x,y) + dan.pendown() +# draw a new flower + for i in range(4): + petal() + + +dan.penup() +dan.goto(0,0) + + + \ No newline at end of file