This Presentation is a draft of a summary of "Learn Python The Hard Way" Book which is very helpful for anyone want to learn python from scratch of
For reading the book and do exercises, the book is available for free here: http://learnpythonthehardway.org/book/
2. • INTERACTIVE MODE PROGRAMMING
•Invoking the interpreter without passing a script file as a parameter brings up the following prompt:
type python and then you can write your commands but if you need to exit that mode type: quit()
• SCRIPT MODE PROGRAMMING
•To write the code in a file with extention “.py” like ex.py and to run it type: python ex.py
•You need to be in the same directory that have the file so if the file path is “D:Phase8-python” use cd
/d D: to change the drive to D and use cd Phase8-python to change the directory to yours (for
Windows 8).
•If you want to get your country's language characters into your file, make sure you type this at the top
of your file: # -*- coding: utf-8 -*- .
3. •Identifier: A name is used to identify a variable, function, class, module or other object
•An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
•Python does not allow punctuation characters such as @, $ and % within identifiers.
•Python is a case sensitive programming language.
•Class names start with an uppercase letter and all other identifiers with a lowercase letter.
•Starting an identifier with a single leading underscore indicates by convention that the identifier is meant
to be private.
•Starting an identifier with two leading underscores indicates a strongly private identifier.
•If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
4. •You can’t name the identifies with the python reserved keywords
5. Multi-line Comment:
You can use “”” “””to make comments.
multiline comments are also used to embed what are called doc strings in a function.
• Comments
• You can use “” or ‘’ with print.
• Any character between “” or ‘’ is considered to as string even if it ‘’ , “” , ! ,or # and so on
• You can use , to print strings with variables.
Single Line Comment:
You can use # to make comments. The # charcter is called octothorpe , pound character ,or hash
6.
7. •Order of operations:
1. Parenthesis
2. Exponent
3. Multiplication and division
4. Division Remainder
5. Addition and subtraction
symbol name Use
+ plus Addition
- minus Subtraction
* asterisk multiplication
/ slash division
% modulus Division remainder
> Greater than Comparison
>= Greater than or equal Comparison
< Less than Comparison
<= Less than or equal Comparison
•Int $ Int = Int Ex: 7/4 =1
•Float $ Int = Float Ex: 7.0/4 =1.75
•Int $ Float = Float Ex: 7/4.0 =1.75
•Float $ Float = Float Ex: 7.0/4.0 =1.75
•Where $ is any mathematic operation
•In th int result, the fractional part after the decimal will be
dropped
8. •Formatters tell Python to take the variable on the right and put it in to replace the %s
with its value.
•You can put the value directly instead of variable name.
sym
bol
name Use
%s String format Used for string representation
%d Decimal Outputs the number in base 10.(to format a number for display)
%r Raw data
Used for debugging to display the raw data for programmers ,where the other
formatters used for displaying to users (representation) like: %s, %d ,etc
Display strings between ‘’ and the raw values for other variable types.
%c Character Converts the integer to the corresponding unicode character before printing.
%b Binary format Outputs the number in base 2.
For one variable
More than one variable
9. •If you multiply a number n in the statement you want to print the statement will be printed n times
•We can use ‘+’ to concatenate two strings (print them sequentially without space)
•After each print, there is a new line ‘n’. So every print will be in a separate line. However, if we put a ,
(comma) at the end of line, the next print will be at the same line.
•In python it’s a bad style if the line is longer than 80 characters.so if the print line exceed that number
we can divide it to two print with comma at the first end to be printed at the same.
•To print multiline as they ‘re written we can use “”” “”” or ‘’’ ‘’’ (no spaces between each 3 commas)
10. •Escape sequences: to encode difficult-to-type characters in a string (print those
characters inside string without error).there are two ways to escape sequence:
1. Using ‘’ backslash:
2. Using “”” “”” or ‘’’ ‘’’
symbol Use
Escape backslash
” Escape double quotation
’ Escape single quotation
n To make a new line. Don’t work with %r which is not made for presentation
t Horizontal tab
v Vertical tab
11. Or
•Command line arguments come in as strings, even if you typed numbers on the command
line. Use int() and float() to convert them just like with int(raw_input()) and float(raw_input()) .
12. • A module is a file containing Python definitions and statements. The file name is the module name with the
suffix .py appended.
•Within a module, the module’s name (as a string) is available as the value of the global variable __name__.
•import module_name or from module_name import * #import all statements from this module
•from module_name import def_name #import specific statements or definition
•You can access the functions or variables in that module with the . (dot) operator.
•Ex: use apple function and tangerine variable from my stuff.py file
•sys : “system specific parameter” This module provides access to some variables used or maintained by
the interpreter and to functions that interact strongly with the interpreter.
•argv : “Argument Variable” holds the list of arguments you pass to your Python script when you run it.
argv[0] is the script name (it is operating system dependent whether this is a full pathname or not).
•Unpacking argv to variables
•Passsing arguments to the sript in run time
13. •It is better to ask the user about the file name than hardcoded it (Write it in your code) so you can
user either raw_input or argv as follows
•Or
•Then
•Use close fn when you finish reading the file
14. • Open(file_name , open_mode). If you don’t write the mode it’s read by default
• Modes: 'w' fore write(truncating the file if it already exist ) , ' r' for read ,and 'a' for append.
• The 'w' and 'a' modes will create the file if not exist but ‘r’ returns error if the file not exist .
• There is also the + modifier : 'w+', 'r+', and 'a+'. This will open the file in both read and write
mode, and depending on the character use position the file in different ways.
• Truncate() : Empties the file. It is not necessary if you open the file in write mode
• Close() : Closes the file. Like File->Save.. in your editor
• Read() : Reads the contents of the file. You can assign the result to a variable.
• Readline() : Reads just one line of a text file.
• Write(“Stuff”) : Writes "stuff" to the file.
• Seek(line_number) : A file in Python, like an old tape drive, has a "read head," (to determine the
position of reading)and you can "seek" this read head around the file to positions, then work with
it there. Each time you do f.seek(0) you're moving to the start of the file. Each time you do
f.readline() you're reading a line from the file, and moving the read head to right after the n that
ends that file. After read() you need to seek the read head to 0 or the position you want because
position will be at the end of file an will not read anything.
15. • Exists(file_name) : returns True if the file exists and False otherwise , based on its name in a
string as an argument. To use exists function, you need to import os.path module
• Len(“any string”) : gets the length of the string that you pass to it then returns that as a
number of bytes.
• You can make a file from command prompt and write text to it by the following command
• If you want to show the file content (in Linux)
16. • Define the function
• And call it
• If the function has no arguments, then the parenthesis will be empty function_name()
• The functions with more than one argument has two ways in definition :
1. The ordinary way
2. Passing arguments as a list like argv
• * in *args: tells Python to take all the Fn arguments and then put them in args as a list. It's like argv that
you've been using, but for functions. It's not normally used too often unless specifically needed.
17. • When functions are dealing with files you can sending the file object instead of the file name to
minimize the code lines (if there are many files dealing with that file)
• Use return to get a value from a function and receive it in a variable.
• After the return statement , any code will not executed.
18. Function Use
print To print anything
python ex.py To execute python script named ex.py
python To enter the interactive programming mode
quit() To exit the interactive programming mode
raw_input(“msg”) Take input from user
int() Convert its input to int
float() Convert its input to float
open(file_name,mode) Open file and return object refer to it
Obj.read() Reads the contents of the file.
Obj.readline() Reads just one line of a text file.
Obj.write() Writes text to the file.
Obj.truncate() Empties the file
Obj.close() Close file
Obj.seek() reposition the read head by bytes. 0 reposition to file start
Len() gets the length of the as a number of bytes.
Exists() returns True if the file exists and False otherwise
21. •Order of operations:
1. Find an equality test (== or !=) and replace it with its truth.
2. Find each and/or inside parentheses and solve those first.
3. Find each not and invert it.
4. Find any remaining and/or and solve it.
5. When you are done you should have True or False.
22. •if-statement creates what is called a "branch" in the code. If the boolean expression (condition)
is True, then run the code under it, otherwise skip it.
•A colon at the end of a line tells Python you are going to create a new "block" of code, and then
indenting four spaces tells Python what lines of code are in that block.
•If-Elif-Else Statements:
•Nested If Statements
23. •List: a container of things that are organized in order from first to last.
•Start the list with the [ and end the list with a ]. Then you put each item separated by commas.
•List elements may be the same type or mixed
•We can print list as one unit using print but we use for to deal with each element in it
•List operations:
list.append(x): add an item to the end of list; equivalent to a[len(a):] = [x].
list.extend(L): Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
list.insert(i,x): Insert an item at a given position i.
list.remove(x): Remove the first item from the list whose value is x. It is an error if there is no such item.
list.pop(i): Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns
the last item in the list.
ist.index(x) : Return the index in the list of the first item whose value is x. It is an error if there is no such item
list.count(x): Return the number of times x appears in the list.
list.sort(cmp=None, key=None, reverse=False): Sort the items of the list in place (the arguments can be used for sort
customization,
list.reverse(): Reverse the elements of the list, in place.
•2D list:
•To access element in list list[index].The index of 1st element is 0 and the index of 2nd element is 1 and so on.
24. •Len(s) : Return the length (the number of items) of an object s. The argument may be a sequence (such as
a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
•String.split(str,num) :returns a list of all the words in the string, using str as the separator (splits on all
whitespace if left unspecified), optionally the second argument num limiting the number of splits to num.
•Str.join(seq) : returns a string, which is the concatenation of the strings in the sequence seq. The separator
between elements is the string str. seq is a sequence of the elements to be joined for ex: list of strings.
•List[3:5] : extracts a "slice" from the list that is from element 3 to element 4, meaning it does not include
element 5. It's similar to how range(3,5) would work.
•List[-1] : return the last element in the list and the index -2 return the element before the last and so on.
25. •For-loop styles:
1. Through a list
2. Repeat no of times using range function
•The range() function only does numbers from the first to the last, not including the last This turns out to be
the most common way to do this kind of loop.
•While-loop:
•A while-loop will keep executing the code block under it as long as a Boolean expression is True. like an if-
statement, but instead of running the code block once, they repeat until the expression is False.
26. •While True : for infinite loop.
•Use (CTRL-c) to abort the program if your loop goes crazy (infinite loop by fault ) .
•Exit(0) : to abort the program. Need to write: from sys import exit
•On many operating systems a program can abort with exit(0), and the number passed in will indicate
an error or not. If you do exit(1) then it will be an error, but exit(0) will be a good exit. The reason it's
backward from normal Boolean logic (with 0==False is that you can use different numbers to indicate
different error results. You can do exit(100) for a different error result than exit(2) or exit(1).
•X in y : if y is a sting, then in checks for sub string
•if y is kind of iterable (list, tuple, …) , then in checks for membership.
•If y is a dictionary, then in checks for membership to being on of the keys.
27. The best way to work on a piece of software is in small chunks like
this:
1.On a sheet of paper or an index card, write a list of tasks you need to
complete to finish the software. This is your to do list.
2.Pick the easiest thing you can do from your list.
3.Write out English comments in your source file as a guide for how you
would accmplish this task in your code.
4.Write some of the code under the English comments.
5.Quickly run your script so see if that code worked.
6.Keep working in a cycle of writing some code, running it to test it, and
fixing it until it works.
28. •First, print out the code you want to understand. Yes, print it out, because your eyes and brain
are more used to reading paper than computer screens. Make sure you print a few pages at a
time.
•Second, go through your printout and take notes of the following:
1. Functions and what they do.
2. Where each variable is first given a value.
3. Any variables with the same names in different parts of the program. These may be trouble
later.
4. Any if-statements without else clauses. Are they right?
5. Any while-loops that might not end.
6. Any parts of code that you can't understand for whatever reason.
•Third, once you have all of this marked up, try to explain it to yourself by writing comments as
you go. Explain the functions, how they are used, what variables are involved and anything you
can to figure this code out.
•Lastly, on all of the difficult parts, trace the values of each variable line by line, function by
function. In fact, do another printout and write in the margin the value of each variable that you
29. •What a dict does is let you use anything as indices, not just numbers. Yes, a dict associates one
thing to another, no matter what it is.
•To add an element
•To delete an element
•To print the whole dict
• dict.items() :Returns a list of dict's (key, value) tuple pairs
•Dict.get(key,default=None) : For key key, returns value or default if key not in dictionary
30. •What a dict does is let you use anything as indices, not just numbers. Yes, a dict associates one
thing to another, no matter what it is.
•To add an element
•To delete an element
•To print the whole dict
• dict.items() :Returns a list of dict's (key, value) tuple pairs
•Dict.get(key,default=None) : For key key, returns value or default if key not in dictionary
31. •Class: Tell Python to make a new type of thing.
•The first method __init__() is a special method, which is called class constructor or initialization method
that Python calls when you create a new instance of this class.
•You declare other class methods like normal functions with the exception that the first argument to each
method is self. Python adds the self argument to the list for you; you don't need to include it when you call
the methods.
•Self: Inside the functions in a class, self is a variable for the instance/object being accessed.
•Object: A unique instance of a data structure that's defined by its class. An object comprises both data
members (class variables and instance variables) and methods.
•Pass: tell Python that you want an empty block. This creates a class but says that there's nothing new to
define in it
•
32. 1. Implicit Inheritance: When you define a function in the parent, but not in the child.Then any
object of the child can call this function as the parent’ s objects do and has the same results.
2. Override Inheritance: When you has a function in the child with the same name of a parent’s
function.Then when an child’s object call the function ,the child function will be executed.
3. Altered Inheritance: special case of overriding where you want to alter the behavior before
or after the Parent class's version runs.
•Multiple Inheritance:
33. •Install the following Python packages:
1. pip from http://pypi.python.org/pypi/pip
2. distribute from http://pypi.python.org/pypi/distribute
3. nose from http://pypi.python.org/pypi/nose
4. virtualenv from http://pypi.python.org/pypi/virtualenv
•ead about how to use all the things you installed.
2. Read about the setup.py fi le and all it has to offer. Warning: it is not a very well-
written
piece of software, so it will be very strange to use.
3. Make a project and start putting code into the module, then get the module working.
4. Put a script in the bin directory that you can run. Read about how you can make a
Python script that’s runnable for your system.
5. Mention the bin script you created in your setup.py so that it gets installed.
6. Use your setup.py to install your own module and make sure it works, then use pip to
uninstall it.
Hinweis der Redaktion
ex1
Ex4.py
Ex1,ex2
there are no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.
Ex3.py
Ex5
To round (approximate) a float number ,You can use the round() function like this: round(1.7333)=2 , round(1.34)=1
Ex5.py
Ex6.py
Ex7.py
Ex9.py
Ex10.py
To know more info about raw_input Fn type pydoc raw_input for linux and python -m pydoc raw_input for windows (Exit out of python first.)
To get out pydoc press q
Ex13.py
For more Ex14.py
The different has to do with where the user is required to give input. If they give your script inputs on the command line, then you use argv. If you want them to input using the keyboard while the script is running, then use raw_input().
command line arguments come in as strings, even if you typed numbers on the command line. Use int() to convert them just like with int(raw_input()).
Ex15.py
Open return something called a “file object” and not the file contents.
there no error when we open the file twice because Python will not restrict you from opening a file more than once and sometimes this is necessary.
To know more info about raw_input Fn type pydoc open for linux and python -m pydoc open for windows (Exit out of python first.)
To get out pydoc press q
Ex16 except seek in ex20
The readline() function returns the \n that's in the file at the end of that line. Add a , at the end of your print function calls to avoid adding double \n to every line.
The seek() function is dealing in bytes, not lines. The code seek(0) moves the file to the 0 byte (first byte) in the file.
Inside readline() is code that scans each byte of the file until it finds a \n character, then stops reading the file to return what it found so far. The file object is responsible for maintaining the current position in the file after each readline() call, so that it will keep reading each line.
EX17.py
Cat file_name :It's an old command that "con*cat*enates" files together, but mostly it's just an easy way to print a file to the screen. Type man cat to read about it.(for linux not windows)
Ex18
The function names same as variable names. Anything that doesn't start with a number, and is letters, numbers, and underscores will work.
We can give the function parameters as: straight values. We can give it variables. We can give it math. We can even combine math and variables.
the number of arguments a function can have ,depends on the version of Python and the computer you're on, but it is fairly large. The practical limit though is about five arguments before the function becomes annoying to use.
Ex20,21 but seek part in the Reading and Writing Files slide
x = x + y is the same as x += y. In English this is called a contraction, and this is kind of like a contraction for the two operations = and +.
Ex22
To use exists you must write “from os.path import exists” to import it from its module
Ex22
Ex22
Ex22
Ex29, ex30, ex31
Python expects you to indent something after you end a line with a : (colon). If it isn't indented, you will most likely create a Python error.
if multiple elif blocks are True, python starts and the top runs the first block that is True, so it will run only the first one.
putting the if-statements inside if-statements as code that can run. This is very powerful and can be used to create "nested" decisions, where one branch leads to another and another.
if a number is between a range of numbers, You have two options: Use 0 < x < 10 or 1 <= x < 10, which is classic notation, or use x in range(1, 10). Range takes only integer numbers not decimal
Ex32,33,34
In mixed lists, notice we have to use %r since we don't know what's in it.
Remember: ordinal == ordered, 1st; cardinal == cards at random, 0. in python programming, we use cardinal numbers. So, the indices of lists start with 0. If we want the third element, we translate this "ordinal" number to a "cardinal" number by subtracting 1
Ex38
Ex32,33
for-loop able to use a variable that isn't defined yet because the variable is defined by the for-loop when it starts, initializing it to the current element of the loop iteration, each time through.
A for-loop can only iterate (loop) "over" collections of things. A while-loop can do any kind of iteration (looping) you want. However, while-loops are harder to get right and you normally can get many things done with for-loops.
Ex35
ex36
Tips for Debugging
Do not use a "debugger." A debugger is like doing a full-body scan on a sick person. You do not get any specific useful information, and you find a whole lot of information that doesn't help and is just confusing.
The best way to debug a program is to use print to print out the values of variables at points in the program to see where they go wrong.
Make sure parts of your programs work as you work on them. Do not write massive files of code before you try to run them. Code a little, run a little, fix a little.
Rules for Loops
Use a while-loop only to loop forever, and that means probably never. This only applies to Python; other languages are different.
Use a for-loop for all other kinds of looping, especially if there is a fixed or limited number of things to loop over.
Rules for If-Statements
Every if-statement must have an else.
If this else should never run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.
Never nest if-statements more than two deep and always try to do them one deep.
Treat if-statements like paragraphs, where each if-elif-elsegrouping is like a set of sentences. Put blank lines before and after.
Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.