PDA

View Full Version : [Tutorial - Python] Part 1 - Variables and Code flow



Eris
07-29-2009, 03:20 PM
See also: Part 0 (http://www.animeforum.com/showthread.php?t=88219)

This section of the tutorial will elaborate upon a few more pretty basic concepts. It is pretty long, so you might not want to go through everything in one sitting.

1. Variables

The first order of business is variables. A variable is a named "box" you can put stuff in. It is best explained with an example:



x = 10;
print("x = ", x);


It is important to note that this is not algebra. x = 1 - x does not mean that x=1/2. It means that (the value x will have) = 1 - (the value x has right now).

Example:


x = 10;
print("x = ", x);
x = x * 2;
print("x = ", x);


Another property of variables in python is that they store only values, and not expressions.

Example:


x = 10;
y = x;
print("x =", x, "y =", y);
x = 5;
print("x =", x, "y =", y);


500
Variables must start in either _ or a letter, and beyond that contain only _, letters and numbers. The following are all valid and distinct variable names:

_toupee
_Toupee
_TOUPEE
o_O
____
twenty2_5
LaAaaAAaaRD



Problems:
Which of these variable names are valid? If they are not, why so?

X
X35
35X
_35X
X 35

All are valid except "35X" which starts with a number, and "X 35" which has a space in it.

500

Let's put this newfound knowledge to use. I'll introduce a new function called "input". It reads text from the user. Example:


name = input("Who are you? ");
print("Hello", name);


This is a new sort of function. Print only receives data, but input gives some back as well. An example session looks like this:


Who are you? Eris
Hello Eris


Believe it or not, this is actually a very important milestone. It is your first non-deterministic program. Up to this point, the behavior of all programs have been set in stone before they were even started. But this program is not like that. It's behavior changes with the user's behavior.

Intermission: Logical operations

It's time to introduce yet another type: Boolean. A boolean can only hold one of two values: True and False (which are equivalent to 1 and 0).

There are three boolean operations: "and", "or" and "not". It's about time for another dreary cheat sheet:


print("and");
print("True and True = ", True and True);
print("True and False = ", True and False);
print("False and True= ", False and True);
print("False and False = ", False and False);
print("");
print("or");
print("True or True = ", True or True);
print("True or False = ", True or False);
print("False or True= ", False or True);
print("False or False = ", False or False);
print("");
print("not");
print("not True = ", not True);
print("not False = ", not False);


There are a whole host of comparison operators that evaluate to boolean values.

x == y evaluates to True if x and y are the same, otherwise False.
x != y evaluates to False if x and y are the same, otherwise True.
x > y evaluates to True if x is greater than y, otherwise False.
x >= y evaluates to True if x is greater than or equal to y, otherwise False.
x < y evaluates to True if x is lesser than y, otherwise False.
x <= y evaluates to True if x is lesser than or equal to y, otherwise False.


But what does "greater" and "less" mean? In numbers, it's pretty obvious, but what about strings? You can think about it like this: In which order would they end up in the phone book? If one string ends up before another, it's less than the other, and vice versa.

Example:

print("John < Bob = ", "John" < "Bob");
print("John > Bob = ", "John" > "Bob");
print("John <= Bob = ", "John" <= "Bob");
print("John >= Bob = ", "John" >= "Bob");
print("John == Bob = ", "John" == "Bob");
print("John != Bob = ", "John" != "Bob");
print(" --- ");
print("Bob < Bob = ", "Bob" < "Bob");
print("Bob > Bob = ", "Bob" > "Bob");
print("Bob <= Bob = ", "Bob" <= "Bob");
print("Bob >= Bob = ", "Bob" >= "Bob");
print("Bob == Bob = ", "Bob" == "Bob");
print("Bob != Bob = ", "Bob" != "Bob");

It's worth noting that upper case letters are sorted after lower case letters. So "Zebra" < "aardvark".

3. Code flow

At long last, all that tedious logic is over, and we can get to some really useful stuff. Code flow. I'll cover two ways of changing the code flow: if and while.

3.1 If

I'll begin with an example.


name = input("Who are you? ");
if name != "Eris":
print("Get out of my program!");
print("I know Ninjas!");
print("Bye.");


It is important to note that the long space before print is a single tab. Not 7 spaces, and not 2 tabs. One and only one tab.

The warning to get out of the program is only printed if the name given isn't Eris. "Bye" is always printed.


The if statement has the following anatomy:


if (expression) :
block


If "expression" is true, the code "block" is run. A code block is one or more lines with a tab in front of them. You can also extend your if statement with an else statement, that only runs if the original expression is false.

Let's extend the original example:


name = input("Who are you? ");
if name != "Eris":
print("Get out of my program!");
print("I know Ninjas!");
else:
print("Hello Eris. Here are your slippers and a newspaper.");
print("Bye.");


Then there's elif (short for else if). Let's re-write the example to incorporate all these features:


name = input("Who are you? ");

if name == "Eris" :
print("Hello Eris. Here are your slippers and a newspaper.");
elif name == "Number Six":
print("I see you went back to your old name, Eris");
elif name == "HAL9000":
print("Open the Pod Bay door, HAL.");
else:
print("Get out of my program!");
print("I know Ninjas!");

print("Bye.");


If statements must be constructed so that they start with if, then optionally one or more elif:s, then optionally an else. That is the only valid order.

A more abstract example:


if (A):
P;
elif (B):
Q;
elif (C):
R;
elif (D):
S;
else:
T;

P is only run if A is true.
Q is only run if A is false and B is true.
R is only run is A is false, B is false and C is true.
S is only run is A is false, B is false, C is false, and D is true.
T is only run if A, B, C and D are all false.

You can also put if statements inside if statements:


name = input("Who are you? ");

if name < "N":
if name < "H":
print("Your name starts with either A, B, C, D, E, F or G");
else:
print("Your name starts with either H, I, J, K, L or M");
else:
print("Your name starts with either N, O, P, Q, R, S, T,",
"U, V, W, X, Y, or Z");


The above code is equivalent to


name = input("Who are you? ");

if (name < "N") and (name < "H"):
print("Your name starts with either A, B, C, D, E, F or G");
elif (name < "N") and not (name < "H"):
print("Your name starts with either H, I, J, K, L or M");
else:
print("Your name starts with either N, O, P, Q, R, S, T,",
"U, V, W, X, Y, or Z");


That's all you need to know about if statements.

3.2 While

The next and final chapter deals with loops, more specifically the while statement. While evaluates a code block as long as the expression it is given is true.

Example:


x = 0;
while x < 10:
print("x = ", x);
x = x + 1;


That program prints x, and increases it by one until it reaches 10. So it prints numbers 0 through 9.

Inevitably, you'll write a program where the statement always is true. You have by that point constructed an infinite loop.


while 1 < 4:
print("All work and no play makes Jack a dull boy.");


If that happens, you can cancel the program by pressing Ctrl+C.

You can also bail out of a loop from within a program by using the "break" statement. This code does the exact same thing as the first program, but checks the condition from within the loop.



x = 0;
while 1 == 1:
if x >= 10:
break;
print("x = ", x);
x = x + 1;


Last, but not least is "continue". Continue skips the rest of the loop block, and restarts a new repetition.



x = 0;
while 1 == 1:
if x > 10:
break;
x = x + 1;
if (x % 2) == 0:
continue;
print("x = ", x);


Remember in the previous part about numbers, how '%' gives you the remainder of a division. If the remainder of a division of zero, then the division goes even. In this case, it skips the printing of the number if x is evenly divisible by two.

So this program prints all odd numbers from 0 through 10.

Problems

Write a program that keeps asking for a password until the correct password is given.
Make the program keep track of how many failed attempts have been tried.
Calculate the sum of all numbers from 1 through 100. (You should get 5050)
Calculate the sum of even numbers from 1 through 100. (You should get 2550)
(Difficult) Re-print the truth tables for or and and with use of loops.
Remember that 0 = False and 1 = True.
You need to put one loop inside another.

Experiment!


That's it for now. I don't know if it's possible to make sense of it all. Do ask questions if I've been going too fast.

Next section will be about functions.

IFS
07-29-2009, 03:55 PM
Thanx alot, I'm going to save all these tutorials, for self study later, seeing as I'm a little to busy with my Project management course, but this is really well explained.