in lesson 1 we explored how to print, store, and get data from the user, as well as types. in this lesson we'll explore conditional statements. by the way, were you able to do the practice problem?
it should look something like this
Code:
x = int(raw_input("what x value would you like? "))
y = int(raw_input("what y value would you like? "))
print x,y
temp =x
x = y
y = temp
print x,y
hopefully you were able to figure this out. if not you may need an even simpler guide.
anyway on to conditional statements. a conditional statement is a piece of code that compares variables and executes the block of code beneath it if the result its true.
Code:
x = int(raw_input("what x value would you like? "))
y = int(raw_input("what y value would you like? "))
if x < y:
print "wow x is", y-x, "whole values away from y."
elif y != 0:
print "ah man, x is", x/y,"times greater than y."
else:
print "whoops, y = 0"
print: "it's the end of the world as we know it!"
this is a fairly simple program that takes two values from the user, and compares them. the first if statement asks "is x less than y?" if so it will execute the print "wow... code.
if not it then goes to the elif statement. elif asks "is y anything but 0?" if so it executes the print "ah man... code. then if y is less than x, and y = 0, it prints "whoops... code. finally no matter which condition executes, the last print "it's the end... gets executed.
note the white space. in python, white space is important, it indicates a group of code.
be sure to use the same amount of white space before each line and use the space bar to indent if you want code together. now let's look at the for statement.
Code:
y = 0
for x in range(0,10):
y = y+x
print "add", x,"to y."
print "y =",y
so x will start off at 0, then go to 1, then 2, etc up to 9. for each x value, the code beneath executes. once again note that the code beneath the for loop is indented. let's take the last example the while loop. while loops are useful when your not entirely sure when you want your code to end.
Code:
y= 0, x= 0
while x < 10 and y<x:
y = y+x
if y>x:
y = y/x
x = x+1
well that's basically it for this lesson. here's another practice problem for you. write code that takes in a value, and then approximates the square root of it.
hint: use two variables, a and b, adding a and b and halfing the result. if this number multiplied by itself is greater than the original number, let a equal the half, else let b.