For the Python activity track, we'll be writing several programs. The steps are outlined below, with each part having an expand button. There are 6 parts.
For your first program, we are going to write a famous program. Perhaps the most famous program in the world. Any serious programmer has written this single line program many times.
print(“Hello world”)
Copy the code in the box above into your new file. Copy it exactly. Python really cares about white space and punctuation.
Time to save our work. From the menu bar at the top select File, then Save to save the contents of the file.
Here is the big moment. Go to the menu bar and select Run and then Run Module.
In the Python Shell you should see the words “Hello world” printed out. BAM! You just wrote a program. You can make the computer say whatever you want now. Muhahahaha!
Try exchanging the words Hello world with some other text. You can put most anything between the “ “ quote symbols and then select Run and Run Module to run the program again.
print(“Hello world”)
print(“I’ll do what I’m told until the robot uprising”)
Add the second line to your program; then save and run it again.
You will notice that the computer prints out whatever you put in between the “ “ quote symbols. It also prints the text in the second command on a new line. The text in between the “ “ quote symbols is called a string. That is the programmer’s term for a bunch of characters that the computer will simply print out.
Here is how this program works. First, the computer looks at the first line and recognizes it is a print command, so it reads the code between the (“ “) parentheses and tries to figure out what to print. Once it prints the contents of the (“ “) parentheses to the screen, it also prints an invisible instruction to start a new line. Then, it repeats the process for the second line.
Some of the words will change colors in the code. This is because the IDE recognizes the words, like print, as valid keywords in Python. It turns those keywords purple. It also recognizes that characters between “ “ quote symbols are strings and turns them green.
Now, delete the lines in your hello world program and start fresh with an empty file. Why did we say that computer tries to figure out what is between the “ “ quote symbols in the print command? Because sometime the computer has to put the string together from different parts that you give it.
Enter the following two lines into your program file:
name = “my name”
print(“Hello ” + name)
You should also try replacing the my name string on the first line with your actual name.
There are a few things going on in this simple little program. First off, you made a variable called name. A variable is like a box inside the computer with a label on it. You can put anything you want in it. Then, you can use the label to get Python to go and fetch the thing that is inside the box and use it in your code. On the first line you stuck your name in the variable. In the second line, you told Python to stick the contents of the variable on the end of “Hello .” You stuck them together using the + symbol. When strings are involved the + symbol will stick them together. The fancy programmer’s term for this is string concatenation.
Also, notice that we left an extra space after “Hello.” Why do you think we did that? What happens if you do not?
You can try and remove the space and run the program again to see what happens.
So, getting the computer to stick your name in a variable and print it out is nice, but would it not have been easier just write your name in the string in the Print statement? Sure.
Variables are more powerful than that though, because you do not actually have to know ahead of time what will be put in them.
Try running the two line program below. When the program asks for your name type it in. (Hint: you’ll need to hit the Enter key once you have typed your in name.) No one knows what string is going to be entered in the name variable until the program is run and you enter it.
name = input(“What is your name? “)
print(“Hello ” + name)
This last program introduces a new Python command -- input. The input command gets information from the user and puts it in a variable. The 3 lines are below.
name = input(“What is your name? “)
my_number = input(“Hello ” + name + “, pick a number ”)
print(“Your number is “ + my_number)
There are two interesting things going on in the second line of the program above. First, we introduced a new variable named my_number that collects a number from the user using a second input command. Second, notice that we use the + symbol on both sides of a variable and build a more complicated string. In this case, we inserted the contents of the name variable in the middle of the string.
The 4 line program below gets a number from the user, but then changes it by adding one to the number before it outputs it.
name = input(“What is your name? “)
my_number = input(“Hello ” + name + “, pick a number ”)
my_number = int(my_number) + 1
print(“Your number is “ + str(my_number))
There are two new commands in this program: int( ) and str( ). They are necessary because we are using the my_number variable two different ways. In the third line, we are using my_number like a number we can do math on, but to do that we have to let the computer know to treat it like a number. The int( ) command tells the computer to treat whatever is inside the ( ) symbols as an integer. You might have seen the word integer before in a math class. Programmers call whole numbers integers, and they are a very common in programming.
In the fourth line, we are using my_number differently. The + symbol is not trying to do math with the variable. Instead, we want to treat it like a string. The str( ) command tells the computer to treat whatever is inside the ( ) symbols as a string.
In programming, strings and integers are more generally known as variable data types. Certain pieces of code will only work if the variable you give them is of a certain data type. For instance, the print command only works on strings. Doing math on a string does not make any sense, so math commands want number types like an integer.
You can ask Python to compare one number to another number. To do this there are a set of special symbols. You might recognize some of them from math class.
a > b asks if a is bigger than b
a < b asks if a is smaller than b
a == b asks if a is the same as b
a != b asks if a is not the same as b
a >= b asks if a is bigger than, or the same size as b
a <= b asks if a is smaller than, or the same size as b
Note that == compares if the numbers are the same size. That is because we have already used the = symbol to assign values. We have to use different symbols so the computer knows if we want to compare values or assign a value.
The code below introduces a new command: the if statement.
name = input(“What is your name? “)
my_number = input(“Hello ” + name + “, pick a number ”)
my_number = int(my_number) + 1
print(“Your number is “ + str(my_number))
if (my_number > 100):
print(“That’s a big number!”)
We use an if statement when we want to check a condition in a program. In this case, we are checking to see if the number the user entered is bigger than 100. The last line of the code is only run if my_number is actually bigger than 100. Run the program a few times to test different numbers.
Also, your IDE automatically indented the line after the if statement. Python needs to see the indentation so it knows which statement you are conditionally running if the if statement is true.
The code below adds an else to the if statement.
name = input(“What is your name? “)
my_number = input(“Hello ” + name + “, pick a number ”)
my_number = int(my_number) + 1
print(“Your number is “ + str(my_number))
if (my_number > 100):
print(“That’s a big number!”)
else:
print(“That number is too small.”)
In this case, if the number in the my_number variable is greater than 100, it prints “That’s a big number!” Otherwise, the computer will do whatever is in the else condition. In this case, if the number is not greater than 100, it will print “That number is too small.”
By adding else conditions to your programs you give the code a catch-all in case the if condition is not satisfied.
The code below adds one more condition to the if statement. The elif keyword stands for else if.
name = input(“What is your name? “)
my_number = input(“Hello ” + name + “, pick a number ”)
my_number = int(my_number) + 1
print(“Your number is “ + str(my_number))
if (my_number > 100):
print(“That’s a big number!”)
elif (my_number > 50):
print(“That’s a medium sized number.”)
else:
print(“That number is too small.”)
The logic above works like this: if my_number is greater than 100 print “That’s a big number!”, else if the number is greater than 50 print “That’s a medium sized number!”, else print “That number is too small.”
It is important to know that once a condition in an if statement is satisfied it will stop checking the other conditions. In this case, if the number in my_number is 120, it will only check the first condition. If the number is 62, it will check if 62 > 100 (hint: it is not). So, then it will check the second elif condition to see if 62 > 50 (hint: it is) and will stop checking conditions.
This program is going to print out random integers.
from random import randint
rand_number = randint(1,10)
print(“The number is “ + str(rand_number))
The first line of this program is little beyond this simple introduction, so for now we will just treat it as a bit of magic. It allows us to use the randint fragment of code in the second line to generate a number.
The second line uses a randint to generate a random number. In this case, randint(1,10) generates a random number between 1 and 10 and assigns the number to a variable named rand_number. By now, I am sure you know what the last line does. Run the program a few times to verify that it generates a random number. The same number might get generated two times in a row, so you might have to run it multiple times to see the number change.
The code below introduces a really important programming concept called loops.
from random import randint
i = 0
while (i < 3):
rand_number = randint(1,10)
print(“The number is “ + str(rand_number))
i = i + 1
print(“All done.”)
The while statement checks to see if its condition is satisfied. As long as it is satisfied, it will run all the indented code. When it gets to the bottom of the indented code it will jump back up to the while statement again and recheck the condition. It will keep looping through indented code until the condition is NOT satisfied. When the condition is NOT satisfied, it will then skip the indented code and jump to the line after it.
In this example, the while statement checks to see if the variable i is less than 3. Since we set i to 0 in the second line of the code, the while statement will be satisfied and will run the indented code. Notice that the last line of the indented code adds 1 to the value currently stored in i. This will force i to grow each time the indented code is looped through. Eventually when the while statement checks if i is greater than 3, it will be, and then it will skip the indented code and jump the line that prints “All done.”
When you run this program, it should print out three random numbers. Try to alter the program so that it prints out more than 3 random numbers. Try to alter the program so it also prints out the value of the i variable on the same line as the random number.
Python – That is the name of the programming language we have been using in this exercise.
Integrated Development Environment – Programmers almost never use the term spelled out. They almost always just call it an IDE. The IDE is the software we use to write our program. It makes common coding tasks easier.
File Extension – That is the part after the period in a file name. For example, the file extension for HelloWorld.py is py.
The computer looks at the file extension to help tell what kind of file it is.
Variable – A variable is structure in programming that stores a value for later use.
Variable data type – A data type determines what kind of values can be stored in a variable. Certain operations can only be done on certain data types.
String – A variable data type that consists of only characters that intended to be read as text. Strings are usually surrounded by “ “ quote symbols. For example, “Hello world.”
String Concatenation – The term for when you join two or more strings into a single string.
Integer - A variable data type that holds whole numbers and can be used for math. For example, 42.
If statement – An important structure in programming that only runs a portion of code if a certain condition is satisfied.
Looping – An important structure in programming that runs a portion of code repeatedly as long as a certain condition is satisfied.