chevron_left chevron_right
Login Register invert_colors photo_library


Stay updated and chat with others! - Join the Discord!
Thread Rating:
  • 0 Vote(s) - 0 Average


Tutorial - Fundamentals of Python 2.6 filter_list
Author
Message
Tutorial - Fundamentals of Python 2.6 #1
Spoiler:
Quote:I am Headrush and I have been learning Python for a few weeks now, I am very happy with Python and I wish to continue to learn it. I like making tutorials for programming because it helps people learning the language, but it also helps me. This tutorial is mainly on Linux, it should work fine on Windows though. Everything that is in italics will be in definitions at the end of the section.

Tutorial Components:

Introduction:
Python Description
Why Python
Could Python Get Me a Job
Definitions

Windows:
Installing Python
Choosing an IDE
Creating your first script
Running your first script
Definitions

Linux:
Installing Python
Choosing an IDE
Creating your first script
Running your first script
Definitions

Programming:
How to Import Modules
Time Module
Comments
Variables
User Input
Logical Operators
If, Else, Elif
While Loop
Creating a Basic Calculator

Helpful Resources:
Python 2.6 Documentation
A Byte of Python


Introduction:


Python Description:

Python is a scripting language, meaning that it does not need to be compiled. Python works on almost all OS. Pythons’ syntax is all about tidiness and legibility, this is because of whitespace.

Why Python:

Python is a very wise choice for programming because it is a fairly easy language to learn, yet so powerful and useful. Python code is also very easy to read this is important because if you make a mistake you can easily see where it is, also if you are programming with someone else they can easily pick up where you left off. If you are going to learn a language such as Perl, you will notice that if you are looking at someone else’s source code it gets very confusing unless they are commenting there code. In Python it is good to comment the code but if you don’t it is a lot easier to read and understand what is going on then many other languages.

Could Python Get Me a Job:

Yes, many people and corporations need Python programmers. Python is a language this is used very much in the world today. Here is a list of companies and applications that use Python.

Applications: BitTorrent, Deluge, Emesene, Portage, Quake Army Knife, and many more

Games: Civilization 4, Battlefield 2, Eve Online. Freedom Force, Frets on Fire, The Temple of Elemental Evil, Vampire: The Masquerade - Bloodlines, Vegas Strike.

Companies: Blizzard, Firaxis Games, Google, Nasa, and many more.

Definitions for Introduction:

Syntax: is how the programming language is structured and what rules apply for it. For example in Python when you indent something it has to be 4 spaces or else you get a syntax error.

Whitespace: is basically anything that you do that involves the tab key and the enter key.

Comments: is a symbol that you use to skip a selection of information from the interpreter or compiler.



Windows:


Installing Python:

Installing Python on Windows is an extremely easy process. Go to this site
python.org, if you have a 32-bit operating system then download Windows x86 MSI Installer. If you have a 64-bit operating system download Windows x86-64 MSI Installer. Then just run the .exe and follow the install. then you have Python on your computer.

Choosing an IDE:

Choosing an IDE is very important for any programming language, but it is not absolutely necessary. You could programming in notepad but I recommend you don’t because there is no syntax highlighting and it would just get irritating. Two IDEs that I recommend are Notepad++ or Eclipse.

Notepad++: If you decide to download Notepad++ then you have to of course first install it. Here is the download link: Notepad++. Then you run the .exe and install it. To change the syntax highlighting to Python go to Language > P > Python now notepad++ has changed the syntax to Python.

Eclipse: If you decide to download Eclipse, you need some other stuff to make Eclipse work. I recommend following these two guides. How to Install Eclipse and How to Setup Python on Eclipse.
Once you have Eclipse up and running you have to go the Update Manager > Help > New Software and add http://pydev.org/updates/ in the Work with textbox, then click Add. Then select PyDev and PyDev Mylyn Intergration (optional). Then click Next, wait until the progress bar fills up and then you will go to Install Details, click Next. You will go to Review Licenses click on the I accept the terms of the license agreements, click Finish. Then finish the installation and restart Eclipse. You still have to add the Python Interpreter, since I am on Linux I recommend you follow this guide. Setting up PyDev

Creating your First script:

For the sake of less errors (because I am on Linux), I am going to tell you how to make your first script in Notepad++. You can use IDE you want it doesn't really make a difference, it is just prefernce.When you first start your script you want to add the shebang line.

Code:
#!/usr/bin/python

The importance of the shebang line is that it tells the script where the interpreter is located.

Code:
print "This is HeadRushs' Python 2.6 tutorial."

This line of code print "This is HeadRushs' Python 2.6 tutorial." displays the text within the quotations to your script. If you just wrote "This is HeadRushs' Python 2.6 tutorial" it would not work because you didn't write print or include the quotations.

Running Your Script:

Now you have your first script, it will display This is HeadRushs' Python 2.6 tutorial. Now save the script as hello.py. Now if you double click on the script there should be a window that pops-up, it should like Command Prompt. It will open up for a second and close that is okay we will fix that later.

Definitions:

Interpreter: changes the source code into another code and executes the new code. In Python the source code gets translated into bytecode.



Linux:


Installing Python:

Most distros come with Python 2.6 already installed, if you don't have Python 2.6 installed on your distro just type this.

Code:
(root) (package manager) (install code) python

For example if you run Linux Mint, you will write in something like this.

Code:
sudo apt-get install python

As you can see sudo gets you in to root, apt-get is the package manager, the install code is install, and I wrote in python at the end because we are installing Python.

Choosing an IDE:

Choosing an IDE is a very important no matter what language you are programming in. In my opinion setting up an IDE for Python in Linux is a lot easier than in Windows. I am going to recommend the two following IDEs to program in Python, gedit or Geany.

gedit: If you decide to use gedit you need to download it, here is the download link. gedit Now of course you have to install gedit. Once you have gedit installed you want to change a few things to make it more ideal for Python. Now you have to go the Statusbar and click on Plain Text > Python. Now since that standard indentation in Python is 4 spaces change the Tab Width to 4. Now you are ready to use gedit as a Python IDE.

Geany: I personally love this IDE, the best part of it is the built-in terminal so you can test your scripts from the IDE. If you decide to use Geany, here is the download link. Geany The one thing that you will realize right away, is that it doesn't automatically highlight the syntax. So the first thing I always do is Save As right away, and name your script whatever.py. Now the IDE will use the Python syntax. You are now ready to program in Python.

Creating Your Script:

The IDE I am going to be using is Geany, you can use whatever IDE you want it doesn't make a difference, it is just preference. I prefer Geany so I am going to be using it. The first line of your script needs to be the shebang line.

Code:
#!/usr/bin/python

The importance of the shebang line is that it tells the script where the interpreter is located.

Code:
print "This is HeadRushs' Python 2.6 tutorial."

This code print "This is HeadRushs' Python 2.6 tutorial." displays the text in quotations, in this case it displays This is HeadRushs' Python 2.6 tutorial. The text would not be displayed without print or the quotations.

Running Your Script:

In Linux running a script is easy, all you have to do is write python and the location to your script into terminal. If your script was named whatever.py and on the Desktop you would write.

Code:
python Desktop/whatever.py

You will see that in terminal it displays This is HeadRushs' Python 2.6 tutorial.

Definitions:

Interpreter: changes the source code into another code and executes the new code. In Python the source code gets translated into bytecode.

Programming:


How to import modules:

Importing modules is important in any programming language, especially Python because you can only do so much in Python without importing modules. If you are using Windows you almost can't do anything without importing modules, there is a module to make the Command Prompt like screen stay open while just printing text. Now we will get to importing modules, to import a module you simply have to write import and your desired module you would like to import. For example we will important an import module, the time module. That module is especially important for Windows users.

Code:
import time

That is all you have to do to import a module. If you want to give the module a name besides its default name then you can do it by writing this.

Code:
import time as t

Now as you can see time is know to the script as t, and if you want to use the module it has to be called t not time.

Time Module:
The time module is used to stop the programming for a certain amount of time. On Windows if you don't use the time module the only time that the script will stop without closing right away is if you are asking for user input. So for Windows users and also Linux users time is an important module and in my opinion is the most important module. To use the time module all you have to do is write sleep(and number of seconds you want the script to stop for). Here is an example of the time module code needed for making the script stop.

Code:
time.sleep(3)

As you can see I want the script for 3 seconds so I put 3 in the brackets.

Comments:

Comments are used to show people what your code is doing and what it means, they are also used for adding information about programmer, and anything else the programmer wants to add in. Comments just get skipped by the interpreter. The two comments I will be showing are inline comments and documentation strings.

Inline Comments: are just supposed to be used at the end of the code to explain what it is doing, although you could use it for anything you want. Here is an example of an inline comment.

Code:
#!/usr/bin/python
print "Hello World" #this is an inline comment, as you can see it won't show up on your script

Documentation Strings:
are just strings that you can fit lots of information in, like if you are trying to explain what your if statement is doing exactly than it would be easier using documentation strings rather than comments. Here is an example a documentation string.

Code:
#!/usr/bin/python
"""This is my documentation string
as you can see this will not show up on our script
now I want to end the documentation string
"""
print "Hello World"


Variables:

Variables are just data types that store information, there are a couple different kinds of variables that we will be going through in this tutorial. Some of these variables are integer and float. Variables are very important in any programming language because they hold information that the programmer might enter or information that the user might enter. First we will go over integer.

integer: is referred to in python as int. Integers hold numbers that don't have decimal numbers and also hold integers, they can hold decimal numbers but float is recommend for holding decimal numbers. Here is an example of a script with integers in it.

Code:
#!/usr/bin/python
x = 5
print x

As you can see in this script we declare x (is by default an int) as 5. Then we print out x, and we get the output 5.

Next we are going to go over float, with float you can hold large decimal numbers. Float is a very good variable to use if you are making a script with math in it. Here is an example of a script with integers in it.

Code:
#!/usr/bin/python
x = float(5.534)
print x

As you can see we declare x as float 5.534, we have to put float(5.534) because that means 5.534 is now a float variable.

Now string, string is a lot more complicated than float and integers because you have to use it with float and integers sometimes. A string is basically text that has been stored, it can also be numbers. We are going to go over how to put text in a string, then we will put what we learned all together.

Code:
#!/usr/bin/python
x = str("HeadRush")
print x

As you can see x is now been declared as a string(str). You have to put your text in quotations within the brackets for the text to be declared as a string.

Now lets put everything we know together.

Code:
#!/usr/bin/python
import time
age = 15
height = float(5.8)
hr = str("Headrush")
print hr + " is " + str(age) + " years old and is " + str(height) + " feet tall."
time.sleep(3)

So we should be able to understand everything to this point except this line of code: print hr + " is " + str(age) + " years old and is " + str(height) + " feet tall.". We will break down this code first you we will look at this part print hr + " is ". So we print out the variable hr, and when you are mixing a variable with a print statement it has be a string so we put str(variable) but since we did that we don't have to worry about it. We add + (or you could use a ,) because we are adding more stuff to the print statement and then " is " prints out is. Next we will look at str(age). We have to put str(age) because age is a variable with a number and is not a string and you can not mix a variable with the print statement at has to be a string so we convert it to a string. All the rest of the code should not be self explanatory.

User Input:

User input is extremely easy in Python, but none the less it's very important. User input is important because if you make any script you almost need user input no matter what kind of script you make. Here is an example of user input in a script.

Code:
#!/usr/bin/python
import time
yourName = str(raw_input("What is your name: "))
print "Hello " + yourName + "!"
time.sleep(2)

We are just going to over this yourName = str(raw_input("What is your name: ")). So, we see that we call str(raw_input("What is your name: ")) yourName. So we declare everything inside of the str(raw_input("What is your name: ")) as a string. Next you see raw_input this is what allows the user to input information, next we see a bracket ( because everything inside of this bracket is text to say what we want from the user. Now we close both brackets and we have the code for the user to input information and it is a string.

Logical Operators:

Logical operators are just operators to compare or modify information, in this tutorial we will just cover the basic operators times (*), add (+), and divide (/). Here is a script with each of the operators in it.

Code:
#!/usr/bin/python
import time
times = 2 * 2
add = 1 + 1
divide = 9 / 3
print times, add, divide
time.sleep(2)

This is pretty self explanatory, although instead of using time + add + divide we use a comma because if we didn't do that we would all the variables together.

If, Elif, Else:

This is probably one of the most important things to know in programming because we compare information and we make sure the person using are script does not get errors and the script closes on them automatically. The most important thing about if, elif, and else statements is they require indents it is like having { in any other language, so they have to be separated from the rest of the code by indenting 4 spaces. Here is an example of a script with if, elif, and else in it.

Code:
#!/usr/bin/python
import time
yourName = str(raw_input("Please enter your name: "))
if yourName == "HeadRush":
    print "You are making this tutorial!"
    time.sleep(2)

elif yourName == "Nyx-":
    print "You are an anime master"
    time.sleep(2)

else:
    print "Oh welcome to this script."
    time.sleep(2)

print "Goodbye this is the end of the if, elif, and else script."
time.sleep(2)

As you can see first we ask for the users' name, then we start the if statement. When you are comparing something in an if statement and if it is something for example HeadRush, we have to use == because that means if it equals something. Then we see "HeadRush" this is just there because if the users' name is HeadRush then we continue on with the if statement, we have to put a : at the end because it just means we continue with the stuff below. As you can see after the if statement we have to space 4 times or tab it because that is just how if statements and other things are because it follows it and it sees the information separate from everything and executes the code. Now we see elif, so if the users' name is Nyx- we print out the following information.
At the end we see else, so if your name is not in any of the other statements it the script follows the else statement.

While Loop:

For the while loop we look at a two things the loop itself and break. Break is just what we write to end the loop. For the while loop the loop won't stop until we use break. Now for a loop we have to use boolean, which is true or false. If a loop is true then it is running if it is false then the loop stops. The loops is an extremely good part of a script if you have a menu but we won't go through that in this tutorial. Here is an example of a loop.

Code:
#!/usr/bin/python
import time
yourName = str(raw_input("Please enter your name: "))
while True:
    if yourName == "HeadRush":
        print "You are making this tutorial!"
        time.sleep(2)
        break
    elif yourName == "Nyx-":
        print "You are an anime master"
        time.sleep(2)
        break
    else:
        print "Oh welcome to this script."
        time.sleep(2)
        break
print "Goodbye this is the end of the if, elif, and else script."
time.sleep(2)

As you can see the while loop is just while, and we use True because we want the loop active. It goes through or previous if script now you see break, break just exits the loop or else it wouldn't stop repeating itself until you manually closed it. The rest of the script is the exact same.

Creating a Basic Calculator:

I am not going to go in depth with this calculator if you don't understand any part of the calculator just refer back to the tutorial. By the end of this tutorial you should be able to make a basic calculator like this.

Code:
#!/usr/bin/python
import time
print "Welcome to HeadRushs' ending tutorial Calculator!"
time.sleep(2)
print "1) add"
print "2) subtract"
print "3) multiply"
print "4) divide"
time.sleep(1)
userChoice = int(raw_input("Enter a number as an option: "))
while True:
    if userChoice == 1:
        addNumberA = int(raw_input("What is the first number you would like to add: "))
        addNumberB = int(raw_input("What is the second number you would like to add: "))
        addEquals = addNumberA + addNumberB
        print addEquals
        time.sleep(1)
        break

    elif userChoice == 2:
        subtractNumberA = int(raw_input("What is the first number you would like to subtract: "))
        subtractNumberB = int(raw_input("What is the second number you would like to subtract: "))
        subtractEquals = subtractNumberA - subtractNumberB
        print subtractEquals
        time.sleep(1)
        break

    elif userChoice == 3:
        multiplyNumberA = int(raw_input("What is the first number you would like to multiply: "))
        multiplyNumberB = int(raw_input("What is the second number you would like to multiply: "))
        multiplyEquals = multiplyNumberA * multiplyNumberB
        print multiplyEquals
        time.sleep(1)
        break

    elif userChoice == 4:
        divideNumberA = int(raw_input("What is the first number you would like to divide: "))
        divideNumberB = int(raw_input("What is the second number you would like to divide: "))
        divideEquals = divideNumberA / divideNumberB
        print divideEquals
        time.sleep(1)
        break

    else:
        print "You have chosen an invalid option, goodbye"
        time.sleep(1)
        break

print "I hope you enjoyed my tutorial and learned a lot."
time.sleep(1)



Helpful Resources:



Python 2.6 Documentation:

Python 2.6 documentation link is right here Python 2.6 Documentation. I always refer to this when I have an issue with Python because it has really good explanations of the code and is really easy to follow.

A Byte of Python:

A Byte of Python is an extremely good book to download, I am currently reading it. It goes through the information fast but if you don't understand something refer to a website and try to understand the code. Here is a link to A Byte of Python: A Byte of Python, if you don't want to download it you can read it online.

Awesome thread, I just had to share.
Credits: http://www.supportforums.net/showthread.php?tid=6808 Smile

Reply






Users browsing this thread: 1 Guest(s)