Tuesday, February 9, 2010

Python - A Real Beginners Guide

PYTHON

I. Intro
II. My First Program
III. Variables, Numbers and Strings
IV. String Manipulation
V. Operators
VI. Arrays/Lists
VII. Loops and Conditionals
a. The IF/ELIF/ELSE Statements
b. The WHILE Statement
VIII Bye bye! Good luck!

+---------------------------------------+
I. Intro
+---------------------------------------+
PYTHON! According to Python.org, this is what Python is...:

"Python is a dynamic object-oriented programming language that can be
used for many kinds of software development. It offers strong support
for integration with other languages and tools, comes with extensive
standard libraries, and can be learned in a few days. Many Python
programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code"

More simply however, Python is an easy-to-read, highly compatible,
oft-used programming language that is powerful and quick. It is often
compared to languages such as Perl, Ruby, Java, etc

ABOUT THIS GUIDE:
- This guide is intended for COMPLETE beginners to programming
languages, and is suggested to most as a first language, as it is as
mentioned before, an easy-to-read and simple language :)

REQUIREMENTS FOR THIS GUIDE:
- Having the latest version of Python installed on your computer. The
installers can be found at http://www.python.org/download/


+---------------------------------------+
II. My First Program
+---------------------------------------+
FOR the first program, we will be creating a small program that writes
"Hello World!" on screen.

Here is the code:
CODE :
__________________________________________________________________________
>>>print("Hello World!")
__________________________________________________________________________

BREAKDOWN:
print() - the typical function (functions will be covered more later
on) to write sentences and variables to the screen.

NOTE: It should also be noted that when using the print function, you
must remember that when you try print multiple things, e.g.
>>>print("Lol", "and", "hi"), a space will immediately be placed
between each part.

NOTE2: Instead of using print(), we also can type the string, number,
or variable and press enter in Python Shell to print the value of it
(remember that you will have to wrap strings in quotation marks if you
decide to use this method).


+---------------------------------------+
III. Variables, Numbers and Strings
+---------------------------------------+
VARIABLES are ways of holding information inside a word, to be able to
call the information back later in a program. The way to assign a value is..:
CODE :
__________________________________________________________________________
>>>#This is a comment line... Comment lines in Python are always
>>>#Preceded by a #
>>>#A variable can either hold a string (words) or a number
>>>varName = "variable"
>>>varName1 = 2009
__________________________________________________________________________

Variables can be changed later in the program. They can also hold a
formula or function. In addition, you can assign the same values to
several variables at once. For examples...

CODE :
__________________________________________________________________________
>>>#This variable holds a total of 25
>>>varFormula = 5*5
>>>
>>>#These variables both hold a value of 45
>>>varX = varY = 40+5
>>>
>>>#This variable holds a function that finds out the length of a
>>>#string or other value
>>>varLength = len("Hello World!")
>>>
>>>#The len() function does not work with numbers!
>>>#Using print(varLength) will output the length of "Hello World!"
>>>#which is 12.
>>>
>>>#Remember that when using the len() function, it counts every
>>>#character, including the space, and not just letters.
__________________________________________________________________________

+---------------------------------------+
IV. Word Indexing
+---------------------------------------+
BEING able to control strings is a vital part of programming. We
already know a couple of basic functions that allow us to manipulate or use strings, i.e. print() and len(). Another useful feature of Python is word indexing: being able to pick out certain letters in strings.

Here is an example of how to use word indexing:

CODE :
__________________________________________________________________________
>>>Hello = "Hello World!" #Establishes a variable...
>>>
>>>Hello[0] #Writes the first letter of the variable
"H"
>>>
>>>Hello[1:] #Writes all letters after the first letter
"ello World!"
>>>
>>>Hello[:5] #Writes all letters up to the sixth letter
"Hello"
>>>
>>>Hello[3:7] #Writes letters between the third and eighth letters
"lo W"
>>>
>>>Hello[3:-1] #Writes letters between position 3 and -1
"lo World"

Yes, strangely enough, the first letter is indexed as [0]... Here is a
little table to illustrate index positions.
CODE :

+---+---+---+---+
| A | B | C | D | = String
+---+---+---+---+
| 0 | 1 | 2 | 3 | = Positive indices
+---+---+---+---+
|-3 |-2 |-1 | ? | = Negative indices
+---+---+---+---+

As you will see, there is absolutely no way of selecting a whole string using negative numbers... Of course, there are other ways of doing that.



+---------------------------------------+
V. Operators
+---------------------------------------+
OPERATORS are VERY important in Python... And sound much more
complicated than they really are. Operators are simply mathematical
symbols that do stuff for programming languages. Here is the table of
operators and how they work:
CODE :

MATHEMATICAL OPERATORS - These produce a value
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|+..............|Addition.......|a + 5 = 10.............|
+---------------+---------------+-----------------------+
|-..............|Subtraction....|a - 5 = 0..............|
+---------------+---------------+-----------------------+
|*..............|Multiplication.|a * a = 25.............|
|**.............|Powers.........|a **3 = 25*25*25 = 125.|
+---------------+---------------+-----------------------+
|/..............|Division.......|a / a = 1..............|
|//.............|Rounds to floor|a // 0.3 = 16..........|
|%..............|Gives remainder|a % 2 = 1..............|
+---------------+---------------+-----------------------+

ASSIGNMENT OPERATORS - These give values to a variable
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|=..............|Assigns a value|a = 5..................|
+---------------+---------------+-----------------------+
|-=.............|Subtraction....|a-=10 is the same as...|
|...............|assigner.......|a = a - 10.............|
+---------------+---------------+-----------------------+
|*=.............|Multiplication.|a *= 10 is the same as.|
|...............|assigner.......|a = a * 10.............|
+---------------+---------------+-----------------------+
|**=............|Power assigner.|a **= 2 is the same as.|
|...............|...............|a = a ** 2.............|
+---------------+---------------+-----------------------+
|/=.............|Division.......|a /= 10................|
|...............|assigner.......|a = a / 10.............|
+---------------+---------------+-----------------------+
etc...etc...etc...etc...etc...etc...etc...etc...etc...etc

COMPARISON OPERATORS - These evaluate the truth of a statement
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|==.............|Is equal to....|a == 5.........TRUE....|
+---------------+---------------+-----------------------+
|!=.............|Not equal to...|a != 5.........FALSE...|
+---------------+---------------+-----------------------+
|>..............|More than......|a > a..........FALSE...|
|<..............|Less than......|a < 10.........TRUE....|
+---------------+---------------+-----------------------+
|>=.............|More than......|a >= a.........TRUE....|
|...............|or equal to....|a >= 6.........FALSE...|
+---------------+---------------+-----------------------+

BOOLEAN OPERATORS - These are used to link COMPARISON OPERATORS
...note: a = 5 for the examples...
+---------------+---------------+-----------------------+
|SYMBOL.........|FUNCTION.......|EXAMPLES ON FUNCTION...|
+---------------+---------------+-----------------------+
|and............|Both expression|a==5 and a>1...........|
|...............|must be true...|Evaluates to true......|
+---------------+---------------+-----------------------+
|or.............|Either expressi|a>6 or a<3.............|
|...............|on must be true|Evaluates to false.....|
+---------------+---------------+-----------------------+
|in.............|Checks if value|arr=["lol", "rofl"]....|
|...............|is in an array.|"lol" in arr...TRUE....|
+---------------+---------------+-----------------------+

These are the main operators that you will need when programming in
Python.


+---------------------------------------+
VI. Arrays/Lists
+---------------------------------------+
ARRAYS/lists can be indexed exactly like words, but can store multiple
strings, numbers and variables. Also, you can append arrays: changing
them as you see fit. Here is the correct way of starting an array and changing it.
[/code]
>>>#Starts an array, 5 "elements" long
>>>arr = ["H", "e", "l", "l", "o"]
>>>
>>>arr[0] #Writes the first element in the array
"H"
>>>
>>>#Here are 3 functions that can change lists
>>>#These will be explained at the end of this chapter
>>>
>>>arr.append("!")
>>>arr # <- Prints the array
["H", "e", "l", "l", "o", "!"]
>>>
>>>arr.insert(1, "a")
>>>arr
["H", "a", "l", "l", "o", "!"]
>>>
>>>arr.extend(["Wo", "rld", "!"])
>>>arr
["H", "a", "l", "l", "o", "!", "Wo", "rld", "!"]
>>>
>>>arr.remove("!")
>>>arr
["H", "a", "l", "l", "o", "Wo", "rld", "!"]
[/code]
BREAKDOWN:
arrName.append(value):
........arrName.........- the array to be changed.
........append(value)...- the function to be used. Only takes one
................argument though. I.e, you can not add two elements to
................the array.

arrName.insert(pos,value):
........arrName.........- the array to be changed.
........insert(pos,v...)- function adds an element at the indicated
................position.

arrName.extend([value1, value2...])
........arrName.........- the array to be changed.
........extend([val...])- function adds multiple elements onto the
................end of a list. The elements to be added must be
................inside square brackets. This function only takes
................one argument - i.e. a list ([]).

arrName.remove(value):
........arrName.........- the array to be changed.
........remove(value)...- removes the first instance of the value
................inputted.

As mentioned before, arrays can be indexed the same way as words. Python also allows you to pick a specific letter/range of letters out
words in an array...

>>>arr = ["Hello", "World", "!"]
>>>arr[0][3:] #Picks first word, letters between 3 to end
"lo"

Also, a useful function for both single strings and arrays:

>>>arr = ["Hello, "World", "!"]
>>>arr.index("Hello") #Displays pos of value in array
0
>>>word = "Hello!"
>>>word.index("H") #Displays pos of first occurrence in array
0

Arrays can also be changed by putting them into formulas, e.g.

CODE :

>>>arr = ["Hello", "World", "!"]
>>>arr = arr + [":P"]
>>>arr
["Hello", "World", "!", ":P"]
>>>
>>>arr = [90, 91] * 2
>>>arr
[90, 91, 90, 91]


In conclusion to this section, arrays are a very much needed tool of a
serious programmer...


+---------------------------------------+
VII. Loops and Conditionals
+---------------------------------------+
+---------------------------------------+
VII.a. The IF/ELSE/ELIF Statements
+---------------------------------------+
IFS, elifs and elses help us develop a sense of control to our
programs... Without these, programs would be, in one word, pretty useless... *(...?)*

In this section, we will also create a whole program, that will
eventually be able let the user of the program input a number, and have the program count down from their number to 0.
Here is a summary of each term, and how they work, IF, ELIF, and ELSE,
including the syntax.

CODE :

#For this part of the program, we need to make sure that the input
#is no more than 9, and no less than 1
#----------------------------------------------------IF---------
>>>numArray = [1,2,3,4,5,6,7,8,9]
>>>#^ Sets up a number array,
>>>#so that we can check if the
>>>#input is between 1:9
>>>
>>>a = int(input("Enter a number 1-9: "))
>>> #This line of programming says that the program will
>>> #output "Enter a number 1-9", asking the user to
>>> #"input" an "integer" (whole number) between 1 and 9
>>>
Enter a number 1-9: #Input goes here
>>>if a in numArray: #Checks if input is in numArray
... print("Countdown initializing!")

So far, the program lets the user input a number to the program and the program checks if that number is between 1 to 9, and if it is, the
program prints "Countdown initializing!". Unfortunately, if the number
is more than 9, or less than 1, nothing happens... That is BAD. So we
need to sort this out. Introducing ELIF...
CODE :

#----------------------------------------------------ELIF------
>>>numArray = [1,2,3,4,5,6,7,8,9]
>>>#^ Sets up a number array,
>>>#so that we can check if the
>>>#input is between 1:9
>>>
>>>a = int(input("Enter a number 1-9: "))
>>> #This line of programming says that the program will
>>> #output "Enter a number 1-9", asking the user to
>>> #"input" an "integer" (whole number) between 1 and 9
>>>
Enter a number 1-9: #Input goes here
>>>if a in numArray: #Checks if input is in numArray
... print("Countdown initializing!")
...elif a > 9: #Checks if a is more than 9
... print("Your number is too high...")

Ah, great! Now our program tells the user off for entering a number too high... But what if the input is less than 1? Well, seeing as we have covered 1-9, and anything above 9, we can now introduce "else"...
CODE :

#----------------------------------------------------ELSE------
>>>numArray = [1,2,3,4,5,6,7,8,9]
>>>#Sets up a number array,
>>> #so that we can check if the
>>> #input is between 1:9
>>>
>>>a = int(input("Enter a number 1-9: "))
>>> #This line of programming says that the program will
>>> #output "Enter a number 1-9", asking the user to
>>> #"input" an "integer" (whole number) between 1 and 9
>>>
Enter a number 1-9: #Input goes here
>>>if a in numArray: #Checks if input is in numArray
... print("Countdown initializing!")
...elif a > 9: #Checks if a is more than 9
... print("Your number is too high...")
...else:
... print("Your number is a bit too low!")

WONDERFUL! Our program now works. However, it is a bit plain, let us go on to WHILE.

+---------------------------------------+
VII.b. The WHILE Statement
+---------------------------------------+
SO, our program up to now is pretty good. We still need to make the
countdown though. And on top of that, we need the input to repeat, in
case the number that the user enters a number that is not between
1-9... This is where the WHILE statement comes into play. The WHILE
statement will repeat and repeat til the condition that makes it run
changes.

Here is the modified script, using the WHILE loop.
CODE :

#----------------------------------------------------WHILE-----
>>>numArray = [1,2,3,4,5,6,7,8,9] #Sets up number array
>>>
>>>case = 0
>>>#^ This variable will allow us to switch from
>>>#one loop to the next... Read on
>>>
>>>while case == 0: ###Checks if case == 0 and then runs script
... a = int(input("Enter a number 1-9: "))
... if a in numArray: #checks if input is in numArray
... print("Countdown initializing...!")
... case += 1 #Tells case to increase by 1;
...
... else:
... pass
>>>#"pass" tells the program to do nothing
>>>#And go to the beginning of the loop again
>>>
>>>#The above loop will repeat til the user enters a valid number
>>>#then case will change to 1 and run the below script
>>>
>>>
>>>
>>>while case == 1: #Checks case == 1, i.e, it checks if the
>>> #number in the first loop is valid
... if a == 0:
... case +=1 #Passes the program to the next part
... else:
... print(a,"more loop(/s) til the bang!")
... a -= 1 #Tells the program to take 1 away from input
>>>
>>>#The above loop continues to repeat til a == 0, when it finally
>>>#carries you to the last part of the program...:
>>>
>>>if case == 2:
>>> print("BANG!")

The above program can be broken down into four simple parts:
1. a preparation of the variables for the program to handle

2. loop one: this loop makes the user enter a number between
one to nine, and then goes to loop two, carrying across the
"a" integer input variable.

3. loop two: this loop counts down starting from "a", which
the user specified. When the loop turns variable "a" to 0, the
program changes case to 2, and sends it across to the final
part.

4. This part simply ends the program, printing 'BANG!' to the
screen.


+---------------------------------------+
VIII. Bye Bye! Good Luck!
+---------------------------------------+
SO, yeah, that's the very very very basics of Python. And I can only
hope that this all didn't sound like a complete load of donkey doodar
to you.

If this does not help you at all, many apologies. Here is a site that
might help you if you wanna take it slower:
http://docs.python.org/3.1/tutorial/ :)
Best of luck to all of you :)

BYE BYE!! <3
Code2004 // Connor

Post-script: please remember that ">>>" and "..." mean that this was written in Python Shell. DO NOT use them in a script, because it wont work xD!

No comments:

Post a Comment

try to make something then you never be lost

+++

Share |

"make something then You never be lost"

wibiya widget