• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The basics, what you need to get started
#1
Firstly i'm going to warn you that i use Linux as my operating system so some parts of this are just for Linux - but you're cool and use Linux, right? Good.

Note: This tutorial is for Python 2.*

A little introduction for the Linux users, when writing a python script you should always start it with "#!/usr/bin/env python" and not "#!/usr/bin/python". If Python is installed in a different directory, other than /usr/bin then using the second method will fail whereas using the first method it'll figure out the correct location of python ( /usr/bin/python or /bin/python from $PATH) and make that as the interpreter for rest of the script.

[code=python]
#!/usr/bin/env python
[/code]

Print

The print command is pretty self explanatory, it simply means print or show the words "Hello World".

[code=python]
print "Hello world"
[/code]

Commenting your code

It is important to comment your code, especially if you work in a team of developers and other people are working on your code.

[code=python]
# This is a comment
[/code]

Variables

In this example "myname" is equal to the value "Mark", myname is a variable that can be recalled later. Printing "Hello" plus the variable will give the result "Hello Mark".

[code=python]
myname = "Mark"
print "Hello " + myname
[/code]

Strings

If you want to make a variable, that age = 16 you can use it in maths such as 10 + age = 26 but when you try to incorporate it in to a sentence such as

[code=python]
age = 16
print "Mark is " + age
[/code]

You'd get an error saying that it cannot add strings and integers together. To get around this you need to make 18 in to a string.

Integer = Numbers
Strings = Letters

[code=python]
age = str(16)
print "Mark is " + age
[/code]

Now when you run it it'll give you, "Mark is 16".

Working with lists

To make a list in Python you first have to give it a name, then have it equal to strings which are inside square brackets, because they are strings they must be in single quotes.

So i've called my list "Family", there are 5 things in my lists, mum, dad, bro, sis and bro. Items in a list are started from 0, so mine is 0-4.

[code=python]
family = ['mum', 'dad', 'bro', 'sis', 'dog']
[/code]

So if we wan't to find a certain person in our family, we can call them out.

[code=python]
family[3]
[/code]

Will give us 'sis' as she's the third value.

You can also count backwards eg.

[code=python]
family[-2]
[/code]

Would also give us the value 'sis'. When counting backwards it starts from -1.


Slicing

Slicing allows you to slice things from a list.

[code=python]
examplelist = [0,1,2,3,4,5,6,7,8,9]
[/code]

If you wanted to extract all of the numbers between 4 and 8 you'd do.

[code=python]
examplelist[4:8]
[/code]

The output would be [4, 5, 6, 7]

You can also leave the end of the range empty, so you can continue to the end of the list, eg.

[code=python]
examplelist[:6]
[/code]

Would start from the beginning and go up to 6, output = " [0, 1, 2, 3, 4, 5] "

[code=python]
examplelist[4:]
[/code]

Going from 4 all the way to the end would give us " [5, 6, 7, 8, 9] "

To see the entire list you can do

[code=python]
examplelist[:]
[/code]

There is an extra option, that allows you to go up in increments, such as

[code=python]
examplelist[1:8:2]
[/code]

Will go from 1, to 8 in multiples of 2. The output is " [1, 3, 5, 7] "


Slicing from a list

First off we need to make a list, we made ours ['m', 'c', 'o', 'm', 'p', 'u', 't', 'e']

[code=python]
example = list ('mcompute')
[/code]

[code=python]
example[4:]=list('pie!')
[/code]

4: mean that we start from the fourth value, in this case p and then go to the end of the list and change the end values to "pie!".

When we run "example" it gives ['m', 'c', 'o', 'm', 'p', 'i', 'e', '!']


Using input and raw_input

In python 2.* there are two types of inputs, "input" and "raw_input", input is generally used for expressions and things like maths problems where as raw_input changes the input in to strings so it can be used for anything.

input

a will then equal whatever number they entered, from here you can use it in maths problems.

[code=python]
a = input ("Enter a number here: ")
[/code]

So if they enter the number 5 then a = 5
It can then be used in equations eg. 6 + a = 11

raw_input

You can take a users input and turn it in to a string. In this example we ask a question, "What is your name? " what ever answer you input it'll be equal to the variable "myname" - you can then recall the variable later.

[code=python]
myname = raw_input = "What is your name? "
print "Hello " + myname
[/code]

Defining

You can group a bunch of things by defining them, they'll be run in order. The output of this is Hello on one line and then World directly beneath it on another.

def is the command, print_these is the name (it can be anything). An important note to know here is that python works off white space, the following lines under the def print_these(): need to be exactly 4 spaces in each other wise it won't work, you'll probably get an error similar to "IndentationError: unexpected indent". Lastly, print_these() runs it.

[code=python]
def print_these():
print "Hello"
print "World"

print_these()
[/code]


Loops

This is a while loop, it's not the most practical example but everything works. It has defined classes, variables, prints, loops, if statements and inputs.

[code=python]
retry_yes = "r"
retry_no = "c"

def printed():
print "You pressed r"

while 1:
retry = raw_input("Press ' r ' to retry or ' c ' to continue.. ")
if retry == retry_yes:
printed()
if retry == retry_no:
print "You pressed c"
[/code]

Running terminal commands in Linux

It took me a while to find this when i first needed it, but here it is. The example below is a simple "ls" command in Linux.

[code=python]
import os
os.system("ls")
[/code]

You can also run it in conjunction with variables such as below, this will simply delete whatever file you enter.

[code=python]
import os
file_name = raw_input("What file do you want to delete? ")
delete_file = "rm " + file_name
os.system(delete_file)
[/code]

Reading and writing files

The raw_input is optional, it simply gets the location of the file, in then opens the files, reads the lines two and three then write the data to the lines, then closes the file. Note: It starts counting the lines from 0 so what we'd think was line 1 would be line 0, that's why [3] is really line 2.

[code=python]
file_location = raw_input("File location: ")

#Opens and reads the file.
file = open(file_location, 'r')
info=file.readlines()
info[3]= "This is the second line"
info[4]= "This is the third line."
#Opens and writes to the file.
file = open(file_location, 'w')
file.writelines(info)
#Closes the file
file.close()
[/code]

Running a python file

When running a python file from a Linux terminal you should use the following syntax. You need to state that the file is a python file first, and then enter the file you wish to run.

Code:
python script.py
  Reply


Forum Jump: