Coding with Python

Coding with Python

Get started or add to your Python skills by using this blog! Share the link with your friends!

Use the “Comment” box to let us know how you like this introduction, to tell us about your Python projects, to share links to your projects, to ask questions, or to suggest new challenges. Please enter your name (first and last initials only or first name and last initial only) but DO NOT enter an email address or website. These comments are public!

Programs, photos and other documents that you send to us will be uploaded to this public folder. You may send your files to virusbashers@roboticsandbeyond.org and we will add them to the folder. Be sure you give your file a title you want to be seen in the folder.

Team leader Samantha S.

Why is Python important?

The coding language of Python is used very widely in many interesting applications. More than 3 billion phones, tablets and other devices run Python code somewhere in the background, and it is a critical part of nearly all server systems. It is used to code animated movies and games and has many other applications. Python is often the first coding language that students learn in college. It has millions of users around the world, provides vast libraries of code to help programmers in writing their code and is available for free. Due to its wide usage, you can find millions of videos and online sources to learn Python from. With just a little experience, Python documentation pages are easy to understand and use for your own programs. Python is best for ages 10 and up.

How to get started

First you will need to download the necessary software. Either search for Python downloads or click the link below.

https://www.python.org/downloads/release/python-380/

Then scroll down to the bottom and download and run the option that suits your operating system.

For a more detailed explanation, search YouTube or go to https://www.wikihow.com/Install-Python or https://livebook.manning.com/book/the-well-grounded-python-developer/chapter-2/v-1/7

Note: The second link ensures that Mac and Linux computers will not have their default Python overwritten, but it uses a virtual environment to do so.

BEGINNER PYTHON PROGRAMMERS (expand for challenges)

Important!  In the challenges below, a # sign followed by some text is not part of your code. It is just an explanation, or comment, for what that line of code is doing. You can type # and some text after a line of code, and the computer will not try to run it because the computer knows that it’s just a comment. Comments are very useful for other people using your program to understand what the code is doing. They are also very useful for you when you haven’t seen the program in a long time.

Beginner Programmer Challenge #1: Print Something: After installing Python, search for a program called IDLE. Click on it, and you will see a window called 3.8.x Shell. Create a new program by going to File -> New File.

Type print(“test”) in the file to print out the word “test.” Save your work by holding down Ctrl or Cmd and the S key or by going to File -> Save. Choose the folder that you want to save the program in and name it whatever you want. Next, go to Run -> Run Module to run your program. A window should pop up, showing the word “test.”

Beginner Programmer Challenge #2: Hello World: Use the print() command to print out Hello World, similar to the way you printed out “test.” The shell window should pop up, showing Hello World.

Beginner Programmer Challenge #3: Hello [Person]: This program uses the input() method. input() prints whatever is in between the parenthesis, then waits for the user to type something and press enter. The program then stores the typed message in the variable named inputVariable. Variables store information that can change or is going to be created once the program has run. The program then concatenates (shortens) the strings inside the print statement, then prints them together.

Create a new program:

inputVariable = input(“What does this variable store?”)

print (“The inputVariable stores a string called ” + inputVariable)

Using this program as a starting point, use input() to find a person’s name. Store that name inside a variable called name. Then print out hello and name next to each other. Bonus points go towards whoever adds punctuation.

Beginner Programmer Challenge #4: Rainbow Response: When you run this program, you’ll find that typing in different responses will result in different answers. The program also introduces conditional statements, prefixed by if or elif. The if statement above means that the computer will run the code directly below if it sees that “black” has been typed in. The elif statement – which stands for else if – runs when the condition of the if statement is not met so its instruction cannot run, and the elif conditional statement is true. In that situation, the program runs the code directly below the elif statement. As shown in the above program, multiple elif’s can be chained together. An else statement wraps up the whole lot, catching anything not covered by the if or elif statements above it. IMPORTANT! Conditional statements always use a double = sign that looks like this: ==.

Create a new program:

color = input(“What is your favorite color?”) # Store the user’s favorite color in color

if (color == “black”): # the double-equals is formed by two equals signs; it’s found in if’s

print(“So do I!”)

elif (opinion == “pink”): # the double-equals is also found in elifs – and anywhere else when the program needs to check if two values are equal

print(“That’s a nice color”)

elif (opinion == “blue”):

print(“I prefer other colors.”)

else:

print(“I don’t understand! What is this ” + color + “?”)

Can you expand this program to cover more colors? How many?

Tips & Tricks for the Beginner section:

  • The print() command needs quotes around strings to print them.
  • The input() function asks a question, which will need quotes around it. Ex: input(“Are you having fun?”)
  • Strings, integers, and values returned by functions can be stored in variables. Ex: color = “blue”
  • Strings need quotes around them to be printed, but variables do not.
  • Strings need concatenation with +’s between them. Ex:

ccString = “his” + “ is ” + “a” + “ concatenated ” + “string”

print(“T” + ccString + “.”)

This code, when run, will print the line: “This is a concatenated string.”

  • Every if, elif, and else needs a colon “:” at the end of the line.
  • Indentation counts!
  • Each elif statement must be before the else statement, otherwise it will not be used.

Remember to share your program code in the Comments below or send it to us in a file and we will upload it to our public Google Drive folder.

INTERMEDIATE PYTHON PROGRAMMERS (expand for challenges)

For those with some experience in Python here are a few fun challenges. You can submit a comment to the blog with questions. You can also submit ideas for other challenges.

Intermediate Programmer Challenge #1: Loop For a While: 

Create a new program: (be careful to follow the indentations of each line of code)

number = 5             # The number the program will try to find

rangeNum = 20        # The upper range of numbers the program will search across

j = 0             # j is a number that counts how many times the (while) loop runs

# a while loop runs while a condition true and stops when it is false

while (j < number):

print(“The current value in the while loop is ” + str(j))     #number j, now a string

j = j+1             # The value of j is being increased by 1

print (“number is ” + str(j))

for x in range(20):    # a for loop runs through each number in its range

print(“The current value in the for loop is ” + str(x))

if (x == number):

print(“number is ” + str(x))

break         # break breaks out of a loop and stops it

Run this program. Now change the values of number and rangeNum and rerun it. Which code is shorter? Which code creates less lines of output? Can you think of any situation where one loop would be more useful than another? Share your answers in the comments!

Intermediate Programmer Challenge #2: Turtle: When you run this program, a new screen will appear. A dart (our turtle) will draw a few lines.

Create a new program:

import turtle

t = turtle.Turtle()

t.forward(100)

t.left(90)

t.forward(50)

t.right(20)

t.penup()

t.forward(30)

Can you make your turtle draw a funny zig-zag?  A square? How short can you make your program?

Intermediate Programmer Challenge #3: Shapes: This program uses the turtle to draw a shape with 3 or more sides. In Challenge #4 you will use this knowledge to make really fun animations of shapes and colors!

Remember – the # sign followed by text is just a comment to tell you what that line of code is doing. You can type it into your code or leave it out.

Remember – save your programs!

Create a new program:

import turtle #This imports the turtle graphics module

t=turtle.Turtle() #Create a turtle drawing object and rename it to a shorter name

# Below is the definition of a method called Polygon. You must call Polygon with its two # parameters, sideCount (the number of sides) and sideLength (the length of each side)

def Polygon(sideCount, sideLength): #Defining a new function, called, “Polygon”

for x in range(sideCount): #This creates the polygon’s sides

t.forward(sideLength) #This lets you pick the number of pixels you want for the length of the side

t.right(360/sideCount) #There are 360 degrees in a polygon, so it should turn 360 divided by the number of sides

t.goto(0,0) #Resets the turtle to the center of the window

t.pendown()

Polygon(6,100) #Creates a hexagon (a 6-sided polygon) with side length of 100 pixels

Another challenge: Can you make a program with input() and turtle that can draw any polygon? If you make shapes with 100, 200, and 500 sides, what do they look like? What happens if the angles are off by a little?

Remember to share your program code in the Comments below or send it to us in a file and we will upload it to our public Google Drive folder.

ADVANCED PYTHON PROGRAMMERS (expand for challenges)

Advanced Programmer Challenge #1: Pixel Art: This program creates three functions called teleport, square, and rectangle. You can create as many functions as you want, and you can include parameters for each function. Use these functions, for loops, and anything else you can find to program your turtle to draw some amazing pixel-based art. Take a screenshot and share your amazing pictures in the comments.

Create a new program:

import turtle

t = turtle.Turtle()

def square(sideLength, sideColor, fillColor):

t.fillcolor(fillColor) # sets the fill color to flllColor

t.begin_fill() # tells Python to start tracking for a fill command

t.pencolor(sideColor) # sets the side Color

for x in range(4): # loops a square

t.forward(sideLength)

t.left(90)

t.end_fill() # tells Python to fill in the square

def rectangle(sideLength, sideWidth, sideColor, color):

t.fillcolor(color)

t.begin_fill()

t.pencolor(sideColor)

for x in range(2):

t.forward(sideLength)

t.left(90)

t.forward(sideWidth)

t.left(90)

t.end_fill()

def teleport(positionX, positionY): # this method moves the turtle without leaving a line

t.penup() # gets the turtle to stop drawing ink

t.goto(positionX, positionY) # moves the turtle

t.pendown() # gets the turtle to start drawing again

t.goto(0,0) # Resets turtle to center of screen

t.setheading(90) # turtle is facing up

Advanced Programmer Challenge #2: Etch-A-Sketch: Go to the Python documentation page on turtle at docs.python.org/3.8/library/turtle.html and take a look at turtle’s many methods. Using your previous knowledge of Python, what amazing program ideas can you come up with?

Section Tips & Tricks:

  • range(x) starts at 0 and goes to x-1
  • A for loop is useful for shortening code
  • turtle’s goto method sends the turtle to a different point
  • turtle’s penup() and pendown() commands respectively stop and start the turtle’s drawing ability
  • Interesting turtle methods are pencolor(), fillcolor(), goto(), circle(), stamp(), size(), speed() and…
  • shape() can have the following parameters: “arrow”, “turtle”, “circle”, “square”, “triangle”, or “classic”

Remember to share your program code in the Comments below or send it to us in a file and we will upload it to our public Google Drive folder.

More Links (taken from an upcoming book by one of Robotics And Beyond’s adult volunteers and instructors)

History of Python (very interesting and entertaining!): Python’s Tale

Many other great stories about computer hardware and software: Command Line Heroes

Share this Post

Leave a Comment

Your email address will not be published.