Вы находитесь на странице: 1из 25

Sudden Python

Drinking from the Fire Hose

Mar 24, 201

Get Python (and IDLE)

We will be using Python 2 (version 2.7.3), not


Python 3

Get it from www.python.org

The download includes an Integrated


Development Environment (IDE), named
IDLE

Running IDLE

IDLE opens a window in which you can


enter and run Python commands

This window is called a REPL (Read-EvalPrint-Loop)

Choose File -> New Window to


open a window in which you can type
entire programs

To execute the program, hit the F5 key


3

Commands and data

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

Also, programs can ignore comments


5

Doing simple arithmetic

Here are the arithmetic operators:

+
*
/

performs addition
performs subtraction
performs multiplication
performs division

When dividing two integers, the result is an integer: 14 / 5 is 2

% performs modulus (remainder of division): 14 % 5 is 4


** performs exponentiation

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

Heres how to ask the user to enter a string:

Heres how to ask the user to enter a number:

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

input and raw_input are functions (or methods)

For now, we will treat function and method as synonyms


7

Printing results

To print results, use the print statement

You can print multiple things separated by commas

print "Two plus two is four"


print 2, "plus", 2, "is", 2 + 2

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:

print 2, "plus", 2,
print "is", 2 + 2

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

Bad uses of comments:

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 (=)

Put spaces after commas (but not before commas)

average = sum / 5
print 2, "plus", 2, "is", 2 + 2

When using a function, do not put spaces on either side


of the parentheses

age = input("What is your age? ")

10

Decisions and tests

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

These same tests work on strings

All capital letters are less than all lowercase letters


11

Compound tests

Boolean values can be combined with these operators:

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

Examples

score > 0 and score <= 100


name == "Joe" and not score > 100

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

Lists and ranges

A list is a sequence of values enclosed in brackets

You can refer to an individual value by putting a bracketed number


(starting from 0) after the list

Example: len(courses) is 3

range is a function that creates a list of integers, from the first


number up to but not including the second number

Example: courses[2] is 'CIT 593'

The len function tells you how many things are in a list

Example: courses = ['CIT 591', 'CIT 592', 'CIT 593']

Example: range(0, 5) creates the list [0, 1, 2, 3, 4]

If you give range a third number, it is used as the step size

Example: range(2, 10, 3) creates the list [2, 5, 8]


17

The for loop

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

The while loop

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.

1.

2.
6.

def sum(numbers):
"""Finds the sum of the numbers in a list."""
total = 0
for number in numbers:
total = total + number
return total

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!

You will make many mistakes, and they will (almost) all be stupid
mistakes

The individual building blocks are all pretty simple, but they go together in
complex patterns

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

Use comments to explain code you arent able to simplify

Remember that the best way to learn something is to


teach it

24

The End

Programming is an art form that fights back.


-- Anonymous

25

Вам также может понравиться