thekrtek.net Thoughts on Security & Technology

18Sep/110

Beginning Python: Lesson 2

Well, it's a Thursday evening and I'm bored, so time for another iteration of Beginning Python! We learned the following last week:

  • Setup of Development Environment
  • Variable Types
  • Operands/Operators (Math and Strings)
  • User Input with raw_input()
  • Testing Operands
Today, we're going to move into more useful topics like loops, functions, and evaluative statements. To get right to it, let's start with evaluative statements and loops.
If you've programmed before then you should be somewhat aware of statements like if, else, while, for, else if and so on. If you haven't programmed before, not to fear, these concepts are quite easy to understand!
  • if statement - evaluates "if" a value on the left coincides with one on the right, such as if 1 = 1 then do
  • else statement - follows after the "if" statement, so if 1 does not equal 2, else, do this now. Basically, if the statement doesn't return true for the "if" statement, do something else.
Before we go on to loops, let's go over if and else. If (pardon the pun) I wanted to make a simple set of code to check a variable and handle it accordingly I would do:
i = 2
if i == 2:
   print 'the value of i is 2!'
else:
   print 'the value of i is not 2!'

What the above block of code does is check (with ==) whether variable i equals the value of 2, if it does then it prints 'the value of i is 2!' in a case where a user would be entering input the else statement or another if statement could be used to take user input and control the flow of the program accordingly (such as a menu). When working with if statements we can use some of the following operators to check values: == (compare two values, see if they match), <= (less than or equal to) >= (greater than or equal to) < (less than) > (greater than). Also if comparing two or more things in an if statement we have expressions like and / or .  Using the example above we can modify it to show this usage.

a = 2
b = 1
if a == 2 and b == 1:
   print 'the value of a is 2 and b is 1'

Onto some simple loops, while and for. The while looks does what it sounds like, "while a condition is met do the following". We can show this with the following:

i = 0
while i < 10:
   print i
   i += 1

So we start with creating a new variable, i, and assign it to the value of 0, then we say, while i is less than 10, print the current value of i and then add 1 to i. It will then loop back up the top and check if i is still less than 10. This loop will keep printing until i = 10 in the final loop. We will go over these in more depth, but on the surface they are quite simple.

Onto the for loop. for loops work by saying "for each item in x, do the following", we can rip an example of this from some code im currently working with:

for char in message:
    new_thing(char)

this says for each char (character) in the message (which is a string variable), call the new_thing function, and pass char to it. It is just as simple as that but when combining everything we've learned so far these items can become very complex and powerful.

More will come soon in this guides, this one isn't as in depth due to my limited time to write them. Once again, email me sbrichards [at] mit.edu if you have any questions or need help!

Filed under: Programming No Comments
9Sep/110

Beginning Python: Lesson 1

PythonScreen1

 

So, it's a Friday night, and you've somehow navigated your way to my site (lucky you). If you came here in search of a guide on learning the Python programming language then you're in the right spot. This guide is intended for absolute beginners and will consist of multiple installments, I'm still learning as well.

To get acquainted with everything and bring you up to speed with who I am... My name is Steve Richards, I'm a student in Seattle Washington and am currently diving into the depths of programming, which I've been fumbling with for the past years. This is a learning process for me as well, so let's do this together :-)

I'm currently running Debian which is a distribution of Linux, you can use Windows, Mac OSX, or Linux as Python is supported on all major platforms. For most of these tutorials I will either be using the IDLE development environment for Python, or Python Interpreter via a Terminal. I'm also using Python 2.7.1+

Assuming you're all set up... Let's go!

Go ahead an open up IDLE or your Python interpreter and type the following (note, >>> notates i'm using the interpreter, do not put it in your code if writing to a file!) :

>>> print 'hello world'
hello world

So this is a very simple "Hello World", we use the  print function and pass some text "literally" to it and then it outputs it. Hopefully you can get the hang of that without too much of an issue. This little demo shows some important subtle items about Python, Python is very flexible. For instance, there is no parentheses, no semi-colon, and I can interchange " " and ' '. These characteristics of Python, bundled with the quick and simple interpreter makes for very quick coding.

Moving on... let's get our types down, and variables.

For now we will only deal with a few types. A type is a 'kind' of value that can be stored in a variable. For example:

  • "Hello!" or 'Hello!' are strings
  • 1 is an integer
  • 1.00 is a floating point number
  • Note: "1" is not 1, you cannot add them, we will talk about how to convert soon though...
These are the three we will focus on for now. Let's go ahead and do some basic assignment in Python. In your interpreter do:
>>> string1 = "hello"
>>> integer1 = 1
>>> float1 = 1.00
>>> print string1, integer1, float1
hello 1 1.0

So, what happened here? In line 1, we create a new variable named string1 and assign (with the = sign) the value of "hello" to it. likewise, in lines 2 and 3 we create new variables and assign an integer (whole number) to one and a floating point (decimal number) to the other. in the 4th line print all 3 values on one line. If you have any experience with another programming language like C or C# you may wonder how Python knows what type each variable is, in Python, types are inherited. So instead of saying  int number1 = 1; we can just create the variable and Python says "oh, that value is a whole number, I'll assume the type Integer!". We can see this by doing:

>>> type(string1)
<type 'str'>
>>> type(integer1)
<type 'int'>
>>> type(float1)
<type 'float'>

The type function tells us what type that variable is. Now without skipping too far ahead, we can even mask other types as others for converting values, such as:

>>> type(int(float1))
<type 'int'>

This is called "casting", but we will cover that later. Moving on!

Now that we've covered basic assignment of variables using the = sign, let's cover other assignment operators, basic math functions, and evaluation operators.

One set of assignment operators you will use often down the road are the following, += -= *= and /= . While these may look cryptic, they are actually very simple assignments, let's do a demo:

>>> integer1 += 1
>>> print integer1
2
>>> integer1 += 1
>>> print integer1
3
>>> integer1 += 1
>>> print integer1
4

What this is doing is the following: integer1 = integer1 + 1 . This notation is shown with +=, in -= *= and /= it does integer1 = integer1 * number and so on. This is a great assignment operator for counting in loops, which will be covered in another iteration (pardon the pun).

Now onto some evaluative operators, these are used for comparing two or more variables or results. we have ==, <=, >=, <, > and some others to cover later. All of these operators return true or false which are called "Boolean" values. Let's run down what each one means:

  • == (not to be confused with assignment operator =) is for use of comparing two values directly, such as saying "does 2 == 2?", == can be pronounced "equals"
  • <= this is, "is the number on the left less than or equal to the number on the right?" so 1 <= 2 is true, as is 2 <= 2.
  • >= this is, "is the number on the left greater than or equal to the number on the right?" so 2 >= 1 is true, as is 2 >= 2.
  • <    this is, "is the number on the left less than the number on the right?" so 1 < 2 is true, but 2 < 1 is false.
  • >    this is, "is the number on the left greater than the number on the right?" so 1 > 2 is false, but 2 > 1 is true.
Well that was repetitive! These come in handy for logical operations like if, else, while, and for statements while we will cover in the next segment. Only two more things left to cover before we finish off this first part of the series: basic math, and input.
These fancy computer thingies are good for one thing especially, math computation, and what is programming without math! In Python we can simply do math operations by doing the following:
>>> print 1+2+3+4
10
>>> a = 1
>>> b = 2
>>> print a+b
3

As we can see above, we can do simple addition either explicitly using numbers, or assigning values to numbers and adding them. We can do basic math like +, -, *, /, and % (modulus) without importing the math module (which we will cover later).

And lastly before we bid adieu till next time, basic input, so you can actually do something with what you've learned so far! To take user input in the terminal do:

>>> string1 = raw_input("Enter some text!: ")
Enter some text!: Hello!
>>> print string1
Hello!
>>> number1 = int(raw_input("Enter a whole number!: "))
Enter a whole number!: 60
>>> print number1
60

In the first example, we assign user input taken with the raw_input function, the text expressed in the value in ( ) following raw_input is what we prompt the user with, whatever they type after is stored in the variable. In the second example we ask for the user to enter a number, we store this number as an integer (even though raw_input usually stores as a string unless specified otherwise) by using casting. We cast simply by putting int() around raw_input("blah: ").

That's it for now! I hope to add more every week or every few days. This guide/series is dedicated to John, I will teach you Python and you will learn it! If you have any questions or feedback please email me sbrichards [at] mit [dot] edu . No Spam Please!