Now that your more familiar with Python's syntax lets see some statements.
if, elif, else:
The if statement is used to execute some code when a special condition is met:
- Code: Select all
x = True
if x == True:
print "Hello World"
as you can see the text "Hello World" is only printed if the variable X is equal to the boolean True, so if x is not equal to True then "Hello World" will not be printed:
- Code: Select all
x = False
if x == True:
print "Hello World"
If that's the case then we're better off using the else statement after the if statement:
- Code: Select all
x = True
if x == True:
print "Hello World"
else:
print "Goodbye World"
It's pretty simple, if x is True then print "Hello World", otherwise print "Goodbye World". Now the else statement doesn't mean x needs to be False, it can be anything as long is it's not True:
- Code: Select all
x = 2
if x == 1:
print "Hello World"
else:
print "Goodbye World"
This mean that if x is anything but 1 it prints "Goodbye World".
Then we have the elif statement, which is a combination of else if:
- Code: Select all
x = 1
if x == 1:
print "Hello"
elif x == 2:
print "Goddbye"
else:
print "Unrecognised number"
This will help you put more than one code depending on the situation of the variable x.
Another example:
- Code: Select all
x = True
y = 1 if x == True else 2
This is the same as before, but more compact.
input() and raw_input() :
We have seen the print statement, but now lets see the input() and raw_input() functions.
Both functions let you ask the user for an input, whether hitting the enter button or typing something:
- Code: Select all
x = raw_input("Enter your name > ")
print "Your name is " + x
while raw_input() is used to input strings only, input() can be used to input strings, integers, lists, tuples, bools, etc:
- Code: Select all
>>> x = input("type a string > ")
type a string > "hello"
>>> y = input("type an integer > ")
type an integer > 1
>>> z = input("type a list > ")
type a list > ["hello", 1]
>>> print x
hello
>>> print y
1
>>> print z
['hello', 1]
while, for, in:
The while statement is used similarly to the if statement, it gets executed if a certain condition is met, but it's a loop, this means the code is going to be executed over and over again until that condition is no longer met:
- Code: Select all
x = True
while x == True:
y = raw_input("finish? y/n >")
if y == "y":
x = False
it can also be terminated with the break statement:
- Code: Select all
x = True
while x == True:
y = raw_input("finish? y/n >")
if y == "y":
break
The for statement is mainly used to execute code individually for each item in a group:
- Code: Select all
x = ["hello", "world"]
for i in x:
print i
and the results:
- Code: Select all
hello
world
See you in the next lesson...
Previous: viewtopic.php?f=37&t=11843
Next: viewtopic.php?f=37&t=11904