Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

[Python] Getting Started

Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
Getting Started with the Python Programming Language

(Updated to fit the 2.x AND the 3.x series of Python.)

I'd like to start by saying Python is the simplest, most straight-forward language I've ever coded in. Though the syntax varies a lot from other languages, it's pretty easy to get started on. With that said, I'd like to share with you this tutorial for getting started with Python.

Some links to get you started:
The Python Website:


"How To Think Like a Computer Scientist: Using Python 2nd Edition"

The first step is to visit and download python for your operating system. It works on all of them.

The Beauty of Python
Python is cross-Operating System (OS) compliant. Meaning it works on Mac, Linux and Windows. Python is Open Source, and the documentation is simply fantastic. The Python syntax is simple and easy to follow. Many keywords are left out of the syntax to make code MUCH smaller than other languages. Python specializes in Object Oriented Programming (OOP) and Functional Programming.

The IDE
Python is a scripting language and uses an Integrated Development Environment (IDE) for developing the scripts. When you install Python, you'll get IDLE. I'll be coding in Python 2.6. Python uses various libraries, but the basics can be done without importing any extra libraries. I'll try to keep to the basics in this tutorial, using no libraries at all. I do suggest getting GASP (a graphics library built for learning how to create GUI applications in Python).


Why Python?

I chose Python because of the simple syntax, and because other languages made simple tasks complex whereas Python did not. For example, to print text to the screen in C++, you would need to use code like this:
Code:
#include <iostream.h>
void main()
{
        cout << "Hello, world." << endl;
}
In Python it's as simple as this:
(Python 2.x)
Code:
print "Hello, World."
(Python 3.x)
Code:
print("Hello, World.")
As a teacher to a beginner programmer, explaining how to print text includes explaining what a library is, what void means, why/when to use main(), what a code block is, the syntax and use of cout, and how to format a line (ending with a semicolon.) At that point, most beginners get lost, give up, or might even decide to do something other than programming.

In Python it's much simpler. I'll explain what a line is, what print means and why we use quotes around text (or a string).

(Rephrased from "How To Think Like a Computer Scientist: Using Python 2nd Edition"
)

In Programming, each line holds information to be interpreted by either an IDE or compiler. The IDE/Compiler will go through your program, one line at a time, and reword it in binary so the computer can understand it. Python is a high-level language. As is C++ and Java. Binary is a low level language. High Level languages are written and understood by humans. Low Level languages are understood (and usually translated from higher level languages) by computers. Low level languages are quicker, whereas high level languages are easier to code by humans. In programming, there's always a trade-off from developer-friendliness to efficiency. We all want our programs to functions as quickly as possible. However, we don't want to spend hours typing at the keyboard 0s and 1s. It's much quicker to code using high-level techniques. Development time vs Efficiency is a constant battle for every programmer (and should be). We'll get more into this later.

Open IDLE, It's Time to Code Your First Program with Python
As you may have tried already, to let the program spit out text, we type the keyword: print

(Python 2.x)
Code:
print "Hello, World."
(Python 3.x)
Code:
print("Hello, World.")
IDLE should have something like this:
Code:
>>> print("Hello, World.")
Hello, World.
Have you ever heard the term, RAM? The RAM is a temporary storage system. Programs use the RAM to store data used in your applications. A Variable is for storing data on the RAM. The text "Hello, World." is a string. "H" is a character. A string is made up of characters. An Integer (int) is a number. A float is a number with a decimal. Integers cannot have decimals. Take a moment to understand this paragraph before moving on.

To create a variable in python, you should think of a clever name for the purpose of the data stored in the variable.

I'm going to call this variable greeting, because it's used to greet the person who uses this program. The equals sign (=) is used to separate the variable's name from the value it holds. A variable's value can be changed, the name cannot. Later I'll explain how we can create two variables with the same place on the RAM in Python. (Which is essentially like having a variable with two names).

Here is a string in python:
Code:
greeting = "Hello, World."
You can see the value of greeting by doing this:
Code:
greeting
The IDE should have something like this:
Code:
>>> greeting = "Hello, World."
>>> greeting
'Hello, World.'
Exercise: See what happens when you use print on greeting. How does it differ from simply typing greeting?

Here are two ways to create strings in Python: You can use quotes (") or apostrophes ('). I'll from here-on be referring to apostrophes as single-quotes (') when used for strings.

If your string contains quotes you should use single-quotes. If your string contains apostrophes you should use quotes.

What happens if you need to use both quotes and apostrophes in the same string?

Concatenation is a term we use to define the combination of values (which can be a string, int, float, and more). To concatenate (combine) two values, we use the plus (+) sign. Note that to concatenate values, they must be the same type. There is a way to change the type of a value- we'll get into that later.

Let's say we want to create a variable to store this:
Jerry says, "Brain's shoes are untied."
Though there are other ways to store strings than just quotes and single-quotes (such as triple-quotes ["""]), we can do this with quotes and single-quotes anyway using concatenation.
(python 2.x)
Code:
concatenated_string = 'Jerry says, "Brian'+"'s shoes are untied."+'"'
print concatenated_string
(python 3.x)
Code:
concatenated_string = 'Jerry says, "Brian'+"'s shoes are untied."+'"'
print(concatenated_string)
Integers

To create an Integer in Python, we don't need to (and cannot) use any kind quotes.

Here is an integer stored inside a variable:
Code:
integer = 3568478
Integers don't differ when you use the print command, and when you just type the variable name.

Notice the lack of commas in this number. The computer doesn't use commas for readability purposes like humans do. In fact, the computer would interpret this much differently if it had commas.
(See what happens when you print an integer with commas. Is it different than what you expected?)

Instead of seeing 3 million, 6 hundred and 84 thousand, 4 hundred and 78, the computer would see a [ame="http://en.wikipedia.org/wiki/Tuple"]tuple[/ame] of three different numbers:
3, 684, and 478

This is referred to as a tuple in Python. A tuple is just as it says. You can store a tuple in a variable like so:
Code:
a_tuple = (123, 456, 789)
Tuples (like integers) don't differ when you use print on them, or just type the variable name:
(python 2.x)
Code:
>>> a_tuple
(123, 456, 789)
>>> print a_tuple
(123, 456, 789)
(python 3.x)
Code:
>>> a_tuple
(123, 456, 789)
>>> print(a_tuple)
(123, 456, 789)
You can print one of the three values in a tuple by using the index number:
Code:
>>> a_tuple[1]
456
Create a variable named b_tuple, and store the strings "hi", "hello", and "hey" in it.
Code:
b_tuple = ("hi",'hello',"hey")
Then type these four lines:
Code:
b_tuple
(python 2.x)
Code:
print b_tuple
(python 3.x)
Code:
print(b_tuple)
Code:
b_tuple[1]
(python 2.x)
Code:
print b_tuple[1]
(python 3.x)
Code:
print(b_tuple[1])
Did it come out as you expected?

You might be wondering why the [1] doesn't call the first value in the tuple. That's because the computer starts counting from 0 (and for good reason). If it weren't for the number 0, the world wouldn't be as advanced in math (not even close), and there likely wouldn't be computers.. Not even a slide-rule. We can all thank the ancient Babylonians for first understanding the importance of 0, and put utterly clearly when the Arabs created the [ame="http://en.wikipedia.org/wiki/Abacus"]Abacus[/ame]. (A base-10 Abacus with 10 rows can calculate numbers ranging into the billions! - From "Programming the Universe" By Seth Lloyd.)

See what happens when print b_tuple[-1].

Now see what happens when you print b_tuple[3].

In Python, if you count backwards, you can print from the last index in a tuple. You cannot, however, print an index that doesn't exist. There is no value for the index of 3, therefore, you cannot summon it.

See what happens when you print b_tuple[-4].

Printing All Of The Values in a Tuple
To print all of the values in a tuple, you don't have to print each one individually line-by-line. Python has an easier way for us to loop through our tuple, and print each value.

Before we can do that, though, let's learn a couple new keywords. For and in are used in harmony with each other in the Python Programming Language. The syntax is like so:
for variable in tuple:
#line of code here
(Note: The use of # is a code comment. Anything after a # sign will not be interpreted by the IDE/Compiler)

The for keyword tells the IDE that a loop is coming up. The italicized variable indicates a temporary variable will be declared for each index inside the tuple. In refers to inside the. The tuple is where the tuple goes. The colon at the end of the line indicates a block of code is going to be used. In Python, a code block starts after a colon, continues for each evenly spaced tab, and ends when the tabs go away.

This code will print each value inside a tuple:
(python 2.x)
Code:
for x in b_tuple:
        print x
(python 3.x)
Code:
for x in b_tuple:
        print(x)
When you type "for x in b_tuple:" within IDLE and press enter, you'll notice the tab is done for you. You can type a line of code (such as print x), and press enter again to start coding a new line within the loop. Once you press enter twice without typing anything, IDLE will execute the loop.

Unlike some other languages, x is declared in the scope of __main__. What that means is, x is now officially declared and usable by your application anywhere after the point it was used in the loop. Try coding this after the loop has finished:
Code:
print x
Notice it prints the last instance in the tuple. (Which is "Hey", in my case.).

That's because it's the last value that was assigned to x.

Lists and the Range Function
A list is a little different than a tuple, but is mostly the same.

One difference is, you cannot change the value of an item within a tuple like this:
Code:
tuple_b[1] = "Hola"
You get an error message.

Another difference is in the way lists are created. Instead of parenthesis (), we use brackets [].

Create a list named a_list, like so:
Code:
a_list = ["Hello",'Hi',"Hey"]
Go ahead and print the list. It's just like a tuple, but with brackets.

Notice you can do all the same things with lists you can with tuples, and more.

Code this now:
Code:
a_list[1] = "Hola!"
Now print the list.
Is it as you expected?

The range is a span between two integers. In Python 2.x, it will return a list between (a) and (b).

Code This:
Code:
range(10)
In Python 2.x, it will show:
[0,1,2,3,4,5,6,7,8,9]

In Python 3.x, it will show:
range(0, 10)

To print each of those numbers, you can code this:
python 2.x
Code:
for i in range(10):
        print i
python 3.x
Code:
for i in range(10):
        print(i)
Range takes two arguments. The first is optional (meaning you only need 1 item in the parenthesis to make a range. The default to argument 1 is 0. Thus, if only the integer 10 is placed in the parenthesis, the range is 0 to 10.. Not including 10). You can create a list from 20-50 by coding it like this:
(python 2.x)
Code:
range(20,50)
(python 3.x)
Code:
list(range(20,50))
See what it does. Did it perform as expected?

For practice, create a variable to store the list generated from a range. Use a loop to cycle through that list.

Now let's convert a tuple into a list. To do that, we use the list function:
Code:
list_b = list(tuple_b)
Go ahead, print out list_b.

We can also convert lists to tuples.

Now try this:
Code:
list_b[1] = "Hola!"
tuple_b = tuple(list_b)
Print out tuple_b.

Try to explain to yourself what just happened. Did the previously unknown function tuple() do exactly as you expected? Is it possible to change the value of an item within a tuple? Actually, it's not. It is possible to change a value in a list, and it's possible to convert tuples to lists, and back.

Therefore, we can create a function for changing a value in a tuple. We'll get into that in a later tutorial. What I will tell you, is that functions hold blocks of code that you can call later on (even multiple times) in your scripts.

Now that you get the gist of Python, explore the web to find out what more you can do with python!

one last exercise: (Creating a simple function)
(python 2.x)
Code:
def Greeting():
        print "Hello, World!"
(python 3.x)
Code:
def Greeting():
        print("Hello, World!")
def means we're defining a function. Greeting is the name of the function. (It doesn't have to be capitalized.) The colon (Like the for loop) tells Python a code block is coming up. Notice the tab, too. You know what print does.

This is how you call the Greeting function:
Code:
Greeting()
Here is a function called echo:
(python 2.x)
Code:
def echo(something):
        print something
(python 3.x)
Code:
def echo(something):
        print(something)
something is only seen in the scope of the echo function. If you try to call "something" after you call echo, you'll get an error unless you created the variable somewhere else (More specifically, in the scope of where you call it).

When you call the function, "echo", you must pass to it in the parenthesis something to be used for the variable something. That something can either be any type of value. It can be given by a variable, or simply by a string in quotes. (Or an integer, list, tuple, and more). Some functions are strict and need a specific type. Since we're only using the print command, any type can be passed to it. Other procedures are more delicate than print, as you might expect.

Here is how you use it:
Code:
greeting = "Hello, World."
echo(greeting)
echo("Goodbye, World.")
As an exercise, create a function that takes a list/tuple as an argument, and prints each value of it. What happens when you pass a string as an argument?
Did it do what you expected? Explain.

Answer:
(Python 2.x)
Code:
def loop_through(List):
        for x in List:
                print x
loop_through(range(10))
loop_through("Hello, World!")
(Python 3.x)
Code:
def loop_through(List):
        for x in List:
                print(x)
loop_through(range(10))
loop_through("Hello, World!")

Enjoy! :thumbup:
 
Last edited:
Zzzz...
Loyal Member
Joined
Dec 26, 2008
Messages
781
Reaction score
225
I've always thought python was some mystic 3d engine language xD I guess I'll start learning as I have to use blender and stuff now for my game. Will check this out later, thanks :D
 
Newbie Spellweaver
Joined
Jul 2, 2010
Messages
17
Reaction score
4
I didn't read all of it, just a bit at the beginning. It so far reminds me of Ruby.

Anyway, good job. I will have to finish some time.
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
Not when the examples I give work on all later versions.....

If I get in depth with more libraries and such, I'll move onto those versions. ATM this one is faster and serves the purpose fine.

I wish I learned Latin first instead of English, anyway.
 
Ginger by design.
Loyal Member
Joined
Feb 15, 2007
Messages
2,340
Reaction score
653
Not when the examples I give work on all later versions.....

If I get in depth with more libraries and such, I'll move onto those versions. ATM this one is faster and serves the purpose fine.

I wish I learned Latin first instead of English, anyway.

Code:
print "hello world."

Will not work in Python 3.1. There are other major differences too.
 
Joined
Apr 18, 2010
Messages
674
Reaction score
393
I chose Python because of the simple syntax, and because other languages made simple tasks complex whereas Python did not. For example, to print text to the screen in C++, you would need to use code like this:
Code:
#include <iostream.h>
void main()
{
        cout << "Hello, world." << endl;
}

Um.... I'm scared to finish reading the rest of this tutorial. D;
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
I know this isn't a C++ tutorial, but you forgot
using namespace std;

or

using std::cout;
using std::endl;
It's not a C++ Tutorial.

Python has a default library for normal things such as I/O, typical list/tuple/dictionary features, logical comparisons and math.

There are libraries for python, for use with special string features, advanced arithmetic features, and for just about anything else you can think of to make programming easier (time features, random, etc).

For simple programs, you really don't need to import additional libraries with Python.
 
Last edited:
Experienced Elementalist
Joined
Mar 26, 2008
Messages
235
Reaction score
1
thanks for this. might try it out later.
 
Back
Top