SlideShare uma empresa Scribd logo
1 de 33
Learn Python The Hard Way
• 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 -*- .
•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.
•You can’t name the identifies with the python reserved keywords
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
•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
•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
•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)
•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
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()) .
• 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
•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
• 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.
• 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)
• 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.
• 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.
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
Symbol Symbol name
and
or
not
!= Not equal
== equal
>= Greater than or equal
<= Less than or equal
True
False
•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.
•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
•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.
•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.
•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.
•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.
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.
•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
•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
•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
•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
•
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:
•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.

Mais conteúdo relacionado

Mais procurados

Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data sciencedeepak teja
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Edureka!
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Chariza Pladin
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonYi-Fan Chu
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python TutorialSimplilearn
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Edureka!
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlibPiyush rai
 

Mais procurados (20)

Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python programming
Python  programmingPython  programming
Python programming
 
Python basics
Python basicsPython basics
Python basics
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Python made easy
Python made easy Python made easy
Python made easy
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlib
 

Semelhante a Learn Python The Hard Way Presentation

Semelhante a Learn Python The Hard Way Presentation (20)

Python for katana
Python for katanaPython for katana
Python for katana
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python Basics
Python BasicsPython Basics
Python Basics
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Lenguaje Python
Lenguaje PythonLenguaje Python
Lenguaje Python
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
 
coolstuff.ppt
coolstuff.pptcoolstuff.ppt
coolstuff.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Introductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.pptIntroductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptx
 
ENGLISH PYTHON.ppt
ENGLISH PYTHON.pptENGLISH PYTHON.ppt
ENGLISH PYTHON.ppt
 
Python 01.pptx
Python 01.pptxPython 01.pptx
Python 01.pptx
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
 
Kavitha_python.ppt
Kavitha_python.pptKavitha_python.ppt
Kavitha_python.ppt
 

Último

Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsRussian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsMonica Sydney
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrHenryBriggs2
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfJOHNBEBONYAP1
 
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsMira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsPriya Reddy
 
Call girls Service in Ajman 0505086370 Ajman call girls
Call girls Service in Ajman 0505086370 Ajman call girlsCall girls Service in Ajman 0505086370 Ajman call girls
Call girls Service in Ajman 0505086370 Ajman call girlsMonica Sydney
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdfMatthew Sinclair
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirtrahman018755
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查ydyuyu
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsMonica Sydney
 
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...kumargunjan9515
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...kajalverma014
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...gajnagarg
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdfMatthew Sinclair
 
一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理F
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查ydyuyu
 
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime NagercoilNagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoilmeghakumariji156
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdfMatthew Sinclair
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查ydyuyu
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC
 

Último (20)

Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsRussian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
 
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsMira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
 
Call girls Service in Ajman 0505086370 Ajman call girls
Call girls Service in Ajman 0505086370 Ajman call girlsCall girls Service in Ajman 0505086370 Ajman call girls
Call girls Service in Ajman 0505086370 Ajman call girls
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
 
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
 
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime NagercoilNagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
 

Learn Python The Hard Way Presentation

  • 1. Learn Python The Hard Way
  • 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
  • 19. Symbol Symbol name and or not != Not equal == equal >= Greater than or equal <= Less than or equal True False
  • 20.
  • 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.

Notas do Editor

  1. ex1
  2. Ex4.py
  3. Ex1,ex2
  4. 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.
  5. 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
  6. Ex5.py Ex6.py
  7. Ex7.py Ex9.py
  8. Ex10.py
  9. 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
  10. 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()).
  11. 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
  12. 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.
  13. 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)
  14. 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.
  15. 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 +.
  16. Ex22 To use exists you must write “from os.path import exists” to import it from its module
  17. Ex22
  18. Ex22
  19. Ex22
  20. 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
  21. 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
  22. Ex38
  23. 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.
  24. Ex35
  25. 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.
  26. ex37
  27. ex37
  28. ex37
  29. ex37
  30. ex37
  31. ex37