- So, what is programming anyway?
- Getting Started with Python Programming
Getting Started with Python Programming
Let’s play with Python!
Printing and Variables
Go to your shell (the one with three angled brackets), and type the following.
print 'Hello, world!'
Press enter, and note what happens. Python should spit back ‘Hello, world!’, but without the quotes. You’ve just written your first line of Python. print is a keyword that tells Python to print something to the screen, and the words in quotes are a string, which is just some text.
You can save for later use and reuse by storing it into a variable. You do that by typing:
>>> greeting = "Hello, world!"
Note that nothing was spit out when you hit enter. That’s because all Python did was store the value of ‘Hello, world!’ into the variable greeting.
Now that you have your value stored, you can print it!
>>> print greeting
That should print out the following (remember in this context, print means show on screen):
Hello, world!
If you want to save this code and run that (just in case you feel like greeting the world later), open up a new file in IDLE and enter the following:
greeting = "Hello, world!" print greeting
Save it as ‘hello.py’ (File > Save), and then run it either by using the Run menu, or by pressing F5. You should see the greeting print out in the shell!
What Can You Store?
You can store all kinds of data in Python, but here are some of the most basic types:
- Whole numbers (integers)
- Decimal numbers (floats)
- Text (strings)
- Lists (just what it says — a list of things)
Let’s talk about numbers first.
Numbers
You have already seen how to store text. Let’s store a number! In your interpreter, enter the following:
>>> x = 5 >>> print x
Five should be printed out! The data type we’ve stored in x is an integer (a whole number). If you want more precision, you can store a float:
>>> y = 1.5
As soon as you add a decimal to a number, that value is now a float. You can even make a ‘whole’ number a float by adding a .0 to the end:
>>> x = 5.0
Math
Now that you know how to store variables, let’s try some math!
Math in Python looks pretty close to math in the real world.
Operation |
Operator |
Example |
Addition |
+ |
5 + 5 |
Subtraction |
- |
5 - 2 |
Multiplication |
* |
2 * 4 |
Division |
/ |
6 / 2 |
Open up your interpreter and try the following:
>>> x = 5 >>> print x * x
You should get 25, because five times five is 25. Try entering the following:
>>> print "Hello " * 5
At first, you might think that wouldn’t work (it would have gotten me kicked out of algebra for certain). But you get five hellos!
Lists
To create a list, use square brackets around a series of items:
>>> ages = [5, 12, 33, 46] >>> pets = ['Coe', 'Gizmo']
To get an item out of a list, you need to give Python the index number of the list. The index number is simply that item’s place in line. It’s important to remember that Python (and most programming languages) start counting at zero. So, the first item in the list is at index zero, the second is at index one, and so on.
Go ahead and enter the above lists into your interpreter, then try the following commands:
>>> print ages[0] >>> print pets[1]
Note that the items in that index are printed out. What if you want to add an item to a list? You use the append method. Let’s add a pet to the list of pets. Type the following in your interpreter.
>>> pets.append('Niko')
Now, check to see what’s in the list. Enter this:
>>> pets
You now have three pets! Niko has been added to the end of the pets list.
Dictionaries
Dictionaries are a special kind of data type that can be incredibly useful when programming. A dictionary you keep on a shelf is filled with pairs of words and definitions. A dictionary in Python is filled with pairs of keys and values.
Open up a new file and enter the following code:
pets = {'Niko': 'cat', 'Gizmo': 'dog', 'Coe': 'fish', 'Boxo': 'dog'} print pets
Save the file as petdict.py and run it. Note what was printed out. You have paired each pet name with its species. The name is the key, and the species is the value.
If you want to get one value out of a dictionary, you give the dictionary the corresponding key. Try adding this line to the end of your code.
print pets['Boxo']
What was printed out? You should see this in your shell:
>>> dog >>>
If you want to add a value to the dictionary, give the dictionary a new key, and set the value. Change your file to look like this:
pets = {'Niko': 'cat', 'Gizmo': 'dog', 'Coe': 'fish', 'Boxo': 'dog'} pets['Ren'] = 'finch' print pets
Save the file and run it. Note what was printed out. Now, the dictionary has a bird in it!
Note that we have two dogs in our dictionary. That’s okay! Values aren’t unique. Keys are, though. Watch what happens if we change the value of Coe to be a bit more specific:
pets = {'Niko': 'cat', 'Gizmo': 'dog', 'Coe': 'fish', 'Boxo': 'dog'} pets['Coe'] = 'betta' print pets
The value associated with Coe was changed. We didn’t get a second entry for Coe. This is what should appear in your shell:
>>> betta >>>
Logic and If Statements
Storing information is all well and good, but programming also involves logic. Sometimes we want to do something only if something is true. Other times, you may want to do something a certain number of times.
Let’s say you only want a block of code to run if you have a certain number of apples. First, you’re going to need to see how many apples you have. To do this, you’re going to need to learn some new operators. These are used to compare one item against another. The following table describes the typical logic statements.
Operation |
Operator |
Example |
Equal to |
== |
5 == 5 |
Not equal to |
!= |
5 != 6 |
Greater than |
> |
6 > 2 |
Greater than or equal to |
>= |
4 >= 4 |
Less than |
< |
4 < 7 |
Less than or equal to |
<= |
4 <= 4 |
Each of these expressions (some values and an operator used together) will return either True or False. Try these out in your interpreter:
>>> 5 == 6 >>> 5 != 6 >>> 4 > 4 >>> 4 <= 4
What did you get back?
You can use these expressions with an if statement so that you can have some code execute only if something is true. Open a file and enter the following:
apples = 5 if apples > 5: print "You have a bunch of apples!"
Save the file as apples.py.
Note the spaces before the print statement. IDLE should put those spaces in there for you, but if not, go ahead and put four spaces in before the print statement. That creates a block of code. Python will only run this block of code if you have more than five apples. If you didn't have these spaces here, Python wouldn't know what you wanted to do if you happened to have more than five apples.
Go ahead and run the file! Nothing should appear to happen. That’s because you have five apples, so nothing is printed. Try changing apples to six. Your code should look like this:
apples = 6 if apples > 5: print "You have a bunch of apples!"
Save the file and run it. This time, some text should be printed out!
For Loops
Sometimes, you want to run a block of code a certain number of times. The most common use case is running a block of code for every item in a list. To do this, use a for loop.
nums = [1, 3, 5, 6, 9] for num in nums: print num print "Hi " * num
Save it as hi.py and run the file. What is printed out?
Basically, a for loop starts at the first item in a list and saves that value into a loop variable. For the loop in hi.py, that’s 'num’. Once the block of code is done, Python moves onto the next value in the list, saves that into the loop variable, and runs the block of code again.
Functions
Sometimes, you want to save a bit of functionality so you can call it later. This is when functions are useful. Open up a new file, and enter the following code:
def say_hi(): print "Hello, there"
Save it as sayhi.py, then run it. Nothing should appear to happen, because what you need to do is call the function. Now, add a line to your file.
def say_hi(): print "Hello, there" say_hi()
Save it and run it. Now what happens? Python should greet you!
You can also pass values into functions. To do this, you need to add some parameters. When you add parameters, the value you send is stored in the parameter, and you can use it within the function. Let’s add one!
Open your file, and change the code like so:
def say_hi(name): print "Hello," name say_hi('Joe')
Save the file and run it. This time, Joe should be greeted.
You can also give parameters a default value when you define them. Change your file to look like this:
def say_hi(name='person'): print "Hello," name say_hi('Joe') say_hi()
Now, Joe and a random person will be greeted!
User Input
Sometimes, you want to get input from the user. Let’s go over two ways to do that: input() and raw_input().
You can use input() to get a number from a user. Open up your interpreter and try the following:
>>> num = input('Give me a number: ')
You should get a prompt, asking for a number. Enter a number, then print out num:
Give me a number: 5 >>> print num
You should see your number there!
What if you don’t want a number, though? Then, you should use raw_input. This function will save whatever the user enters as a string.
>>> name = raw_input('Your name: ') Your name: Katie >>> print name Katie
So, input() should be used for getting literal values, like numbers, and raw_input() should be used when you want to save exactly what the user entered as a string.
New Functionality
You can also bring new functionality into your program. Python comes with a large standard library that allows you to do so much more with your program with only a few extra lines of code.
I’ll just go over one module (that’s a part of a library) for now: random. Random is a great module for generating random numbers. To use random, you’ll need to import it. Open up your interpreter and enter the following:
>>> import random >>> random.random()
What is printed out? It should be a float between one and zero. Go ahead and type out random.random() a few times, and see what is printed.
You can also import just the functionality you want from a module. Type this into your interpreter.
>>> from random import randint >>> randint(10)
What was printed out? It should be a random number between zero and ten.
Random is hardly the only module available. For other available modules, check out the official documentation, or get a hold of Doug Hellmann’s book The Python Standard Library by Example.
Guessing Game, Redux
Now that you’ve been exposed to a bit of programming, let’s take another stab at our guessing game. Here’s a souped up version:
from random import randint secret = randint(10) guess = secret - 1 while guess != secret: guess = input("Give me a guess: ") if guess > secret: print "Sorry, that's too high!" if guess < secret: print "Sorry, that's too low." if guess == secret: print "That's right!"
With just a few lines of code, you have made the program much more robust! Run it, and see if you can follow what it does.
Learning More
This is just meant as an introduction to what Python and programming can do for you. However, as you can see, just knowing a few concepts can make something functional. It doesn’t take much code to make something cool, or to make your life easier.
If you’d like to learn more, I wrote a book geared towards the absolute beginner (Teach Yourself Python in 24 Hours) and a video training course as well (Python Guide for the Total Beginner LiveLessons). In it, I start at installation and go all the way up to making websites and games in Python. You should also check out Doug Hellmann’s book to learn more about the standard Python library. Finally, there is a mountain of documentation at the official Python site, including a tutorial to get you started!