Some python essentials to get you started

Assigning a variable and printing its value

my_string = "I am a string"
my_num = 5

print my_string, "and I'm a", my_num
I am a string and I'm a 5

A for loop along a list

print range(10)
for num in range(10):
    print num
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
1
2
3
4
5
6
7
8
9

Another for loop

for item in ['dog', 'cat', 'pig']:
    print item
dog
cat
pig

A few simple conditionals (if statements)

if my_num == 5:
    print "it's a 5!"
else:
    print "it's not a 5!"
it's a 5!
if 5<2:
    print 'yes indeed'
elif 10<2:
    print 'this is true too!'

Predict what each of these statements will return. Then check.

print 's'==True
False
print 1==True
True
print 0==True
False
print True==False
False
print (True or False)==True
True
print print==True
  File "<ipython-input-10-4540373c5b89>", line 1
    print print==True
              ^
SyntaxError: invalid syntax

A while loop

another_num=5
while another_num <= 5 and another_num>0:
    print "I'm a ", another_num, "and I'm less than or equal to 5!"
    another_num -= 1
I'm a  5 and I'm less than or equal to 5!
I'm a  4 and I'm less than or equal to 5!
I'm a  3 and I'm less than or equal to 5!
I'm a  2 and I'm less than or equal to 5!
I'm a  1 and I'm less than or equal to 5!

Now for a couple exercises

  1. Use a for loop that prints out the numbers 0 through 5
  2. Use a for loop to print out the numbers 2 through 8. Now do another one to print 9 through 0 (i.e., backwards)
    Use help(range) to see some other things you can do with the range function
  3. Given the list ['one', 'two','three','four'], write code that will print: 'one and a two and a three and a four'
  4. Write a bit of code using for loop(s) that print out the following sequence:
    0
    01
    012
    0123
    01234
    012345
    This one's gonna be challenging to people who have not programmed before. Give it a try and then turn to your neighbor and talk about how you might solve it.
If you're writing your program in the Python Shell or in a Jupyter Notebook, Python will automatically append a newline to anything you print. To keep it from doing that end the print statement with a comman, e.g., `print i,`. If you're writing the code in a text editor and executing using `python filename.py`, you can keep using `print` in the normal way.