Sudden Python: Drinking From The Fire Hose
Sudden Python: Drinking From The Fire Hose
15-Apr-14
Running IDLE
IDLE opens a window in which you can enter and run Python commands
Choose File -> New Window to open a window in which you can type entire programs
A program consists of commands (more commonly called statements) that manipulate data Here are the four most common kinds of data:
Integers (whole numbers), such as 5, 17, or -300 Floating point numbers, such as 3.1416 Strings are character sequences enclosed in either single quotes or double quotes, such as "Madam, I'm Adam" and '"Too soon," she said.' Straight quotes only (" and '), not curly quotes ( ) Boolean (logical) valuesthere are only two of these, True and False
4
Program components
Programs can read in data Programs can write results In between reading and writing, programs can
compute, that is, do arithmetic (or logic) test, that is, decide what to do next loop, that is, do the same actions a number of times delegate, that is, ask other parts of the program to perform some task
+ * /
The result of doing arithmetic is often assigned to a variable: sum = 10 + 22 + 13 + 44 + 72 Variables can be used in arithmetic: average = sum / 5
6
Reading in data
name = raw_input("What is your name? ") Whatever the user types in, up to a press of the Enter key, is a string that is assigned to the variable name age = input("What is your age? ") Whatever the user types in, up to a press of the Enter key, is converted to a number and assigned to the variable age
Printing results
Each print statement writes a newline at the end (so that the next print statement goes to a new line) You can omit the newline by ending with a comma:
Comments
A comment is a note to any human looking at the program; comments are ignored by the computer. A comment begins with # and extends to the end of the line Good uses of comments:
At the beginning of a program, to tell what the program does When using someone elses code, to say where you got it from To explain any code thats hard to understand To explain something thats obvious anyway To explain code thats hard to understand, but could be made simpler To add irrelevant comments, like # Go Eagles! When you should instead use a doc string (described on a later slide)
9
Layout
Every statement goes on a line by itself Put spaces around operators, including the assignment operator (=)
When using a function, do not put spaces on either side of the parentheses
10
Your program can decide what to do by making a test The result of a test is a boolean value, True or False Here are tests on numbers:
< means is less than <= means is less than or equal to == means is equal to != means is not equal to >= means is greater than or equal to < means is greater than All capital letters are less than all lowercase letters
11
Compound tests
and gives True if both sides are True or gives True if at least one side is True not given True, this returns False, and vice versa score > 0 and score <= 100 name == "Joe" and not score > 100
Examples
12
The if statement
The if statement evaluates a test, and if it is True, performs the following indented statements; but if the test is False, it does nothing Examples:
if grade == "A+": print "Congratulations!" if score < 0 or score > 100: print "Thats not possible!" score = input("Enter a correct value: ")
13
if with else
The if statement can have an optional else part, to be performed if the test result is False Example:
if grade == "A+": print "Congratulations!" else: print "You could do so much better." print "Your mother will be disappointed."
14
if with elif
The if statement can have any number of elif tests Only one group of statements is executedthose controlled by the first test that passes Example:
if grade == "A": print "Congratulations!" elif grade == "B": print "That's pretty good." elif grade == "C": print "Well, it's passing, anyway." else: print "You really blew it this time!"
15
Indentation
Indentation is required and must be consistent Standard indentation is 4 spaces or one tab IDLE does this pretty much automatically for you Example:
if 2 + 2 != 4: print "Oh, no!" print "Arithmethic doesn't work!" print "Time to buy a new computer."
16
You can refer to an individual value by putting a bracketed number (starting from 0) after the list
The len function tells you how many things are in a list
range is a function that creates a list of integers, from the first number up to but not including the second number
A for loop performs the same statements for each value in a list
Example: for n in range(1, 4): print "This is the number", n prints This is the number 1 This is the number 2 This is the number 3
The for loop uses a variable (in this case, n) to hold the current value in the list
18
A while loop performs the same statements over and over until some test becomes False
Example: n = 3 while n > 0: print n, "is a nice number." n = n 1 prints 3 is a nice number. 2 is a nice number. 1 is a nice number.
If the test is initially False, the while loop doesn't do anything. If the test never becomes False, you have an "infinite loop." This is usually bad.
19
Calling a function
A function is a section of code that either (1) does some input or output, or (2) computes some value.
A function can do both, but it's bad style. Good style is functions that are short and do only one thing Most functions take one or more arguments, to help tell them what to do
Here's a function that does some input: age = input("How old are you? ") The argument, "How old are you?", is shown to the user Here's a function that computes a value (a list): odds = range(1, 100, 2) The arguments are used to tell what to put into the list
20
Defining a function
1. 2.
3.
4. 5. 6.
def sum(numbers): """Finds the sum of the numbers in a list.""" total = 0 for number in numbers: total = total + number return total
1.
2.
6.
def defines a function numbers is a parameter: a variable used to hold an argument This doc string tells what the function does A function that computes a value must return it sum(range(1, 101)) will return 5050
21
Summary
Arithmetic: + - * / % < <= == != >= > Logic (boolean): True False and or not Strings: "Double quoted" or 'Single quoted' Lists: [1, 2, 3, 4] len(lst) range(0, 100, 5) Input: input(question) raw_input(question) Decide: if test: elif test: else: For loop: for variable in list: While loop: while test: Calling a function: sum(numbers) Defining a function: def sum(numbers): return result
22
Advice to beginners
Programming is hard!
The individual building blocks are all pretty simple, but they go together in complex patterns
You will make many mistakes, and they will (almost) all be stupid mistakes
That doesnt mean you are stupid! Experts make just as many stupid mistakes, but they are more experienced at finding and correcting them Therefore: Dont be shy about letting other people see your mistakes
In a few weeks you will find that it suddenly all starts to make sense, and you'll wonder what the problem was Dont panic! Theres lots of help available
23
Advice to non-beginners
A lot is known about how to program well You probably have a lot of bad habits to unlearn The following are important habits to learn:
Thorough testing is essential; anything less is amateurish Concentrate on clarity (not efficiency) at all times If code is hard to understand, simplify it
24
The End
25