When you download a version of Python, it usually comes with three or four other programs; we don't need them. The only program we'll be using is the IDLE. So, open that up and let's get things running.
It is a tradition in programming that says that, when you learn a new language, the first program you're going to write must print "Hello, World!" on the screen. It's not necessary, but let's do this, so we can talk about some stuff.
Alright, here is a Python Hello World program:
print "Hello, World!"
[NOTE: Remember when I said that there would be differences in Python 3.0 and newer? If you use a version that is newer than 3.0, when you try to run this program, you will get an error, because they changed the syntax of the print statement to "print("Hello, World!")". Watch out for that.]
As you can see, there is the "print" function, that tells the computer to print what follows in the console, as well as some text, enclosed in quotes (""), which we call a "string" (I will talk more about that in a second).
Now, we can also add comments to the code. Comments are very useful, because they are just notes you leave to yourself or other programmers, and the computer just ignores them. Comments in Python can be added using a hashtag (#). Here is our commented Hello World program:
# prints "Hello, World!" in the console print "Hello, World!"
Now, since we successfully wrote our first Python program, let's talk about variables and data types.
The definition of a variable in programming is very close to that one you learned in school. I like to think of a variable as an empty box, which can store one value. Later on in our program, we can change its value, but first we must declare it:
x = 0
There are some things you must watch out for when declaring a variable. First and foremost, you cannot use any keywords reserved by Python (for example, you cannot have a variable named "print", because print is a function of Python). You also cannot have a variable that begins with a number. A safe way to name a variable, is to think of a name that starts with a letter of the alphabet, contains letters of the alphabet, "_" and numbers ONLY. If your variable name consists of two words, there are many ways to declare it. For example: "myVar", "my_var". Also, keep in mind that Python is a case-sensitive language. That means that "myVar", "Myvar" and "MyVar" are all different variables.
But there are many data types a variable can support:
- An integer (..., -3, -2, -1, 0, 1, 2, 3, ...)
- A float (A floating point decimal number, like 3.2810378)
- A character (A single letter, like "e")
- A string (A sequence of letters, like "Hello, World!")
There are also built-in functions that can be used to change a data type to another, if possible. For example, test these:
print int(3.7) print int(3.1) x = 5.282719 x = int(x) print x # many people suggest that you should turn your numbers into # strings if you plan to just print them print str(0)