id
int64
0
25.6k
text
stringlengths
0
4.59k
3,000
the single quote in howl' is fine because you've used double quotes to mark the beginning and end of the string multiline strings allow you to use newlines in strings without the \ escape character the expressions evaluate to the following' 'hello'hello'loworld the expressions evaluate to the following'hellotrue 'hello the expressions evaluate to the following['remember,''remember,''the''fifth''of''november ''there-can-be-only-one the rjust()ljust()and center(string methodsrespectively the lstrip(and rstrip(methods remove whitespace from the left and right ends of stringrespectively the re compile(function returns regex objects raw strings are used so that backslashes do not have to be escaped the search(method returns match objects the group(method returns strings of the matched text group is the entire matchgroup covers the first set of parenthesesand group covers the second set of parentheses periods and parentheses can be escaped with backslash\(and \ if the regex has no groupsa list of strings is returned if the regex has groupsa list of tuples of strings is returned the character signifies matching "eitherorbetween two groups the character can either mean "match zero or one of the preceding groupor be used to signify non-greedy matching the matches one or more the matches zero or more the { matches exactly three instances of the preceding group the { , matches between three and five instances the \ \wand \ shorthand character classes match single digitwordor space characterrespectively the \ \wand \ shorthand character classes match single character that is not digitwordor space characterrespectively appendix
3,001
match either [ - -zor [ - - passing re or re ignorecase as the second argument to re compile(will make the matching case insensitive the character normally matches any character except the newline character if re dotall is passed as the second argument to re compile()then the dot will also match newline characters the sub(call will return the string ' drummersx pipersfive ringsx hens the re verbose argument allows you to add whitespace and comments to the string passed to re compile( re compile( '^\ { , }(,\ { })*$'will create this regexbut other regex strings can produce similar regular expression re compile( '[ - ][ - ]*\swatanabe' re compile( '(alice|bob|carol)\ (eats|pets|throws)\ (apples|cats |baseballs)'re ignorecase no pyinputplus is third-party module and doesn' come with the python standard library this optionally makes your code shorter to typeyou can type pyip inputstr(instead of pyinputplus inputstr(the inputint(function returns an int valuewhile the inputfloat(function returns float value this is the difference between returning and call pyip inputint(min= max= list of regex strings that are either explicitly allowed or denied the function will raise retrylimitexception the function returns the value 'hello relative paths are relative to the current working directory absolute paths start with the root foldersuch as or :on windowsit evaluates to windowspath(' :/users/al'on other operating systemsit evaluates to different kind of path object but with the same path the expression ' :/users'alresults in an errorsince you can' use the operator to join two strings the os getcwd(function returns the current working directory the os chdir(function changes the current working directory answers to the practice questions
3,002
the folder is the current folderand is the parent folder :\bacon\eggs is the dir namewhile spam txt is the base name the string 'rfor read mode'wfor write modeand 'afor append mode an existing file opened in write mode is erased and completely overwritten the read(method returns the file' entire contents as single string value the readlines(method returns list of stringswhere each string is line from the file' contents shelf value resembles dictionary valueit has keys and valuesalong with keys(and values(methods that work similarly to the dictionary methods of the same names the shutil copy(function will copy single filewhile shutil copytree(will copy an entire folderalong with all its contents the shutil move(function is used for renaming files as well as moving them the send trash functions will move file or folder to the recycle binwhile shutil functions will permanently delete files and folders the zipfile zipfile(function is equivalent to the open(functionthe first argument is the filenameand the second argument is the mode to open the zip file in (readwriteor append assert spam > 'the spam variable is less than either assert eggs lower(!bacon lower('the eggs and bacon variables are the same!or assert eggs upper(!bacon upper()'the eggs and bacon variables are the same! assert false'this assertion always triggers to be able to call logging debug()you must have these two lines at the start of your programimport logging logging basicconfig(level=logging debugformat=%(asctime) %(levelname) %(message) ' appendix
3,003
to be able to send logging messages to file named programlog txt with logging debug()you must have these two lines at the start of your programimport logging logging basicconfig(filename='programlog txt'level=logging debugformat=%(asctime) %(levelname) %(message) ' debuginfowarningerrorand critical logging disable(logging criticalyou can disable logging messages without removing the logging function calls you can selectively disable lower-level logging messages you can create logging messages logging messages provides timestamp the step in button will move the debugger into function call the step over button will quickly execute the function call without stepping into it the step out button will quickly execute the rest of the code until it steps out of the function it currently is in after you click continuethe debugger will stop when it has reached the end of the program or line with breakpoint breakpoint is setting on line of code that causes the debugger to pause when the program execution reaches the line to set breakpoint in muclick the line number to make red dot appear next to it the webbrowser module has an open(method that will launch web browser to specific urland that' it the requests module can download files and pages from the web the beautifulsoup module parses html finallythe selenium module can launch and control browser the requests get(function returns response objectwhich has text attribute that contains the downloaded content as string the raise_for_status(method raises an exception if the download had problems and does nothing if the download succeeded the status_code attribute of the response object contains the http status code after opening the new file on your computer in 'wb"write binarymodeuse for loop that iterates over the response object' iter_content(method to write out chunks to the file here' an examplesavefile open('filename html''wb'for chunk in res iter_content( )savefile write(chunkanswers to the practice questions
3,004
brings up the developer tools in chrome pressing ctrlshift- (on windows and linuxor option- (on os xbrings up the developer tools in firefox right-click the element in the page and select inspect element from the menu '#main highlight 'div div 'button[value="favorite"] spam gettext( linkelem attrs the selenium module is imported with from selenium import webdriver the find_element_methods return the first matching element as webelement object the find_elements_methods return list of all matching elements as webelement objects the click(and send_keys(methods simulate mouse clicks and keyboard keysrespectively calling the submit(method on any element within form submits the form the forward()back()and refresh(webdriver object methods simulate these browser buttons the openpyxl load_workbook(function returns workbook object the sheetnames attribute contains worksheet object run wb['sheet 'use wb active sheet[' 'value or sheet cell(row= column= value sheet[' ''helloor sheet cell(row= column= value 'hellocell row and cell column they hold the highest column and row with values in the sheetrespectivelyas integer values openpyxl cell column_index_from_string(' ' openpyxl cell get_column_letter( sheet[' ':' ' wb save('example xlsx' formula is set the same way as any value set the cell' value attribute to string of the formula text remember that formulas begin with the sign when calling load_workbook()pass true for the data_only keyword argument appendix
3,005
sheet column_dimensions[' 'hidden true freeze panes are rows and columns that will always appear on the screen they are useful for headers openpyxl chart reference()openpyxl chart series()openpyxl chart barchart()chartobj append(seriesobj)and add_chart( to access google sheetsyou need credentials filea token file for google sheetsand token file for google drive ezsheets has ezsheets spreadsheet and ezsheets sheet objects call the downloadasexcel(spreadsheet method call the ezsheets upload(function and pass the filename of the excel file access ss['students'][' ' call ezsheets getcolumnletterof( access the rowcount and columncount properties of the sheet object call the delete(sheet method this is only permanent if you pass the permanent=true keyword argument the createspreadsheet(function and createsheet(spreadsheet method will create spreadsheet and sheet objectsrespectively ezsheets will throttle your method calls file object returned from open(read-binary ('rb'for pdffilereader(and write-binary ('wb'for pdffilewriter( calling getpage( will return page object for page since page is the first page the numpages variable stores an integer of the number of pages in the pdffilereader object call decrypt('swordfish'the rotateclockwise(and rotatecounterclockwise(methods the degrees to rotate is passed as an integer argument docx document('demo docx' document contains multiple paragraphs paragraph begins on new line and contains multiple runs runs are contiguous groups of characters within paragraph use doc paragraphs run object has these variables (not paragraphanswers to the practice questions
3,006
boldedno matter what the style' bold setting is none will make the run object just use the style' bold setting call the docx document(function doc add_paragraph('hello there!' the integers and in excelspreadsheets can have values of data types other than stringscells can have different fontssizesor color settingscells can have varying widths and heightsadjacent cells can be mergedand you can embed images and charts you pass file objectobtained from call to open(file objects need to be opened in read-binary ('rb'for reader objects and write-binary ('wb'for writer objects the writerow(method the delimiter argument changes the string used to separate cells in row the lineterminator argument changes the string used to separate rows json loads(json dumps( reference moment that many date and time programs use the moment is january utc time time( time sleep( it returns the closest integer to the argument passed for exampleround( returns datetime object represents specific moment in time timedelta object represents duration of time run datetime datetime( weekday()which returns this means mondayas the datetime module uses for monday for tuesdayand so on up to for sunday threadobj threading thread(target=spamthreadobj start( appendix make sure that code running in one thread does not read or write the same variables as code running in another thread
3,007
smtp and imaprespectively smtplib smtp()smtpobj ehlo()smptobj starttls()and smtpobj login(imapclient imapclient(and imapobj login( list of strings of imap keywordssuch as 'before ''from 'or 'seen assign the variable imaplib _maxline large integer valuesuch as the pyzmail module reads downloaded emails the credentials json and token json files tell the ezgmail module which google account to use when accessing gmail message represents single emailwhile back-and-forth conversation involving multiple emails is thread include the 'has:attachmenttext in the string you pass to search( you will need the twilio account sid numberthe authentication token numberand your twilio phone number an rgba value is tuple of integerseach ranging from to the four integers correspond to the amount of redgreenblueand alpha (transparencyin the color function call to imagecolor getcolor('cornflowerblue''rgba'will return ( )the rgba value for that color box tuple is tuple value of four integersthe left-edge -coordinatethe top-edge -coordinatethe widthand the heightrespectively image open('zophie png' call the imageobj save('new_filename png'method of the image object the imagedraw module contains code to draw on images imagedraw objects have shape-drawing methods such as point()line()or rectangle(they are returned by passing the image object to the imagedraw draw(function imageobj size is tuple of two integersthe width and the height imageobj crop(( )notice that you are passing box tuple to crop()not four separate integer arguments move the mouse to the upper-left corner of the screenthat isthe ( coordinates pyautogui size(returns tuple with two integersfor the width and height of the screen answers to the practice questions
3,008
pyautogui position(returns tuple with two integersfor the xand -coordinates of the mouse cursor the moveto(function moves the mouse to absolute coordinates on the screenwhile the move(function moves the mouse relative to the mouse' current position pyautogui dragto(and pyautogui drag(pyautogui typewrite('helloworld!'either pass list of keyboard key strings to pyautogui write((such as 'left'or pass single keyboard key string to pyautogui press( pyautogui screenshot('screenshot png' pyautogui pause you should use selenium for controlling web browser instead of pyautogui pyautogui clicks and types blindly and cannot easily find out if it' clicking and typing into the correct windows unexpected pop-up windows or errors can throw the script off track and require you to shut it down call the pyautogui getwindowswithtitle('notepad'function run pyatuogui getwindowswithtitle('firefox')and then run activate( appendix
3,009
symbols (assignmentoperator +(augmented addition assignmentoperator /(augmented division assignmentoperator %(augmented modulus assignmentoperator *(augmented multiplication assignmentoperator -(augmented subtraction assignmentoperator (backslashescape character - line continuation character {(bracesin dictionaries greedy vs nongreedy matching matching specific repetitions with - (caret symbolmatching beginning of string negative character classes (colon) (dollar sign) - (dot character) - (dot-star character) (double quotes) =(equal tooperator *(exponentoperator (forward slash) - division operator (greater thanoperator >(greater than or equal tooperator (hash character) /(integer division/floored quotientoperator (less thanoperator <(less than or equal tooperator (modulus/remainderoperator (multiplicationoperator !(not equal tooperator ((parentheses) (pipe character) (plus signaddition operator concatenation operator (question mark) - (single quote) [(square brackets) (star character) (subtraction operator) ''(triple quotes) (underscore) absolute path abspath(function (os path module) activate(function (pyautogui) active sheet add_break(method (docx) add_heading(method (docx) add_paragraph(method (docx) add_picture(method (docx) add_run(method (docx) adding logo project - adding bullets to wiki markup project - addition operator (+) addpage(method (pypdf ) - algebraic chess notation alpha transparency and binary operator api (application programming interface) append(list method arguments function keyword argv variable (sys module) asciibetical order
3,010
assignment (=operator assignment statement asterisk attributes augmented assignment operators automatic form filler project - backing up folder project - back(method (selenium) backslash (\) - barchart(function (openpyxl) - basename(function (os path module) - basicconfig(function (logging module) beautiful soup see also bs module binary files binary operators and and comparison operators - not or bitwise or operator blocking execution blocks of code boolean data type binary operators - "truthyand "falseyvalues using binary and comparison operators - box tuple braces ({}in dictionaries greedy vs nongreedy matching matching specific repetitions with - break statement overview using in for loop browseropening using webbrowser module bs module creating object from html finding element with select(method index getting attribute overview built-in functions calling functions call stack - camelcase caret symbol (^matching beginning of string negative character classes cascading style sheets (css) case sensitivity cell data type (openpyxl) cellsin excel spreadsheets accessing writing values to center(string method - chaining method calls character classes creating negative shorthand character styles chart objects chdir(function (os module) chess chromedeveloper tools in clear(method openpyxl selenium click(function (pyautogui) clicking the mouse click(method (selenium) clipboardcopying and pasting - close(file method cm(method (openpyxl) colon (:) color valuesrgba - column_index_from_string(function (openpyxl) columnsin excel spreadsheets setting height and width of slicing worksheet objects to get cell objects combining select pages from many pdfs project - comma-delimited items
3,011
comma-separated values (csvsee csv (comma-separated valuescomments multiline overview comparison operators - equal to (==) greater than (>) greater than or equal to (>=) less than (<) less than or equal to (<=) not equal to (!=) compile(function (re module) compressed files creating zip files extracting zip files - overview reading zip files computer screen coordinates of resolution of concatenation operator (+lists strings concurrency issues conditions continue statement overview using in for loop convertaddress(function (ezsheets) conway' game of life project - coordinated universal time (utc) coordinates of computer screen of an image - copy(function copy module pyperclip - copy(method (pillow) copy module copy(function deepcopy(function copyto(function (ezsheets) copytree(function (shutil module) countdown(function (pyautogui) countdown project cprofile module crashesprograms create(method (twilio) createsheet(function (ezsheets) create_sheet(method (openpyxl) createspreadsheet(function (ezsheets) critical(function (logging module) critical logging level cron crop(method (pillow) css (cascading style sheets) csv (comma-separated valuesdefined delimiter for format overview line terminator for module reader objects reading data in loop writer objects current working directory cwd(method (pathlib module) \ character class \ character class data types booleans defined dictionaries floating-point numbers integers lists mutable vs immutable - none value strings tuples date arithmetic datetime module datetime(function datetime objects fromtimestamp(function now(function timedelta(function total_seconds(method debug(function (logging module) debug logging level index
3,012
assertions - defined getting traceback as string - logging in mu - raising exceptions decimal numbers see floating-point numbers decode(method (imaplib module) decrypt(function (pypdf ) deduplicate deepcopy(function (copy module) def statement delete_messages(method (imaplib module) deleting files/folders permanently using send trash module delimiter del statement dictionaries get(method items(method keys(method lists vs nesting overview - setdefault(method values(method directories see folders dirname(function (os path module) disable(function (logging module) division (/operator document objects (docx) docx module add_break(method add_heading(method add_paragraph(method add_picture(method add_run(method document objects font(function installing linechart(function paragraph objects dollar sign ($) - dot character ) - dot-dot folder - dot folder - dot-star character *) index doubleclick(function (pyautogui) double quotes (") downloadasexcel(method (ezsheets) downloadashtml(method (ezsheets) downloadasods(method (ezsheets) downloadaspdf(method (ezsheets) downloadastsv(method (ezsheets) downloading files from web web pages - downloading xkcd comics project - drag(function (pyautogui) dragging the mouse dragto(function (pyautogui) draw(function (pillow) drawing on images ellipses lines points polygons rectangles text - dumps(function (json module) ehlo(method (smtplib module) elementshtml elif statement ellipse(method (pillow) else statements emails deleting disconnecting from server fetching imap marking message as read searching sending smtp encodingsunicode encrypt(function (pypdf ) endswith(string method enumerate(function epoch timestamp equal to (==operator
3,013
extracttext(method (pypdf ) error logging level errors crashes and help forxxxiv escape characters - evaluatation excel spreadsheets application support charts in column width converting between column letters and numbers creating documents creating worksheets deleting worksheets font styles formulas in freezing panes - getting cell values getting rows and columns getting worksheet names merging and unmerging cells opening documents openpyxl overview reading files row height saving workbooks updating workbooks vs writing values to cells exception objects exceptions assertions and - getting traceback as string - handling raising - except statement - execution defined pausing until specific time terminating exists(function (os path module) exit codes exit(function (sys module) exponent (**operator expressions expunge(method (imaplib module) extensionfile ezgmail - ezgmail module init(function recent(function search(function send(function summary(function unread(function ezsheets credentials and token files installing quotas revoking credentials sheet objects - spreadsheet objects - ezsheets module convertaddress(function copyto(function createsheet(function createspreadsheet(function downloadasexcel(method downloadashtml(method downloadasods(method downloadaspdf(method downloadastsv(method getcolumn(method getcolumnletterof(function getcolumnnumberof(function getcolumns(method getrow(method getrows(method listspreadsheets(function spreadsheet(function updatecolumn(function updatecolumns(function updaterow(function updaterows(function upload(function factory(function (pyzmail) failsafeexception exceptions false boolean value "falseyvalues fetching current weather project - fetch(method (imaplib module) file editor index
3,014
absolute vs relative paths backslash vs forward slash - compressed files creating directories current working directory opening files overview paths - plaintext vs binary files reading files renaming files - send trash module shelve module shutil module walking directory trees writing files filename file objects findall(method (re module) find_element_by_*(methods (selenium) find_elements_by_*(methods (selenium) firefoxdeveloper tools in firefox(function (selenium) floating point numbers float(function integer equivalence overview rounding flow control blocks of code break statements conditions continue statements elif statements else statements for loops if statements overview while loops folders absolute paths in absolute vs relative paths backslash vs forward slash - copying creating current working directory defined index deleting permanently deleting using send trash module file sizes folder contents moving path validity root renaming walking font data type font(function (docx) font stylesin excel spreadsheets form filler project formulas (excel) for statements forward slash (/) - division operator freeze panes in excel spreadsheets fromtimestamp(function (datetime module) functions see also names of individual functions arguments as "black box" built-in def statements exception handling keyword arguments none value and overview parameters return values gausscarl friedrich generating random quizzes project - getactivewindow(function (pyautogui) get_addresses(method (pyzmail) getallwindows(function (pyautogui) getcolumnletterof(function (ezsheets) getcolumn(method (ezsheets) getcolumnnumberof(function (ezsheets) getcolumns(method (ezsheets) getcwd(function (os module) get(dictionary method
3,015
getpage(method (pypdf ) get_payload(method (pyzmail) getpixel(function (pillow) getrow(method (ezsheets) getrows(method (ezsheets) get_sheet_by_name(method (openpyxl) get_sheet_names(method (openpyxl) getsize(function (os path module) get_subject(method (pyzmail) getwindowsat(function (pyautogui) getwindowswithtitle(function (pyautogui) gif format global scope global statement global variable gmail google maps graphical user interface (guisee gui (graphical user interfacegreater than (>operator greater than or equal to (>=operator greedy matching group(method (re module) groupsregex guess the number program - gui (graphical user interfacecontrolling the keyboard hotkey combinations key names pressing and releasing sending string from keyboard controlling the mouse clicking the mouse dragging the mouse - moving the mouse scrolling the mouse - determining mouse position - image recognition installing pyautogui module overview screenshots stopping program hash character (#) headingsword document helpwith programming asking on forumsxxxiii-xxxix onlinexxxvi-xxxviii hotkey combinations hotkey(function (pyautogui) how to keep an idiot busy for hours project - html (hypertext markup languageattributes browser developer tools and finding elements learning resources overview viewing page source - idle (integrated development and learning environment)xxxv if statements images adding logo to - box tuples color values in - coordinates in - copying and pasting in cropping drawing on ellipses lines points polygons rectangles text - flipping - opening with pillow pixel manipulation recognition of resizing rgba color values - rotating - transparent pixels imap (internet message access protocoldefined deleting messages disconnecting from server index
3,016
protocol(continuedfetching messages folders logging into server searching messages imapclient(function (imaplib module) imapclient module imaplib module decode(method delete_messages(method expunge(method fetch(method imapclient(function list_folders(method login(method logout(method search(method select_folder(method immutable data types importing modules import statement inches(method (openpyxl) indentation indexerror exception indexes - for dictionaries see keys for lists for strings negative index(method infinite loop info(function (logging module) info logging level init(function (ezgmail) in operator in place modification inputbool(function (pyinputplus) inputchoice(function (pyinputplus) inputcustom(function (pyinputplus) inputdatetime(function (pyinputplus) inputemail(function (pyinputplus) inputfilepath(function (pyinputplus) inputfloat(function (pyinputplus) input(function index inputint(function (pyinputplus) inputmenu(function (pyinputplus) inputnum(function (pyinputplus) inputpassword(function (pyinputplus) inputstr(function (pyinputplus) input validation inputyesno(function (pyinputplus) insert(list method integer division/floored quotient (//operator integers floating-point equivalence int(function overview interactive development environment (idle)xxxv interactive shellxxxv-xxxvi internet explorerdeveloper tools in internet message access protocol (imapsee imap (internet message access protocolint(function isabs(function (os path module) isalnum(string method isalpha(string method isdecimal(string method isdir(function (os path module) isencrypted(method (pypdf ) isfile(function (os path module) islower(string method isspace(string method istitle(string method isupper(string method - items(dictionary method iteration iter_content(method (requests) - join(function (os path module) join(method (threading module) join(string method jpeg format json (javascript object notation) json module dumps(function loads(function
3,017
"just text memodule project - keyboard hotkey combinations key names pressing and releasing sending string from keyboard keyboardinterrupt exception keydown(function (pyautogui) keysdictionary keys(dictionary method keyup(function (pyautogui) key-value pair keyword arguments launchd launching programs opening files with default applications opening websites overview passing command line arguments running python scripts scheduling lazy matching see non-greedy matching len(function less than (<operator less than or equal to (<=operator libreoffice line breaksword documents linechart(function (docx) line continuation character line(method (pillow) line terminator linked stylesword documents linux backslash vs forward slash - cron installing pythonxxi installing third-party modules - starting idlexxxiii starting muxxxii listdir(function (os module) list_folders(method (imaplib module) list(function list-like lists append(method changing values using index concatenation dictionaries vs finding number of values using len() index(method insert(method multiple assignment trick mutable vs immutable data types - negative indexes nesting overview remove(method replication sort(method using with for loops listspreadsheets(function (ezsheets) ljust(string method - loads(function (json module) load_workbook(function (openpyxl) local scope local variable locateallonscreen(function (pyautogui) locateonscreen(function (pyautogui) logging levels critical debug error info warning logging module basicconfig(function critical(function debug(function disable(function error(function info(function warning(function login(method imaplib module smtplib module index
3,018
loops lower(string method - lstrip(string method macos backslash vs forward slash - installing pythonxxxiiixxxiv installing third-party modules - launchd opening files with default applications open program pip tool on - running python programs starting idlexxxv starting muxxxv terminal window - magic ball example program makedirs(function (os module) mapit py with the webbrowser module project - matching greedy non-greedy math operators addition (+) division (/) exponent (**) integer division/floored quotient (//) modulus/remainder (%) multiplication (*) order of operations maximize(function (pyautogui) merge_cells(method (openpyxl) methods see also names of individual methods chaining calls defined dictionary - list - string - microsoft windows see windows (operating systemmiddleclick(function (pyautogui) minimize(function (pyautogui) index mkdir(method (pathlib module) modules see also names of individual modules importing third-partyinstalling - modulus/remainder (%operator monty pythonxxx mouse clicking determining position - dragging - moving scrolling - mousedown(function (pyautogui) mouseup(function (pyautogui) move(function pyautogui shutil module moveto(function (pyautogui) moving files/folders multi-clipboard multi-clipboard automatic messages project - updatable multi-clipboard - multiline comments multiline strings - multiple assignment trick multiplication operator (*) multiplication quiz project - multithreaded xkcd downloader project - multithreading concurrency issues join(method overview passing arguments to threads start(method thread(function mutable data types nameerror exception namelist(method (zipfile module) negative character classes negative indexes nested dictionaries and lists nested for loops new(method (image module) none value
3,019
not binary operator not in operator now(function (datetime module) dirname(function exists(function isabs(function isdir(function isfile(function join(function split(function open(function webbrowser module open(method (pillow) openoffice open program openpyxl openpyxl module barchart(function - clear(method cm(method column_index_from_string(function create_sheet(method get_sheet_by_name(method get_sheet_names(method inches(method load_workbook(function merge_cells(method reference(function remove_sheet(method unmerge_cells(method operators see also names of individual operators augmented assignment binary boolean comparison defined math unary or binary operator order of operations origin coordinate os module chdir(function getcwd(function listdir(function makedirs(function walk(function rmdir(function unlink(function os path module abspath(function basename(function - page data type (pypdf ) paragraph objects (docx) paragraph styles parametersfunctions parentheses (()) parsing partition(string method passing arguments paste(function (pyperclip) paste(method (pillow) pathlib module cwd(method mkdir(method paths absolute vs relative backslash vs forward slash - current working directory overview pause variable (pyautogui) pdffilereader data type pdf (portable document formatfiles adding pages to combining select page from many pdfs project - copying pages in creating decrypting encrypting extracting text from format overview overlaying pages rotating pages pdffilewriter data type pformat(function (pprint module) phone number and email address extractor project - pig latin project - pillow copying and pasting in images cropping images index
3,020
drawing on images ellipses lines points polygons rectangles text - flipping images - module opening images pixel manipulation resizing images rgba color values - rotating images - transparent pixels pillow module copy(method crop(method draw(function ellipse(method getpixel(function line(method open(method paste(method point(method polygon(method putpixel(function rectangle(method resize(method - rotate(method text(method textsize(method transpose(method truetype(function pipe (|character pip tool - pixel pixelmatchescolor(function (pyautogui) plaintext files plus character (+) png format point point(method (pillow) poll(method (threading module) polygon(method (pillow) popen(function (subprocess module) portable document format (pdffiles see pdf (portable document formatfiles index position(function (pyautogui) pprint module pformat(function pprint(function precedence press(function (pyautogui) print(function processes defined opening files with default applications passing command line arguments to popen(function (subprocess module) profiling code program execution projects adding logo - adding bullets to wiki markup - automatic form filler - backing up folder - combining select pages from many pdfs - conway' game of life - downloading xkcd comics - fetching current weather - generating random quizzes - guess the number - how to keep an idiot busy for hours - "just text memodule - mapit py with the webbrowser module - multi-clipboard automatic messages - multiplication quiz - multithreaded xkcd downloader - phone number and email address extractor - pig latin - reading data from spreadsheet - removing the header from csv files - renaming files - rockpaperscissors -
3,021
emails - simple countdown program - super stopwatch - updatable multi-clipboard - updating spreadsheet - zigzag - putpixel(function (pillow) pyautogui failsafeexception exceptions functions - overview pyautogui module activate(function click(function countdown(function doubleclick(function drag(function dragto(function getactivewindow(function getallwindows(function getwindowsat(function getwindowswithtitle(function hotkey(function keydown(function - keyup(function - locateallonscreen(function locateonscreen(function maximize(function middleclick(function minimize(function mousedown(function mouseup(function move(function moveto(function pixelmatchescolor(function position(function press(function restore(function rightclick(function screenshot(function scroll(function size(function write(function pyinputplus pyinputplus module inputbool(function inputchoice(function inputcustom(function inputdatetime(function inputemail(function inputfilepath(function inputfloat(function inputint(function inputmenu(function inputnum(function inputpassword(function inputstr(function inputyesno(function pypdf pypdf module addpage(method - decrypt(function encrypt(function extracttext(method getpage(method isencrypted(method rotateclockwise(method rotatecounterclockwise(method pyperclip pyperclip module copy(function paste(function python downloadingxxxiii-xxxiv helpxxxvi-xxxix installingxxxiv interactive shellxxxv-xxxvi interpreterxxxiv overviewxxx starting idlexxxv starting muxxxiv-xxxv python-docx module pyzmail pyzmail module get_addresses(method get_payload(method get_subject(method factory(function question mark (?) - quit(method (smtplib module) raise_for_status(method (requests module) raise statement index
3,022
randint(function sample(function shuffle(function range(function raw strings read(method reader(method (csv module) reading data from spreadsheet project - readlines(method recent(function (ezgmail) rectangle(method (pillow) redditxxxviii reference(function (openpyxl) references refresh(method (selenium) regular expressions beginning of string matches case sensitivity character classes defined dot-star character *) end of string matches extracting phone numbers and email addresses - findall(method finding patterns without greedy matching group(method groups html and matching specific repetitions - multiple argument for compile(function non-greedy matching one or more matches optional matching spreading over multiple lines substituting strings using symbols using parentheses using pipe characters verbose mode wildcard character zero or more matches relational operators relative path relpath(function remainder/modulus (%operator index re module compile(function findall(method group(method search(method sub(method remove(method remove_sheet(method (openpyxl) removing the header from csv files project - renaming files/folders - replication of lists string requests module get(function raise_for_status(method resize(method (pillow) - resolution of computer screen response objects (requests) restore(function (pyautogui) return statement return valuesfunction reverse keyword argument rgba color values - rightclick(function (pyautogui) rjust(method - rmdir(function (os module) rmtree(function (shutil module) rockpaperscissors - rotateclockwise(method (pypdf rotatecounterclockwise(method (pypdf rotate(method (pillow rotating images - rounding numbers rowsin excel spreadsheets rstrip(string method run objects \ character class \ character class % directive safarideveloper tools in sample(function (random module) save()method document workbook
3,023
screenshot(function (pyautogui) screenshots analyzing getting scroll(function (pyautogui) search(function (ezgmail) search(method imaplib module re module select_folder(method (imaplib module) selenium selenium module back(method clear(method click(method firefox(function refresh(method send_keys(method submit(method send(function (ezgmail) sending member dues reminder emails project - send_keys(method (selenium) sendmail(method (smtplib module series objects setdefault(dictionary method shebang line sheet shelve module short message service (smssee sms (short message serviceshuffle(function (random module) shutil module deleting files/folders moving files/folders overview renaming files/folders - sidtwilio account simple countdown program project - simple mail transfer protocol (smtp) single quote (') single-threaded program size(function (pyautogui) sleep(function slices getting sublists with getting substrings with sms (short message servicegateway service sending messages - twilio service - smtp (simple mail transfer protocol) smtpauthenticationerror smtp(function (smtplib module smtp_ssl(function (smtplib module) sort(method sound filesplaying source codexxx split(function (os path module) split(string method spreadsheet(function spreadsheets see excel spreadsheets square brackets ([]) stack overflowxxxviii standard library star character (*) start(method (threading module) start program startswith(string method starttls(method (smtplib module) step argument strftime(function (time module) strings center(method - concatenation copying and pasting - defined double quotes for endswith(method escape characters - extracting pdf text as indexes for interpolation isalnum(method isalpha(method isdecimal(method islower(method isspace(method istitle(method isupper(method join(method literals ljust(method - lower(method index
3,024
lstrip(method multiline partition(method raw replication rjust(method - rstrip(method slicing split(method startswith(method strip(method upper(method str(function strip(string method strptime(function sub(method (re module) submit(method (selenium) subtraction operator (-) sudokuxxx summary(function (ezgmail) super stopwatch project - syntax error can' assign to keyword eol while scanning string literal invalid syntax sys module argv variable exit(function tag objects tagshtml task scheduler text(method (pillow) textsize(method (pillow) threading module join(method poll(method start(method thread object - throwaway codexxviii tic-tac-toe timedelta(function (datetime module) time module overview sleep(function super stopwatch project - time(function index tls encryption - top-level domain total_seconds(method (datetime module) transpose(method (pillow) triple quotes (''') true boolean value truetype(function (pillow) truth tables - "truthyvalues try statement tuple data type tuple(function twilio twilio module create(method twiliorestclient(function type(function ubuntu installing pythonxxxiv installing third-party modules - pip tool on - popen(function running python programs - starting idlexxxv starting muxxxv terminal window - unary operators underscore ( ) unicode encodings unix epoch unlink(function (os module) unmerge_cells(method (openpyxl) unread(function (ezgmail) updatecolumn(function (ezsheets) updatecolumns(function (ezsheets) updaterow(function (ezsheets) updaterows(function (ezsheets) updatable multi-clipboard - updating spreadsheet project - upload(function (ezsheets) upper(string method - utc (coordinated universal time)
3,025
valueerror valuesdefined values(dictionary method variables assignment statements defined global initialization local naming overwriting references verbose moderegular expressions volumes \ character class \ character class wait(function (subprocess module) walk(function (os module) warning(function (logging module) warning logging level weather datafetching web scraping browser developer tools bs module - downloading files images - pages - and google maps project html finding elements learning resources overview - viewing page source - overview requests module selenium module clicking buttons following links installing sending special keystrokes submitting forms using firefox with webbrowser module webdriver objects (selenium) webelement objects (selenium) websitesopening from script while loop overview infinite wildcard character (*) windows (operating systembackslash vs forward slash - installing pythonxxxiii-xxxiv installing third-party modules - opening files with default applications pip tool on - running python programs - starting idlexxxv starting muxxxv task scheduler terminal window - workbook worksheet write(function (pyautogui) write(method writerow(method (csv modules) xkcd comics downloading project - multithreaded downloader project - zigzag project - zipfile module adding to zip files creating zip files extracting zip files namelist(method overview reading zip files zipfile objects zipinfo objects index
3,026
oop in python python libraries requestspython requests module making get request making post requests pandaspython library pandas indexing dataframes pygame beautiful soupweb scraping with beautiful soup iii
3,027
oop in python introduction programming languages are emerging constantlyand so are different methodologies object-oriented programming is one such methodology that has become quite popular over past few years this talks about the features of python programming language that makes it an object-oriented programming language language programming classification scheme python can be characterized under object-oriented programming methodologies the following image shows the characteristics of various programming languages observe the features of python that makes it object-oriented
3,028
what is object oriented programmingobject oriented means directed towards objects in other wordsit means functionally directed towards modelling objects this is one of the many techniques used for modelling complex systems by describing collection of interacting objects via their data and behavior pythonan object oriented programming (oop)is way of programming that focuses on using objects and classes to design and build applications major pillars of object oriented programming (oopare inheritancepolymorphismabstractionad encapsulation object oriented analysis(ooais the process of examining problemsystem or task and identifying the objects and interactions between them why to choose object oriented programmingpython was designed with an object-oriented approach oop offers the following advantagesprovides clear program structurewhich makes it easy to map real world problems and their solutions facilitates easy maintenance and modification of existing code enhances program modularity because each object exists independently and new features can be added easily without disturbing the existing ones presents good framework for code libraries where supplied components can be easily adapted and modified by the programmer imparts code reusability procedural vs object oriented programming procedural based programming is derived from structural programming based on the concepts of functions/procedure/routines it is easy to access and change the data in procedural oriented programming on the other handobject oriented programming (oopallows decomposition of problem into number of units called objects and then build the data and functions around these objects it emphasis more on the data than procedure or functions also in oopdata is hidden and cannot be accessed by external procedure
3,029
the table in the following image shows the major differences between pop and oop approach principles of object oriented programming object oriented programming (oopis based on the concept of objects rather than actionsand data rather than logic in order for programming language to be objectorientedit should have mechanism to enable working with classes and objects as well as the implementation and usage of the fundamental object-oriented principles and concepts namely inheritanceabstractionencapsulation and polymorphism
3,030
let us understand each of the pillars of object-oriented programming in briefencapsulation this property hides unnecessary details and makes it easier to manage the program structure each object' implementation and state are hidden behind well-defined boundaries and that provides clean and simple interface for working with them one way to accomplish this is by making the data private inheritance inheritancealso called generalizationallows us to capture hierarchal relationship between classes and objects for instancea 'fruitis generalization of 'orangeinheritance is very useful from code reuse perspective abstraction this property allows us to hide the details and expose only the essential features of concept or object for examplea person driving scooter knows that on pressing hornsound is emittedbut he has no idea about how the sound is actually generated on pressing the horn polymorphism poly-morphism means many forms that isa thing or action is present in different forms or ways one good example of polymorphism is constructor overloading in classes
3,031
object-oriented python the heart of python programming is object and oophowever you need not restrict yourself to use the oop by organizing your code into classes oop adds to the whole design philosophy of python and encourages clean and pragmatic way to programming oop also enables in writing bigger and complex programs modules vs classes and objects modules are like "dictionarieswhen working on modulesnote the following pointsa python module is package to encapsulate reusable code modules reside in folder with __init__ py file on it modules contain functions and classes modules are imported using the import keyword recall that dictionary is key-value pair that means if you have dictionary with key employeid and you want to retrieve itthen you will have to use the following lines of codeemployee {"employeid""employee unique identity!"print (employee ['employeid]you will have to work on modules with the following processa module is python file with some functions or variables in it import the file you need nowyou can access the functions or variables in that module with the (dotoperator consider module named employee py with function in it called employee the code of the function is given belowthis goes in employee py def employeid()print ("employee unique identity!"now import the module and then access the function employeidimport employee employee employeid(
3,032
you can insert variable in it named ageas showndef employeid()print ("employee unique identity!"just variable age "employee age is **nowaccess that variable in the following wayimport employee employee employeid(print(employee agenowlet' compare this to dictionaryemployee['employeid'get employeid from employee employee employeid(get employeid from the module employee age get access to variable notice that there is common pattern in pythontake key value style container get something out of it by the key' name when comparing module with dictionaryboth are similarexcept with the followingin the case of the dictionarythe key is string and the syntax is [keyin the case of the modulethe key is an identifierand the syntax is key classes are like modules module is specialized dictionary that can store python code so you can get to it with the operator class is way to take grouping of functions and data and place them inside container so you can access them with the 'operator if you have to create class similar to the employee moduleyou can do it using the following codeclass employee(object)def __init__(self)self age "employee age is ##def employeid(self)print ("this is just employee unique identity"
3,033
noteclasses are preferred over modules because you can reuse them as they are and without much interference while with modulesyou have only one with the entire program objects are like mini-imports class is like mini-module and you can import in similar way as you do for classesusing the concept called instantiate note that when you instantiate classyou get an object you can instantiate an objectsimilar to calling class like functionas shownthis_obj employee(get employeid from the class print(this_obj ageinstantiatethis_obj employeid(get variable age you can do this in any of the following three waysdictionary style employee['employeid'module style employee employeid(print(employee ageclass style this_obj employee(this_obj employeid(print(this_obj age
3,034
oop in python environment setup this will explain in detail about setting up the python environment on your local computer prerequisites and toolkits before you proceed with learning further on pythonwe suggest you to check whether the following prerequisites are metlatest version of python is installed on your computer an ide or text editor is installed you have basic familiarity to write and debug in pythonthat is you can do the following in pythono able to write and run python programs debug programs and diagnose errors work with basic data types write for loopswhile loopsand if statements code functions if you don' have any programming language experienceyou can find lots of beginner tutorials in python on tutorialspoint installing python the following steps show you in detail how to install python on your local computerstep go to the official python website downloads menu and choose the latest or any stable version of your choice
3,035
step save the python installer exe file that you're downloading and once you have downloaded itopen it click on run and choose next option by default and finish the installation step after you have installedyou should now see the python menu as shown in the image below start the program by choosing idle (python guithis will start the python shell type in simple commands to check the installation
3,036
choosing an ide an integrated development environment is text editor geared towards software development you will have to install an ide to control the flow of your programming and to group projects together when working on python here are some of ides avaialable online you can choose one at your convenience pycharm ide komodo ide eric python ide noteeclipse ide is mostly used in javahowever it has python plugin pycharm pycharmthe cross-platform ide is one of the most popular ide currently available it provides coding assistance and analysis with code completionproject and code navigationintegrated unit testingversion control integrationdebugging and much more download link languages supportedpythonhtmlcssjavascriptcoffee scripttypescriptcython,angularjsnode jstemplate languages screenshot why to choosepycharm offers the following features and benefits for its userscross platform ide compatible with windowslinuxand mac os includes django ideplus css and javascript support includes thousands of pluginsintegrated terminal and version control integrates with gitsvn and mercurial
3,037
offers intelligent editing tools for python easy integration with virtualenvdocker and vagrant simple navigation and search features code analysis and refactoring configurable injections supports tons of python libraries contains templates and javascript debuggers includes python/django debuggers works with google app engineadditional frameworks and libraries has customizable uivim emulation available komodo ide it is polyglot ide which supports languages and basically for dynamic languages such as pythonphp and ruby it is commercial ide available for days free trial with full functionality activestate is the software company managing the development of the komodo ide it also offers trimmed version of komodo known as komodo edit for simple programming tasks this ide contains all kinds of features from most basic to advanced level if you are student or freelancerthen you can buy it almost half of the actual price howeverit' completely free for teachers and professors from recognized institutions and universities it got all the features you need for web and mobile developmentincluding support for all your languages and frameworks download link the download links for komodo edit(free versionand komodo ide(paid versionare as given herekomodo edit (freekomodo ide (paid
3,038
screenshot why to choosepowerful ide with support for perlphppythonruby and many more cross-platform ide it includes basic features like integrated debugger supportauto completedocument object model(domviewercode browserinteractive shellsbreakpoint configurationcode profilingintegrated unit testing in shortit is professional ide with host of productivity-boosting features eric python ide it is an open-source ide for python and ruby eric is full featured editor and idewritten in python it is based on the cross platform qt gui toolkitintegrating the highly flexible scintilla editor control the ide is very much configurable and one can choose what to use and what not you can download eric ide from below linkwhy to choose great indentationerror highlighting code assistance code completion code cleanup with pylint quick search integrated python debugger
3,039
screenshot choosing text editor you may not always need an ide for tasks such as learning to code with python or arduinoor when working on quick script in shell script to help you automate some tasks simple and light weight code-centric text editor will do also many text editors offer features such as syntax highlighting and in-program script executionsimilar to ides some of the text editors are given hereatom sublime text notepad+atom text editor atom is hackable text editor built by the team of github it is free and open source text and code editor which means that all the code is available for you to readmodify for your own use and even contribute improvements it is cross-platform text editor compatible for macoslinuxand microsoft windows with support for plug-ins written in node js and embedded git control download link
3,040
screenshot languages supported / ++ #csscoffeescripthtmljavascriptjavajsonjuliaobjective-cphpperlpythonruby on railsrubyshell scriptscalasqlxmlyaml and many more sublime text editor sublime text is proprietary software and it offers you free trial version to test it before you purchase it according to stackoverflow' developer surveyit' the fourth most popular development environment some of the advantages it provides is its incredible speedease of use and community support it also supports many programming languages and mark-up languagesand functions can be added by users with pluginstypically community-built and maintained under free-software licenses
3,041
screenshot language supported pythonrubyjavascript etc why to choosecustomize key bindingsmenussnippetsmacroscompletions and more auto completion feature quickly insert text code with sublime text snippets using snippetsfield markers and place holders opens quickly cross platform support for maclinux and windows jump the cursor to where you want to go select multiple lineswords and columns notepad +it' free source code editor and notepad replacement that supports several languages from assembly to xml and including python running in the ms windows environmentits use is governed by gpl license in addition to syntax highlightingnotepad+has some features that are particularly useful to coders
3,042
screenshot key features syntax highlighting and syntax folding pcre (perl compatible regular expressionsearch/replace entirely customizable gui auto completion tabbed editing multi-view multi-language environment launchable with different arguments language supported almost every language ( languageslike pythoncc++ #java etc
3,043
oop in python data structures python data structures are very intuitive from syntax point of view and they offer large choice of operations you need to choose python data structure depending on what the data involvesif it needs to be modifiedor if it is fixed data and what access type is requiredsuch as at the beginning/end/random etc lists list represents the most versatile type of data structure in python list is container which holds comma-separated values (items or elementsbetween square brackets lists are helpful when we want to work with multiple related values as lists keep data togetherwe can perform the same methods and operations on multiple values at once lists indices start from zero and unlike stringslists are mutable data structure list any empty list empty_list [ list of string str_list ['life''is''beautiful' list of integers int_list [ #mixed items list mixed_list ['this' 'is' ' ' 'mixed' 'list'to print the list print(empty_list[print(str_list['life''is''beautiful'print(type(str_list)print(int_list[
3,044
print(mixed_list['this' 'is' ' ' 'mixed' 'list'accessing items in python list each item of list is assigned number that is the index or position of that number indexing always start from zerothe second index is one and so forth to access items in listwe can use these index numbers within square bracket observe the following code for examplemixed_list ['this' 'is' ' ' 'mixed' 'list'to access the first item of the list mixed_list[ 'thisto access the th item mixed_list[ to access the last item of the list mixed_list[- 'listempty objects empty objects are the simplest and most basic python built-in types we have used them multiple times without noticing and have extended it to every class we have created the main purpose to write an empty class is to block something for time being and later extend and add behavior to it to add behavior to class means to replace data structure with an object and change all references to it so it is important to check the datawhether it is an object in disguisebefore you create anything observe the following code for better understanding#empty objects obj object(obj traceback (most recent call last)file ""line in obj attributeerror'objectobject has no attribute '
3,045
so from abovewe can see it' not possible to set any attributes on an object that was instantiated directly when python allows an object to have arbitrary attributesit takes certain amount of system memory to keep track of what attributes each object hasfor storing both the attribute name and its value even if no attributes are storeda certain amount of memory is allocated for potential new attributes so python disables arbitrary properties on object and several other built-insby default empty objects class empobjectpass obj empobject(obj 'helloworld!obj 'helloworld!henceif we want to group properties togetherwe could store them in an empty object as shown in the code above howeverthis method is not always suggested remember that classes and objects should only be used when you want to specify both data and behaviors tuples tuples are similar to lists and can store elements howeverthey are immutableso we cannot addremove or replace objects the primary benefits tuple provides because of its immutability is that we can use them as keys in dictionariesor in other locations where an object requires hash value tuples are used to store dataand not behavior in case you require behavior to manipulate tupleyou need to pass the tuple into function(or method on another objectthat performs the action as tuple can act as dictionary keythe stored values are different from each other we can create tuple by separating the values with comma tuples are wrapped in parentheses but not mandatory the following code shows two identical assignments stock 'msft' stock ('msft' type (stock type(stock stock =stock true
3,046
defining tuple tuples are very similar to list except that the whole set of elements are enclosed in parentheses instead of square brackets just like when you slice listyou get new list and when you slice tupleyou get new tuple tupl ('tuple','is''an','immutable''list'tupl ('tuple''is''an''immutable''list'tupl[ 'tupletupl[- 'listtupl[ : ('is''an'python tuple methods the following code shows the methods in python tuplestupl ('tuple''is''an''immutable''list'tupl append('new'traceback (most recent call last)file ""line in tupl append('new'attributeerror'tupleobject has no attribute 'appendtupl remove('is'traceback (most recent call last)file ""line in tupl remove('is'attributeerror'tupleobject has no attribute 'removetupl index('list' tupl index('new'traceback (most recent call last)file ""line in tupl index('new'
3,047
valueerrortuple index( ) not in tuple "isin tupl true tupl count('is' from the code shown abovewe can understand that tuples are immutable and henceyou cannot add elements to tuple you cannot append or extend method you cannot remove elements from tuple tuples have no remove or pop method count and index are the methods available in tuple dictionary dictionary is one of the python' built-in data types and it defines one-to-one relationships between keys and values defining dictionaries observe the following code to understand about defining dictionaryempty dictionary my_dict {dictionary with integer keys my_dict :'msft' 'it'dictionary with mixed keys my_dict {'name''aarav' ]using built-in function dict(my_dict dict({ :'msft' :'it'}from sequence having each item as pair my_dict dict([( ,'msft')( ,'it')]accessing elements of dictionary my_dict[
3,048
'msftmy_dict[ 'itmy_dict['it'traceback (most recent call last)file ""line in my_dict['it'keyerror'itfrom the above code we can observe thatfirst we create dictionary with two elements and assign it to the variable my_dict each element is key-value pairand the whole set of elements is enclosed in curly braces the number is the key and msft is its value similarly is the key and it is its value you can get values by keybut not vice-versa thus when we try my_dict['it'it raises an exceptionbecause it is not key modifying dictionaries observe the following code to understand about modifying dictionarymodifying dictionary my_dict { 'msft' 'it'my_dict[ 'softwaremy_dict { 'msft' 'software'my_dict[ 'microsoft technologiesmy_dict { 'msft' 'software' 'microsoft technologies'from the above code we can observe thatyou cannot have duplicate keys in dictionary altering the value of an existing key will delete the old value you can add new key-value pairs at any time
3,049
dictionaries have no concept of order among elements they are simple unordered collections mixing data types in dictionary observe the following code to understand about mixing data types in dictionarymixing data types in dictionary my_dict { 'msft' 'software' 'microsoft technologies'my_dict[ 'operating systemmy_dict { 'msft' 'software' 'microsoft technologies' 'operating system'my_dict['bill gates''ownermy_dict { 'msft' 'software' 'microsoft technologies' 'operating system''bill gates''owner'from the above code we can observe thatnot just strings but dictionary value can be of any data type including stringsintegersincluding the dictionary itself unlike dictionary valuesdictionary keys are more restrictedbut can be of any type like stringsintegers or any other deleting items from dictionaries observe the following code to understand about deleting items from dictionarydeleting items from dictionary my_dict { 'msft' 'software' 'microsoft technologies' 'operating system''bill gates''owner'del my_dict['bill gates'my_dict { 'msft' 'software' 'microsoft technologies' 'operating system'my_dict clear(my_dict {
3,050
from the above code we can observe thatdel lets you delete individual items from dictionary by key clear deletes all items from dictionary sets set(is an unordered collection with no duplicate elements though individual items are immutableset itself is mutablethat is we can add or remove elements/items from the set we can perform mathematical operations like unionintersection etc with set though sets in general can be implemented using treesset in python can be implemented using hash table this allows it highly optimized method for checking whether specific element is contained in the set creating set set is created by placing all the items (elementsinside curly braces {}separated by comma or by using the built-in function set(observe the following lines of code#set of integers my_set { , , , print(my_set{ #set of mixed datatypes my_set { "hello world!"( )print(my_set{ ( )'hello world!'methods for sets observe the following code to understand about methods for sets#methods for sets #add(xmethod topics {'python''java'' #'topics add(' ++'topics {' #'' ++''java''python'#union(smethodreturns union of two set
3,051
topics {' #'' ++''java''python'team {'developer''content writer''editor','tester'group topics union(teamgroup {'tester'' #''python''editor''developer'' ++''java''content writer'intersets(smethodreturns an intersection of two sets inters topics intersection(teaminters set(difference(smethodreturns set containing all the elements of invoking set but not of the second set safe topics difference(teamsafe {'python'' ++''java'' #'diff topics difference(groupdiff set(#clear(methodempties the whole set group clear(group set(operators for sets observe the following code to understand about operators for setspython set operations #creating two sets set set(set set(adding elements to set
3,052
for in range( , )set add(ifor in range( , )set add(jset { set { #union of set and set set set set same as set union(set print('union of set set set 'set union of set set set { #intersection of set set set set set same as set intersection(set print('intersection of set and set set 'set intersection of set and set set { checking relation between set and set if set set set issuperset(set print('set is superset of set 'elif set set #set issubset(set print('set is subset of set 'else#set =set print('set is same as set 'set is superset of set difference between set and set set set set print('elements in set and not in set set 'set elements in set and not in set set { check if set and set are disjoint sets if set isdisjoint(set )
3,053
print('set and set have nothing in common\ 'set and set have nothing in common removing all the values of set set clear(set set(
3,054
oop in python building blocks in this we will discuss object oriented terms and programming concepts in detail class is just factory for an instance this factory contains the blueprint which describes how to make the instances an instances or object are constructed from the class in most caseswe can have more than one instances of class every instance has set of attribute and these attributes are defined in classso every instance of particular class is expected to have the same attributes class bundles behavior and state class will let you bundle together the behavior and state of an object observe the following diagram for better understandingthe following points are worth notable when discussing class bundlesthe word behavior is identical to function it is piece of code that does something (or implements behaviorthe word state is identical to variables it is place to store values within class when we assert class behavior and state togetherit means that class packages functions and variables
3,055
classes have methods and attributes in pythoncreating method defines class behavior the word method is the oop name given to function that is defined within class to sum upclass functions is synonym for methods class variables is synonym for name attributes class blueprint for an instance with exact behavior object one of the instances of the classperform functionality defined in the class type indicates the class the instance belongs to attribute any object valueobject attribute method "callable attributedefined in the class observe the following piece of code for examplevar "hellojohnprinttype (var)or print(var upper()upper(method is calledhellojohn creation and instantiation the following code shows how to create our first class and then its instance class myclass(object)pass create first instance of myclass this_obj myclass(print(this_objanother instance of myclass that_obj myclass(print (that_objhere we have created class called myclass and which does not do any task the argument object in myclass class involves class inheritance and will be discussed in later pass in the above code indicates that this block is emptythat is it is an empty class definition let us create an instance this_obj of myclass(class and print it as shown
3,056
herewe have created an instance of myclass the hex code refers to the address where the object is being stored another instance is pointing to another address now let us define one variable inside the class myclass(and get the variable from the instance of that class as shown in the following codeclass myclass(object)var create first instance of myclass this_obj myclass(print(this_obj varanother instance of myclass that_obj myclass(print (that_obj varoutput you can observe the following output when you execute the code given above as instance knows from which class it is instantiatedso when requested for an attribute from an instancethe instance looks for the attribute and the class this is called the attribute lookup instance methods function defined in class is called method an instance method requires an instance in order to call it and requires no decorator when creating an instance methodthe first parameter is always self though we can call it (selfby any other nameit is recommended to use selfas it is naming convention class myclass(object)var= def firstm(self)print("helloworld"obj myclass(print(obj varobj firstm(
3,057
output you can observe the following output when you execute the code given above helloworld note that in the above programwe defined method with self as argument but we cannot call the method as we have not declared any argument to it class myclass(object)def firstm(self)print("helloworld"print(selfobj myclass(obj firstm(print(objoutput you can observe the following output when you execute the code given abovehelloworld encapsulation encapsulation is one of the fundamentals of oop oop enables us to hide the complexity of the internal working of the object which is advantageous to the developer in the following wayssimplifies and makes it easy to understand to use an object without knowing the internals any change can be easily manageable object-oriented programming relies heavily on encapsulation the terms encapsulation and abstraction (also called data hidingare often used as synonyms they are nearly synonymousas abstraction is achieved through encapsulation encapsulation provides us the mechanism of restricting the access to some of the object' componentsthis means that the internal representation of an object can' be seen from outside of the object definition access to this data is typically achieved through special methodsgetters and setters
3,058
this data is stored in instance attributes and can be manipulated from anywhere outside the class to secure itthat data should only be accessed using instance methods direct access should not be permitted class myclass(object)def setage(selfnum)self age num def getage(self)return self age zack myclass(zack setage( print(zack getage()zack setage("fourty five"print(zack getage()output you can observe the following output when you execute the code given above fourty five the data should be stored only if it is correct and validusing exception handling constructs as we can see abovethere is no restriction on the user input to setage(method it could be stringa numberor list so we need to check onto above code to ensure correctness of being stored class myclass(object)def setage(selfnum)self age num def getage(self)return self age zack myclass(zack setage(
3,059
print(zack getage()zack setage("fourty five"print(zack getage()init constructor the __init__ method is implicitly called as soon as an object of class is instantiated this will initialize the object myclass(the line of code shown above will create new instance and assigns this object to the local variable the instantiation operationthat is calling class objectcreates an empty object many classes like to create objects with instances customized to specific initial state thereforea class may define special method named __init__(as showndef __init__(self)self data [python calls __init__ during the instantiation to define an additional attribute that should occur when class is instantiated that may be setting up some beginning values for that object or running routine required on instantiation so in this examplea newinitialized instance can be obtained byx myclass(the __init__(method can have single or multiple arguments for greater flexibility the init stands for initializationas it initializes attributes of the instance it is called the constructor of class class myclass(object)def __init__(self,aaabbb)self aaa self bbb myclass( print( ax boutput
3,060
class attributes the attribute defined in the class is called "class attributesand the attributes defined in the function is called 'instance attributeswhile definingthese attributes are not prefixed by selfas these are the property of the class and not of particular instance the class attributes can be accessed by the class itself classname attributenameas well as by the instances of the class (inst attributenamesothe instances have access to both the instance attribute as well as class attributes class myclass()age myclass age myclass( age class attribute can be overridden in an instanceeven though it is not good method to break encapsulation there is lookup path for attributes in python the first being the method defined within the classand then the class above it class myclass(object)classy 'class valuedd myclass(print (dd classythis should return the string 'class valueclass value dd classy "instance valueprint(dd classyreturn the string "instance valueinstance value this will delete the value set for 'dd classyin the instance del dd classy since the overriding attribute was deletedthis will print 'class valueprint(dd classyclass value
3,061
we are overriding the 'classyclass attribute in the instance dd when it' overriddenthe python interpreter reads the overridden value but once the new value is deleted with 'del'the overridden value is no longer present in the instanceand hence the lookup goes level above and gets it from the class working with class and instance data in this sectionlet us understand how the class data relates to the instance data we can store data either in class or in an instance when we design classwe decide which data belongs to the instance and which data should be stored into the overall class an instance can access the class data if we create multiple instancesthen these instances can access their individual attribute values as well the overall class data thusa class data is the data that is shared among all the instances observe the code given below for better undersandingclass instancecounter(object)count instances class attributewill be accessible to all def __init__(selfval)self val val instancecounter count += accessible through class name increment the value of class attributein above lineclass ('instancecounter'act as an object def set_val(selfnewval)self val newval def get_val(self)return self val def get_count(self)return instancecounter count instancecounter( instancecounter( instancecounter( for obj in (abc)print ('val of obj% %(obj get_val())initialized value print ('count% %(obj get_count())always
3,062
output val of obj count val of obj count val of obj count in shortclass attributes are same for all instances of class whereas instance attributes is particular for each instance for two different instanceswe will have two different instance attributes class myclassclass_attribute def class_method(self)self instance_attribute ' am instance attributeprint (myclass __dict__output you can observe the following output when you execute the code given above{'__module__''__main__''class_attribute' 'class_method'<function myclass class_method at >'__dict__'<attribute '__dict__of 'myclassobjects>'__weakref__'<attribute '__weakref__of 'myclassobjects>'__doc__'nonethe instance attribute myclass __dict__ as showna myclass( class_method(print( __dict__{'instance_attribute'' am instance attribute'
3,063
oop in python object oriented shortcuts this talks in detail about various built-in functions in pythonfile / operations and overloading concepts python built-in functions the python interpreter has number of functions called built-in functions that are readily available for use in its latest versionpython contains built-in functions as listed in the table given belowbuilt-in functions abs(dict(help(min(setattr(all(dir(hex(next(slice(any(divmod(id(object(sorted(ascii(enumerate(input(oct(staticmethod(bin(eval(int(open(str(bool(exec(isinstance(ord(sum(bytearray(filter(issubclass(pow(super(bytes(float(iter(print(tuple(callable(format(len(property(type(chr(frozenset(list(range(vars(classmethod(getattr(locals(repr(zip(compile(globals(map(reversed(__import__(complex(hasattr(max(round(delattr(hash(memoryview(set(this section discusses some of the important functions in brieflen(function the len(function gets the length of stringslist or collections it returns the length or number of items of an objectwhere object can be stringlist or collection len(['hello' ]
3,064
len(function internally works like list __len__(or tuple __len__(thusnote that len(works only on objects that has __len__(method set { set __len__( howeverin practicewe prefer len(instead of the __len__(function because of the following reasonsit is more efficient and it is not necessary that particular method is written to refuse access to special methods such as __len__ it is easy to maintain it supports backward compatibility reversed(seqit returns the reverse iterator seq must be an object which has __reversed__(method or supports the sequence protocol (the __len__(method and the __getitem__(methodit is generally used in for loops when we want to loop over items from back to front normal_list [ class customsequence()def __len__(self)return def __getitem__(self,index)return " { }format(indexclass funkyback()def __reversed__(self)return 'backwards!for seq in normal_listcustomsequence()funkyback()print('\ {}format(seq __class__ __name__)end=""for item in reversed(seq)print(itemend=""the for loop at the end prints the reversed list of normal listand instances of the two custom sequences the output shows that reversed(works on all the three of thembut has very different results when we define __reversed__
3,065
output you can observe the following output when you execute the code given abovelist customsequencex funkybackbackwards!enumerate the enumerate (method adds counter to an iterable and returns the enumerate object the syntax of enumerate (isenumerate(iterablestart= here the second argument start is optionaland by default index starts with zero ( enumerate names ['rajesh''rahul''aarav''sahil''trevor'enumerate(nameslist(enumerate(names)[( 'rajesh')( 'rahul')( 'aarav')( 'sahil')( 'trevor')so enumerate(returns an iterator which yields tuple that keeps count of the elements in the sequence passed since the return value is an iteratordirectly accessing it is not much useful better approach for enumerate(is keeping count within for loop for in in enumerate(names)print('names numberstr( )print(nnames number rajesh names number rahul names number aarav names number sahil names number trevor
3,066
there are many other functions in the standard libraryand here is another list of some more widely used functionshasattrgetattrsetattr and delattrwhich allows attributes of an object to be manipulated by their string names all and anywhich accept an iterable object and return true if allor anyof the items evaluate to be true nzipwhich takes two or more sequences and returns new sequence of tupleswhere each tuple contains single value from each sequence file / the concept of files is associated with the term object-oriented programming python has wrapped the interface that operating systems provided in abstraction that allows us to work with file objects the open(built-in function is used to open file and return file object it is the most commonly used function with two argumentsopen(filenamemodethe open(function calls two argumentfirst is the filename and second is the mode here mode can be 'rfor read only mode'wfor only writing (an existing file with the same name will be erased)and 'aopens the file for appendingany data written to the file is automatically added to the end ' +opens the file for both reading and writing the default mode is read only on windows'bappended to the mode opens the file in binary modeso there are also modes like 'rb''wband ' +btext 'this is the first linefile open('datawork',' 'file write(text file close(in some caseswe just want to append to the existing file rather then over-writing itfor that we could supply the value 'aas mode argumentto append to the end of the filerather than completely overwriting existing file contents open('datawork',' 'text this is second linef write(text close(
3,067
once file is opened for readingwe can call the readreadlineor readlines method to get the contents of the file the read method returns the entire contents of the file as str or bytes objectdepending on whether the second argument is 'bfor readabilityand to avoid reading large file in one goit is often better to use for loop directly on file object for text filesit will read each lineone at timeand we can process it inside the loop body for binary files however it' better to read fixed-sized chunks of data using the read(methodpassing parameter for the maximum number of bytes to read open('fileone',' +' readline('this is the first line \nf readline('this is the second line \nwriting to filethrough write method on file objects will writes string (bytes for binary dataobject to the file the writelines method accepts sequence of strings and write each of the iterated values to the file the writelines method does not append new line after each item in the sequence finally the close(method should be called when we are finished reading or writing the fileto ensure any buffered writes are written to the diskthat the file has been properly cleaned up and that all resources tied with the file are released back to the operating system it' better approach to call the close(method but technically this will happen automatically when the script exists an alternative to method overloading method overloading refers to having multiple methods with the same name that accept different sets of arguments given single method or functionwe can specify the number of parameters ourself depending on the function definitionit can be called with zeroonetwo or more parameters class humandef sayhello(selfname=none)if name is not noneprint('hello nameelseprint('hello '#create instance
3,068
obj human(#call the methodelse part will be executed obj sayhello(#call the method with parameterif part will be executed obj sayhello('rahul'output hello hello rahul default arguments functions are objects too callable object is an object can accept some arguments and possibly will return an object function is the simplest callable object in pythonbut there are others too like classes or certain class instances every function in python is an object objects can contain methods or functions but object is not necessary function def my_func()print('my function was called'my_func description ' silly functiondef second_func()print('second function was called'second_func description 'one more sillier functiondef another_func(func)print("the description:"end="print(func descriptionprint('the name'end='print(func __name__print('the class:'end='
3,069
print(func __class__print("now 'll call the function passed in"func(another_func(my_funcanother_func(second_funcin the above codewe are able to pass two different functions as argument into our third functionand get different output for each onethe descriptiona silly function the namemy_func the classnow 'll call the function passed in my function was called the descriptionone more sillier function the namesecond_func the classnow 'll call the function passed in second function was called callable objects just as functions are objects that can have attributes set on themit is possible to create an object that can be called as though it were function in python any object with __call__(method can be called using function-call syntax
3,070
oop in python inheritance and polymorphism inheritance and polymorphism this is very important concept in python you must understand it better if you want to learn inheritance one of the major advantages of object oriented programming is re-use inheritance is one of the mechanisms to achieve the same inheritance allows programmer to create general or base class first and then later extend it to more specialized class it allows programmer to write better code using inheritance you can use or inherit all the data fields and methods available in your base class later you can add you own methods and data fieldsthus inheritance provides way to organize coderather than rewriting it from scratch in object-oriented terminology when class extend class ythen is called super/parent/base class and is called subclass/child/derived class one point to note here is that only data fields and method which are not private are accessible by child classes private data fields and methods are accessible only inside the class syntax to create derived class isclass baseclassbody of base class class derivedclass(baseclass)body of derived class inheriting attributes now look at the below example
3,071
output we first created class called date and pass the object as an argumenthere-object is built-in class provided by python later we created another class called time and called the date class as an argument through this call we get access to all the data and attributes of date class into the time class because of that when we try to get the get_date method from the time class object tm we created earlier possible object attribute lookup hierarchy the instance the class any class from which this class inherits inheritance examples let' take closure look into the inheritance exampleobject animal cat dog let' create couple of classes to participate in examplesanimalclass simulate an animal catsubclass of animal dogsubclass of animal in pythonconstructor of class used to create an object (instance)and assign the value for the attributes constructor of subclasses always called to constructor of parent class to initialize value for the attributes in the parent classthen it start assign value for its attributes
3,072
output in the above examplewe see the command attributes or methods we put in the parent class so that all subclasses or child classes will inherits that property from the parent class if subclass try to inherits methods or data from another subclass then it will through an error as we see when dog class try to call swatstring(methods from that cat classit throws an error(like attributeerror in our case
3,073
polymorphism ("many shapes"polymorphism is an important feature of class definition in python that is utilized when you have commonly named methods across classes or subclasses this permits functions to use entities of different types at different times soit provides flexibility and loose coupling so that code can be extended and easily maintained over time this allows functions to use objects of any of these polymorphic classes without needing to be aware of distinctions across the classes polymorphism can be carried out through inheritancewith subclasses making use of base class methods or overriding them let understand the concept of polymorphism with our previous inheritance example and add one common method called show_affection in both subclassesfrom the example we can seeit refers to design in which object of dissimilar type can be treated in the same manner or more specifically two or more classes with method of the same name or common interface because same method(show_affection in below exampleis called with either type of objects output soall animals show affections (show_affection)but they do differently the "show_affectionbehaviors is thus polymorphic in the sense that it acted differently depending on the animal sothe abstract "animalconcept does not actually "show_affection"but specific animals(like dogs and catshave concrete implementation of the action "show_affection
3,074
python itself have classes that are polymorphic examplethe len(function can be used with multiple objects and all return the correct output based on the input parameter overriding in pythonwhen subclass contains method that overrides method of the superclassyou can also call the superclass method by calling super(subclassselfmethod instead of self method example class thought(object)def __init__(self)pass def message(self)print("thoughtalways come and go"class advice(thought)def __init__(self)super(adviceself__init__(def message(self)print('warningrisk is always involved when you are dealing with market!'
3,075
inheriting the constructor if we see from our previous inheritance example__init__ was located in the parent class in the up 'cause the child class dog or cat didn' 've __init__ method in it python used the inheritance attribute lookup to find __init__ in animal class when we created the child classfirst it will look the __init__ method in the dog classthen it didn' find it then looked into parent class animal and found there and called that there so as our class design became complex we may wish to initialize instance firstly processing it through parent class constructor and then through child class constructor output in above exampleall animals have name and all dogs particular breed we called parent class constructor with super so dog has its own __init__ but the first thing that happen is we call super super is built in function and it is designed to relate class to its super class or its parent class in this case we saying that get the super class of dog and pass the dog instance to whatever method we say here the constructor __init__ so in another words we are calling parent class animal __init__ with the dog object you may ask why we won' just say animal __init__ with the dog instancewe could do this but if the name of animal class were to changesometime in the future what if we wanna rearrange the class hierarchy
3,076
so the dog inherited from another class using super in this case allows us to keep things modular and easy to change and maintain so in this example we are able to combine general __init__ functionality with more specific functionality this gives us opportunity to separate common functionality from the specific functionality which can eliminate code duplication and relate class to one another in way that reflects the system overall design conclusion __init__ is like any other methodit can be inherited if class does not have __init__ constructorpython will check its parent class to see if it can find one as soon as it finds onepython calls it and stops looking we can use the super (function to call methods in the parent class we may want to initialize in the parent as well as our own class multiple inheritance and the lookup tree as its name indicatesmultiple inheritance is python is when class inherits from multiple classes for examplea child inherits personality traits from both parents (mother and fatherpython multiple inheritance syntax to make class inherits from multiple parents classeswe write the the names of these classes inside the parentheses to the derived class while defining it we separate these names with comma below is an example of thatclass motherpass class fatherpass class child(motherfather)pass issubclass(childmotherand issubclass(childfathertrue multiple inheritance refers to the ability of inheriting from two or more than two class the complexity arises as child inherits from parent and parents inherits from the grandparent class python climbs an inheriting tree looking for attributes that is being requested to be read from an object it will check the in the instancewithin class then
3,077
parent class and lastly from the grandparent class now the question arises in what order the classes will be searched breath-first or depth-first by defaultpython goes with the depth-first that' is why in the below diagram the python searches the dothis(method first in class so the method resolution order in the below example will be mrod-> -> -> look at the below multiple inheritance diagram
3,078
let' go through an example to understand the "mrofeature of an python output
3,079
example let' take another example of "diamond shapemultiple inheritance above diagram will be considered ambiguous from our previous example understanding "method resolution orderi mro will be -> -> -> -> but it' not on getting the second from the cpython will ignore the previous so the mro will be in this case will be -> -> ->
3,080
let' create an example based on above diagramoutput simple rule to understand the above output isif the same class appear in the method resolution orderthe earlier appearances of this class will be remove from the method resolution order in conclusionany class can inherit from multiple classes python normally uses "depth-firstorder when searching inheriting classes but when two classes inherit from the same classpython eliminates the first appearances of that class from the mro decoratorsstatic and class methods functions(or methodsare created by def statement
3,081
though methods works in exactly the same way as function except one point where method first argument is instance object we can classify methods based on how they behavelike simple methoddefined outside of class this function can access class attributes by feeding instance argumentdef outside_func(()instance methoddef func(self,class methodif we need to use class attributes @classmethod def cfunc(cls,static methoddo not have any info about the class @staticmethod def sfoo(till now we have seen the instance methodnow is the time to get some insight into the other two methodsclass method the @classmethod decoratoris builtin function decorator that gets passed the class it was called on or the class of the instance it was called on as first argument the result of that evaluation shadows your function definition syntax class (object)@classmethod def fun(clsarg arg )funfunction that needs to be converted into class method returnsa class method for function
3,082
they have the access to this cls argumentit can' modify object instance state that would require access to self it is bound to the class and not the object of the class class methods can still modify class state that applies across all instances of the class static method static method takes neither self nor cls(classparameter but it' free to accept an arbitrary number of other parameters syntax class (object)@staticmethod def fun(arg arg )returnsa static method for function funself static method can neither modify object state nor class state they are restricted in what data they can access when to use what we generally use class method to create factory methods factory methods return class object (similar to constructorfor different use cases we generally use static methods to create utility functions
3,083
oop in python -python design pattern overview modern software development needs to address complex business requirements it also needs to take into account factors such as future extensibility and maintainability good design of software system is vital to accomplish these goals design patterns play an important role in such systems to understand design patternlet' consider below example every car' design follows basic design patternfour wheelssteering wheelthe core drive system like accelerator-break-clutchetc soall things repeatedly builtproducedshall inevitably follow pattern in its design it carsbicyclepizzaatm machineswhatever even your sofa bed designs that have almost become standard way of coding some logic/mechanism/technique in softwarehence come to be known as or studied assoftware design patterns why is design pattern importantbenefits of using design patterns arehelps you to solve common design problems through proven approach no ambiguity in the understanding as they are well documented reduce the overall development time helps you deal with future extensions and modifications with more ease than otherwise may reduce errors in the system since they are proven solutions to common problems classification of design patterns the gof (gang of fourdesign patterns are classified into three categories namely creationalstructural and behavioral creational patterns creational design patterns separate the object creation logic from the rest of the system instead of you creating objectscreational patterns creates them for you the creational patterns include abstract factorybuilderfactory methodprototype and singleton creational patterns are not commonly used in python because of the dynamic nature of the language also language itself provide us with all the flexibility we need to create in sufficient elegant fashionwe rarely need to implement anything on toplike singleton or factory also these patterns provide way to create objects while hiding the creation logicrather than instantiating objects directly using new operator
3,084
structural patterns sometimes instead of starting from scratchyou need to build larger structures by using an existing set of classes that' where structural class patterns use inheritance to build new structure structural object patterns use compositionaggregation to obtain new functionality adapterbridgecompositedecoratorfacadeflyweight and proxy are structural patterns they offers best ways to organize class hierarchy behavioral patterns behavioral patterns offers best ways of handling communication between objects patterns comes under this categories arevisitorchain of responsibilitycommandinterpreteriteratormediatormementoobserverstatestrategy and template method are behavioral patterns because they represent the behavior of systemthey are used generally to describe the functionality of software systems commonly used design patterns singleton it is one of the most controversial and famous of all design patterns it is used in overly object-oriented languagesand is vital part of traditional object-oriented programming the singleton pattern is used forwhen logging needs to be implemented the logger instance is shared by all the components of the system the configuration files is using this because cache of information needs to be maintained and shared by all the various components in the system managing connection to database here is the uml diagramsingleton single +instancestatic +get_instance(static class logger(object)def __new__(cls*args**kwargs)if not hasattr(cls'_logger')
3,085
cls _logger super(loggercls__new__(cls*args**kwargsreturn cls _logger in this examplelogger is singleton when __new__ is calledit normally constructs new instance of that class when we override itwe first check if our singleton instance has been created or not if notwe create it using super call thuswhenever we call the constructor on loggerwe always get the exact same instance obj logger(obj logger(obj =obj true obj obj
3,086
oop in python advanced features in this we will look into some of the advanced features which python provide core syntax in our class design in this we will look ontohow python allows us to take advantage of operators in our classes python is largely objects and methods call on objects and this even goes on even when its hidden by some convenient syntax var 'hellovar world!var var 'hello world!var __add__(var 'hello world!num num num __add__(num var [' '' 'var ['hello'john'var __add__(var [' '' ''hello'john'so if we have to add magic method __add__ to our own classescould we do that too let' try to do that we have class called sumlist which has contructor __init__ which takes list as an argument called my_list class sumlist(object)def __init__(selfmy_list)self mylist my_list def __add__(selfother)
3,087
new_list for xy in zip(self mylistother mylist)return sumlist(new_listdef __repr__(self)return str(self mylistaa sumlist([ , ]bb sumlist([ ]cc aa bb aa __add__(bbprint(ccshould gives us list ([ ]output [ but there are many methods which are internally managed by others magic methods below are some of them'abcin var var __contains__('abc'var ='abcvar __eq__('abc'var[ var __getitem__( var[ : var __getslice__( len(varvar __len__(print(varvar __repr__(inheriting from built-in types classes can also inherit from built-in types this means inherits from any built-in and take advantage of all the functionality found there in below example we are inheriting from dictionary but then we are implementing one of its method __setitem__ this (setitemis invoked when we set key and value in the dictionary as this is magic methodthis will be called implicitly
3,088
class mydict(dict)def __setitem__(selfkeyval)print('setting key and value!'dict __setitem__(selfkeyvaldd mydict(dd[' ' dd[' ' for key in dd keys()print('{ }={ }format(keydd[key])outputsetting key and valuesetting key and valuea= = let' extend our previous examplebelow we have called two magic methods called __getitem__ and __setitem__ better invoked when we deal with list index mylist inherits from 'listobject but indexes from instead for class mylist(list)inherits from list def __getitem__(selfindex)if index = raise indexerror if index index index return list __getitem__(selfindexthis method is called when we access value with subscript like [ def __setitem__(selfindexvalue)if index = raise indexerror if index index index
3,089
list __setitem__(selfindexvaluex mylist([' '' '' ']__init__(inherited from builtin list print(x__repr__(inherited from builtin list append('hello')append(inherited from builtin list print( [ ]' (mylist __getitem__ cutomizes list superclass method index is but reflects print ( [ ]'hello(index is but reflects output [' '' '' ' hello in above examplewe set three item list in mylist and implicitly __init__ method is called and when we print the element xwe get the three item list ([' ',' ',' ']then we append another element to this list later we ask for index and index but if you see the outputwe are getting element from the (index- what we have asked for as we know list indexing start from but here the indexing start from (that' why we are getting the first item of the listnaming conventions in this we will look into names we'll used for variables especially private variables and conventions used by python programmers worldwide although variables are designated as private but there is not privacy in python and this by design like any other well documented languagespython has naming and style conventions that it promote although it doesn' enforce them there is style guide written by "guido van rossumthe originator of pythonthat describe the best practices and use of name and is called pep here is the link for thispep stands for python enhancement proposal and is series of documentation that distributed among the python community to discuss proposed changes for example it is recommended all
3,090
module names all_lower_case class names and exception namescamelcase global and local namesall_lower_case functions and method namesall_lower_case constantsall_upper_case these are just the recommendationyou can vary if you like but as most of the developers follows these recommendation so might me your code is less readable why conform to conventionwe can follow the pep recommendation we it allows us to getmore familiar to the vast majority of developers clearer to most readers of your code will match style of other contributers who work on same code base mark of professional software developers everyone will accept you variable naming'publicand 'privatein pythonwhen we are dealing with modules and classeswe designate some variables or attribute as private in pythonthere is no existence of "privateinstance variable which cannot be accessed except inside an object private simply means they are simply not intended to be used by the users of the code instead they are intended to be used internally in generala convention is being followed by most python developers name prefixed with an underscore for example _attrval (example belowshould be treated as non-public part of the api or any python codewhether it is functiona method or data member below is the naming convention we followpublic attributes or variables (intended to be used by the importer of this module or user of this class)private attributes or regular_lower_case variables (internal use by the module or class)_single_leading_underscore private attributes that shouldn' be subclassed__double_leading_underscore magic attributes__double_underscores__ (use themdon' create themclass getset(object)instance_count public __mangled_name 'no privacy!special variable
3,091
oop in python files and strings def __init__(selfvalue)self _attrval value _attrval is for internal use only getset instance_count + @property def var(self)print('getting the "varattribute'return self _attrval @var setter def var(selfvalue)print('setting the "varattribute'self _attrval value @var deleter def var(self)print('deleting the "varattribute'self _attrval none cc getset( cc var public name print(cc _attrvalprint(cc _getset__mangled_nameoutput setting the "varattribute no privacy
3,092
strings strings are the most popular data types used in every programming language whybecause weunderstand text better than numbersso in writing and talking we use text and wordssimilarly in programming too we use strings in string we parse textanalyse text semanticsand do data mining and all this data is human consumed text the string in python is immutable string manipulation in pythonstring can be marked in multiple waysusing single quote )double quoteor even triple quote ''in case of multiline strings string examples "hellob '' multi line stringsimple!'' ('multiple'strings'togethers'string manipulation is very useful and very widely used in every language oftenprogrammers are required to break down strings and examine them closely strings can be iterated over (character by character)slicedor concatenated the syntax is the same as for lists the str class has numerous methods on it to make manipulating strings easier the dir and help commands provides guidance in the python interpreter how to use them below are some of the commonly used string methods we use methods description isalpha(checks if all characters are alphabets isdigit(checks digit characters isdecimal(checks decimal characters isnumeric(checks numeric characters find(returns the highest index of substrings istitle(checks for titlecased strings join(returns concatenated string lower(returns lower cased string upper(returns upper cased string partion(returns tuple bytearray(returns array of given byte size
3,093
enumerate(returns an enumerate object isprintable(checks printable character let' try to run couple of string methodsstr 'hello world!str startswith(' 'false str startswith(' 'true str endswith(' 'false str endswith(' !'true str find(' ' #above returns the index of the first occurence of the character/substring str find('lo' str upper('hello world!str lower('hello world!str index(' 'traceback (most recent call last)file ""line in str index(' 'valueerrorsubstring not found ('hello how are you' split('['hello''how''are''you' = split(''*join( 'hello*how*are*yous partition('('hello'''how are you'
3,094
string formatting in python formatting of strings has changednow it more logical and is more flexible formatting can be done using the format(method or the sign(old stylein format string the string can contain literal text or replacement fields delimited by braces {and each replacement field may contains either the numeric index of positional argument or the name of keyword argument syntax str format(*args**kwargsbasic formatting '{{}format('example''one''example one'{{}format('pie'' ''pie below example allows re-arrange the order of display without changing the arguments '{ { }format('pie'' '' piepadding and aligning strings value can be padded to specific length #padding charactercan be space or special character '{: }format('python''python '{:> }format('python'python'{:<{} }format('python', 'python '{:*< }format('python''python******
3,095
'{:*^ }format('python''***python***'{ }format('python object oriented programming''python object #abovetruncated characters from the left side of specified string '{{}}format('python object oriented', 'python object #named placeholders data {'name':'raghu''place':'bangalore''{name{place}format(**data'raghu bangalore#datetime from datetime import datetime '{:% /% /% % :% }format(datetime( , , , , ) : strings are unicode strings as collections of immutable unicode characters unicode strings provide an opportunity to create software or programs that works everywhere because the unicode strings can represent any possible character not just the ascii characters many io operations only know how to deal with byteseven if the bytes object refers to textual data it is therefore very important to know how to interchange between bytes and unicode converting text to bytes converting strings to byte object is termed as encoding there are numerous forms of encodingmost common ones arepngjpegmp wavasciiutf- etc also this(encodingis format to represent audioimagestextetc in bytes this conversion is possible through encode(it take encoding technique as argument by defaultwe use 'utf- technique python code to demonstrate string encoding initialising string 'tutorialspoint#initialising byte object 'tutorialspoint
3,096
using encode(to encode the string encoded version of is stored in using ascii mapping encode('ascii'check if is converted to bytes or not if( == )print('encoding successful!'elseprint('encoding unsuccessful!'encoding successfulconverting bytes to text converting bytes to text is called the decoding this is implemented through decode(we can convert byte string to character string if we know which encoding is used to encode it so encoding and decoding are inverse processes python code to demonstrate byte decoding #initialise string 'tutorialspoint#initialising byte object 'tutorialspoint#using decode(to decode the byte object decoded version of is stored in using ascii mapping decode('ascii'
3,097
#check if is converted to string or not if ( = )print('decoding successful!'elseprint('decoding unsuccessful!'decoding successfulfile / operating systems represents files as sequence of bytesnot text file is named location on disk to store related information it is used to permanently store data in your disk in pythona file operation takes place in the following order open file read or write onto file (operationclose the file python wraps the incoming (or outgoingstream of bytes with appropriate decode (or encodecalls so we can deal directly with str objects opening file python has built-in function open(to open file this will generate file objectalso called handle as it is used to read or modify the file accordingly open( ' :\users\rajesh\desktop\index webm','rb' mode 'rbf name ' :\\users\\rajesh\\desktop\\index webmfor reading text from filewe only need to pass the filename into the function the file will be opened for readingand the bytes will be converted to text using the platform default encoding
3,098
oop in python exception and exception classes in generalan exception is any unusual condition exception usually indicates errors but sometimes they intentionally puts in the programin cases like terminating procedure early or recovering from resource shortage there are number of built-in exceptionswhich indicate conditions like reading past the end of fileor dividing by zero we can define our own exceptions called custom exception exception handling enables you handle errors gracefully and do something meaningful about it exception handling has two components"throwingand 'catchingidentifying exception (errorsevery error occurs in python result an exception which will an error condition identified by its error type #exception / traceback (most recent call last)file ""line in / zerodivisionerrordivision by zero var= print(vertraceback (most recent call last)file ""line in print(vernameerrorname 'veris not defined #above as we have misspelled variable name so we get an nameerror print('hellosyntaxerroreol while scanning string literal #above we have not closed the quote in stringso we get syntaxerror #below we are asking for keythat doen' exists
3,099
mydict {mydict[' 'traceback (most recent call last)file ""line in mydict[' 'keyerror' #above keyerror #below asking for index that didn' exist in list mylist [ , , , mylist[ traceback (most recent call last)file ""line in mylist[ indexerrorlist index out of range #aboveindex out of rangeraised indexerror catching/trapping exception when something unusual occurs in your program and you wish to handle it using the exception mechanismyou 'throw an exceptionthe keywords try and except are used to catch exceptions whenever an error occurs within try blockpython looks for matching except block to handle it if there is oneexecution jumps there syntaxtry#write some code #that might throw some exception except exception handleralert the user the code within the try clause will be executed statement by statement if an exception occursthe rest of the try block will be skipped and the except clause will be executed trysome statement here exceptexception handling