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"Code: Select all
x = False
if x == True:
print "Hello World"Code: Select all
x = True
if x == True:
print "Hello World"
else:
print "Goodbye World"Code: Select all
x = 2
if x == 1:
print "Hello World"
else:
print "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"Another example:
Code: Select all
x = True
y = 1 if x == True else 2input() 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 " + xCode: 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]
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 = FalseCode: Select all
x = True
while x == True:
y = raw_input("finish? y/n >")
if y == "y":
breakCode: Select all
x = ["hello", "world"]
for i in x:
print iCode: Select all
hello
worldPrevious: viewtopic.php?f=37&t=11843
Next: viewtopic.php?f=37&t=11904
Advertising