Leaderboard


Popular Content

Showing content with the highest reputation since 07/19/2018 in all areas

  1. 1 point
    -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Tutorial and Practice: Introduction to Loops and Turtle -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Requirement: Watch up to Tutorial 4 This is an introduction to using while loops, for loops and turtle. Turtle is one of pythons built in GUI's ( Graphical User Interface ), don't get to excited this GUI is only used for drawing things on a canvas like simple shapes, lines and words. Python has other GUI's for creating actual interfaces with buttons and menus, ect, but that's a bit advanced for now, one step at a time. Loops are used to execute portions of code repeatedly, you could type out print("Hello World") 100 times if you really wanted to or you could utilize loops. Loops are a main staple of programming and you should focus on learning it carefully as it is an important part of programming. There are two types of loops you can use, we will go over both of them and then do a practice program to apply what you've learned. Getting started with While Loops: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- This is a loop many make mistakes with, the reason for that is that a while loop will continue to loop forever until it's condition to break out of the loop is met. Many mistakes are made here that result in an infinite loop as the condition is never met and this is usually an undesired effect as the program will be stuck in the loop until the program is closed. This is the basic layout of a while loop: while condition: Body of code you want looped You would also change the condition somewhere in this code so it doesn't loop forever, unless that is desired. Alright lets do an actual example code start up python and try out this code: While Loop Example 1: num = 0 # First lets make a variable it will serve as our condition for the loop. while num < 50: # While the number is less than 50. print("Hello World") # We print "Hello World" to the screen num += 1 # Now we increment num by 1 so it will eventually be 50 and drop us out of the loop # Without this increment num would stay 0 and be less than 50 always so the loop will always # be True and go forever as well, we REALLY don't want "Hello World" being printed forever. The program will run the code and when it hits the while loop it will check the condition to see if it evaluates to True. If it does it will enter the loop, if it doesn't then it will skip over the loop since the condition is False and never enter it. When in the while loop every time it reaches the end of the code in the loop it will go back up and check the condition again if it is still True it will enter the loop again, if not it will exit the loop and continue the program. Lets do another example to study this with two while loops, both, one or none may be entered and run depending on what the user inputs. While Loop Example 2: # This section prompts the user for input that we store in the variable num which will again # be used as our conditional statement for the loops. print("For this example try a number between 0 and 50, do not enter a float (decimal)") num = int(input("Enter a number for the loops: ")) print("") # We can use <, >, <=, >=, == don't be afraid to play around # with it to see the different effects it's the best way to learn. # This is the first loop, if num is less than 25 this loop will be entered. while num < 25: print("Entering the first loop, num is currently", num) # We increment num by 1 so that the condition will eventually be False and we will exit the loop. num += 1 print("") # This is the second loop, if num is less than 50 we will enter the loop while num < 50: print("Entering the second loop, num is currently", num) # Again we'll increment num by 1 so that the condition will eventually be False and we will exit the loop. num += 1 print("") print("Both while loop conditions are False now and we are out of the loops, num is now", num) Brain Teaser: What would happen if you switched the order of the loops like so, give it a try and watch carefully what happens: print("For this example try a number between 0 and 50, do not enter a float (decimal)") num = int(input("Enter a number for the loops: ")) print("") while num < 50: print("Entering the second loop, num is currently", num) num += 1 print("") while num < 25: print("Entering the first loop, num is currently", num) num += 1 print("") print("Both while loop conditions are False now and we are out of the loops, num is now", num) Can you guess why it runs like that? Answer: Sometimes we want the program to loop but we don't know how many times we need it to loop. This is where a while loop really comes in handy especially for looping menus, ect. Let's do one more example where we will continually prompt the user to enter text until the user types "exit", at which point we will drop out of the loop. This is what is known as controlling a loop with a Sentinel Value. While Loop Example 3: # First lets make a variable named text, this will store the users input and act as # our sentinel value to get out of the loop. We will also prompt the user to enter anything they want. text = input("Enter some text (The loop will only end when you type exit): ") # Now let's make a string variable named textStorage, as the name suggests it will # store all of the users input in one single string, for now we initialize it to an empty string for use later. textStorage = "" # Now for the main code, our loop. While text is not equal to "exit" (our escape/sentinel value) while text != "exit": # Enter the loop, add what was entered by the user to textStorage and add a space at the end # so that when we print it later it isn't all bunched together makingithardtoreadlikethis. textStorage += text + " " # Let's prompt the user to enter some more text and store their input in text # (this will over write what was previously stored hence the use of our textStorage variable, we don't want to lose it!) text = input("Enter some text (The loop will only end when you type exit): ") # Now we're at the end of the loop, it will go back up to the start of the loop and check if the # condition is still True, is text still not equal to "exit" (escape/sentinel value)? # If it is True we will run the loop again if it is False we will exit the loop and continue. # We are now out of the loop and can continue the code print("Exited the loop") # Here we print our textStorage variable, this will print everything the user entered while in the loop print(textStorage) As you can see loops are VERY useful and a powerful tool for programmers. There are many ways in which you can use loops to accomplish complicated tasks, you can even set a while loop to always be True by simply typing while True:. Why would you want a while loop to run infinitely, isn't that bad? Generally yes, but in some cases it is desired like for looping a menu, ect. However if a while True: is used the programmer generally puts in a break statement. A break is used to get you out of any loop at any point, we will be using breaks later, but just know that they can be used for any loop to get you out at any point in the loop even if the loops condition is not yet met. Getting started with For Loops: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- This loop type is another one that can be confusing for some and many make the error know as the off by one. This type of loop is good when you know exactly how many times you want the program to loop. The basic layout of a for loop is as follows: for variable generally most just use i or j but you can use anything here it's only used as a counter in range(initial value, end value): Body of code to loop Ok let's do an actual example you can run, remember our while loop "Hello World"? Lets do that again but with a for loop: For Loop Example 1: # We begin our for loop, i is used as a counter, it will automatically increment on it's own # Each time the for loop reaches the end of the code inside it will increment by 1. # i will start as 0 (our initial value) and go to 50 (our end value) and print "Hello World" 50 times. for i in range(0, 50): print("Hello World", i) # We're going to print i each time, watch and see what happens Did you see what happened with our i variable? Notice that i went from 0 to 49 inside the code, but it didn't go to 50 why is that? Well the simple answer is that range(initial value, end value) is actually run as range(initial value, end value -1). The reason we didn't do range(1, 50) is because that would have only printed "Hello World" 49 times not 50. To get it to print it 50 times we did range(0, 50) as this is actually 51 times (count 0) and -1 makes it 50 times. You could also do range(1, 51) or range(1, 50 + 1). I'm sure by now you can see why some run into the off by one error quite often especially if they aren't careful when using for loops. This is the basics of using loops, as this is just meant to be an introduction we will stop here for now and practice what we've learned shortly. There is just one more topic we need to discuss before we can do our practice program... Getting started with Pythons Turtle GUI: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Turtle is one of pythons built in GUIs generally used for drawing shapes, text and lines on a canvas. To be able to use Turtle and it's functions we need to first import it, we can do this by typing import turtle. Let's practice using some of turtles functions and mess around a bit: Turtle Example 1: # First we need to import turtle so we can use it's functions. # Importing is usually done at the top of the code. import turtle turtle.showturtle() # This shows the turtle (drawing cursor) turtle.circle(40) # This will make a circle with a radius of 40 turtle.color("blue") # Here we change the color of our "pen" to blue turtle.write("Hello World") # Now we write Hello World onto the canvas at the current coordinates turtle.penup() # Pull the pen up, if we don't do this we will draw a line when we move it. turtle.goto(-250, - 200) # Move to the following x, y coordinates on the canvas turtle.pendown() # Put the pen down to start drawing again turtle.pensize(5) # Let's make the "pen" thicker by 5 pixels turtle.fillcolor("red") # Let's make the color we fill things with red turtle.begin_fill() # Start filling with color turtle.circle(40, steps = 3) # We make another circle but only with 3 lines (steps) this makes a triangle! turtle.end_fill() # Stop filling with color turtle.penup() turtle.goto(-250, 200) turtle.pendown() turtle.hideturtle() # Here we hide the turtle (drawing cursor) so we can't see it. turtle.color("green") # Change the "pen" color to green now turtle.forward(200) # Draw a line forward 200 pixels turtle.right(90) # Turn our turtle (drawing cursor) 90 degrees turtle.color("purple") # Change "pen" color to purple now turtle.forward(100) # And draw another line forward 100 pixels turtle.showturtle() # Let's show the turtle again turtle.penup() turtle.goto(100, 200) turtle.fillcolor("orange") # Here we change the fill color to orange now turtle.begin_fill() turtle.circle(60, steps = 6) # Here we create a circle in 6 steps, this is a hexagon! turtle.end_fill() turtle.color("black") # Change the "pen" color to black turtle.write("One Stop Programming") # Now we write "One Stop Programming" at the current coordinates turtle.hideturtle() # Hide the turtle (drawing cursor) turtle.done() # We're finished drawing now so we pause it for viewing the canvas Now that we've practiced with turtle a little bit lets try a few small exercises before the actual practice program. Let's Begin: For this exercise try to create a small program using a loop of your choice, either will work. Here's what we want to accomplish, we want to draw 3 shapes on a canvas. It doesn't have to be anything fancy with colors ect but if you want to get crazy go for it and be as creative as you like. All we want to do is practice using a loop to draw 3 shapes on the canvas, everything you need has been covered up to this point. If you need to, look back at the examples. Hint: You may want to use at least 2 variables for the x, y coordinates and increment them inside the loop so you don't draw your shapes on top of each other. There are a few ways you can accomplish this exercise, below is my example of how I went about coding it. If your stuck or want to compare go ahead and scroll down to see my example code: While Loop Example: For Loop Example: Continued in next post.
  2. 1 point
    Alright let's do one last example before the practice program. We will use a break we will import turtle and import random. Random is used for well, exactly what you think it will be used for, it will be used for randomizing variables in our code to spice it up a bit so it isn't so predictable. For this example we're going to randomize some text, the color and draw it on the canvas. This program will be very similar to the practice program so be sure to reference it if needed. Note: I used \n in both the practice example and actual practice program, all this does is it tells the program to print a blank line for spacing purposes, it's the same as if you did print(""). Using \n just helps to reduce some of the code clutter. Practice Example Program: Alright you now should have everything at your disposal to tackle this next practice program, be sure to reference our practices and examples we've done up to this point for this coding practice. -=-=-=-=-=-=-=-=-=-=-=-=-=-=- Shapes Practice Program: -=-=-=-=-=-=-=-=-=-=-=-=-=-=- For this practice program we will be using everything thats been taught up to this point. The goal of this practice is to create a program that will give the user a menu, ask the user how many to draw, draw the selected shape onto a canvas, randomly color the shapes and give a menu option for randomly picking shapes so each one is different when drawn with randomly chosen colors if our user is indecisive. Heres a step by step break down of what needs to be done for this project, remember one step at a time: 1. Import random and turtle 2. Create the functions you need for randomly picking colors and drawing the shapes 3. Create the main menu with the list of shape options and make it loop 4. Setup any variables you may need such as x, y coordinates 5. The user needs to be prompted for the shape to draw from the menu 6. The user needs to be prompted for how many to draw you could do up to 24 if you want 7. Add in error checking in case the user enters an invalid option 8. Create an option that will randomly draw a different shape each time . If the user decided they wanted the program to draw 24 different shapes you should get circles, diamonds, ect drawn to the canvas all randomly colored as well. Here is a sample of my output: To create the above shapes all you need to do is change the steps for example turtle.circle(radius, steps = 5) this is the pentagon. Using steps 3-6 will give you the shapes listed here, a circle is just turtle.circle(radius). Feel free to get as creative as you like, again this is only to get you thinking and pick your brain a bit so don't worry if it seems to hard, it was meant to challenge you a little. Here is the completed code below, go ahead and compare, modify, reference or study. If you have any questions or run into problems on any of these practices and examples post it here for help, be sure to include the code that's giving you the issue, it's easier to troubleshoot if we can see it. Shapes Practice Program Completed Code: