id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
6,400 | parameters filenamea file path librarychoose specific pyexcel-io plugin for writing renderer_librarychoose pyexcel parser plugin for writing parameters related to csv file format for csvfmtparams are accepted delimiter field separator lineterminator line terminator encodingcsv specific specify the file encoding the csv file for exampleencoding='latin especiallyencoding='utf- -sigwould add utf bom header if used in rendereror would parse csv with utf brom header used in parser escapechar one-character string used by the writer to escape the delimiter if quoting is set to quote_none and the quotechar if doublequote is false quotechar one-character string used to quote fields containing special characterssuch as the delimiter or quotecharor which contain new-line characters it defaults to '"quoting controls when quotes should be generated by the writer and recognised by the reader it can take on any of the quote_constants (see section module contentsand defaults to quote_minimal skipinitialspace when truewhitespace immediately following the delimiter is ignored the default is false pep_ _off when true in python version pep- is turned on the default is false pyexcel sheet save_to_memory sheet save_to_memory(file_typestream=none**keywordssave the content to memory parameters file_type any value of 'csv''tsv''csvz''tsvz''xls''xlsm''xlsm''odsstream the memory stream to be written to note in python for csv and tsv formatplease pass an instance of stringio for xlsxlsxand odsan instance of bytesio pyexcel sheet save_to_database sheet save_to_database(sessiontableinitializer=nonemapdict=noneauto_commit=truesave data in sheet to database table parameters session database session table database table initializer initialization functions for your table mapdict custom map dictionary for your data columns auto_commit by defaultdata is auto committed api documentation |
6,401 | pyexcel sheet save_to_django_model sheet save_to_django_model(modelinitializer=nonemapdict=nonebatch_size=nonesave to database table through django model parameters model database model initializer initialization functions for your model mapdict custom map dictionary for your data columns batch_size parameter to django concerning the size for bulk insertion internal api reference this is intended for developers and hackers of pyexcel data sheet representation in inheritance order from parent to child matrix(arraythe internal representation of sheet data pyexcel internal sheets matrix class pyexcel internal sheets matrix(arraythe internal representation of sheet data each element can be of any python types __init__(arrayconstructor the reason deep copy was not made here is because the data sheet could be huge it could be costly to copy every cell to new memory area :param list arraya list of arrays methods __init__(arraycell_value(rowcolumn[new_value]clone(column_at(indexcolumn_range(columns(contains(predicatecut(topleft_cornerbottomright_cornerdelete_columns(column_indicesdelete_rows(row_indicesenumerate( constructor random access to table cells gets the data at the specified column utility function to get column range returns left to right column iterator has something in the table get rectangle shaped data out and clear them in position delete columns by specified list of indices deletes specified row indices iterate cell by cell from top to bottom and from left to right continued on next page support the project |
6,402 | table continued from previous page extend_columns(columnsinserts two dimensional data after the rightmost column extend_columns_with_rows(rowsrows were appended to the rightmost side extend_rows(rowsinserts two dimensional data after the bottom row filter([column_indicesrow_indices]apply the filter with immediate effect format(formatterapply formatting action for the whole sheet get_array(**keywordsget data in array format get_bookdict(**keywordsget data in bookdict format get_csv(**keywordsget data in csv format get_csvz(**keywordsget data in csvz format get_dict(**keywordsget data in dict format get_fods(**__fods getter is not defined matrix get_grid get_handsontable(**keywordsget data in handsontable format get_handsontable_html(**keywordsget data in handsontable html format get_html(**__html getter is not defined get_internal_array(present internal array matrix get_json matrix get_latex matrix get_latex_booktabs matrix get_mediawiki matrix get_ndjson get_ods(**keywordsget data in ods format matrix get_orgtbl matrix get_pipe matrix get_plain get_records(**keywordsget data in records format matrix get_rst matrix get_simple get_svg(**keywordsget data in svg format get_texttable(**keywordsget data in texttable format get_tsv(**keywordsget data in tsv format get_tsvz(**keywordsget data in tsvz format get_url(**__url getter is not defined get_xls(**keywordsget data in xls format get_xlsm(**keywordsget data in xlsm format get_xlsx(**keywordsget data in xlsx format map(custom_functionexecute function across all cells of the sheet number_of_columns(the number of columns number_of_rows(the number of rows paste(topleft_corner[rowscolumns]paste rectangle shaped data after position plot([file_type]visualize the data rcolumns(returns right to left column iterator region(topleft_cornerbottomright_cornerget rectangle shaped data out register_input(file_type[instance_namepartial(func*args**keywordsnew function with ]partial application of the given arguments and keywords register_io(file_type[instance_name]partial(func*args**keywordsnew function with partial application of the given arguments and keywords continued on next page api documentation |
6,403 | table continued from previous page register_presentation(file_type[]partial(func*args**keywordsnew function with partial application of the given arguments and keywords reverse(opposite to enumerate row_at(indexgets the data at the specified row row_range(utility function to get row range rows(returns top to bottom row iterator rrows(returns bottom to top row iterator rvertical(default iterator to go through each cell one by one from rightmost column to leftmost row and from bottom to top example save_as(filename**keywordssave the content to named file save_to_database(sessiontable[]save data in sheet to database table save_to_django_model(model[initializersave to database table through django model ]save_to_memory(file_type[stream]save the content to memory set_array(content**keywordsset data in array format set_bookdict(content**keywordsset data in bookdict format set_column_at(column_indexdata_array[updates column data range ]set_csv(content**keywordsset data in csv format set_csvz(content**keywordsset data in csvz format set_dict(content**keywordsset data in dict format set_fods(content**keywordsset data in fods format matrix set_grid set_handsontable(_y**_zhandsontable setter is not defined set_handsontable_html(_y**_zhandsontable html setter is not defined set_html(content**keywordsset data in html format matrix set_json matrix set_latex matrix set_latex_booktabs matrix set_mediawiki matrix set_ndjson set_ods(content**keywordsset data in ods format matrix set_orgtbl matrix set_pipe matrix set_plain set_records(content**keywordsset data in records format set_row_at(row_indexdata_arrayupdate row data range matrix set_rst matrix set_simple set_svg(_y**_zsvg setter is not defined set_texttable(_y**_ztexttable setter is not defined set_tsv(content**keywordsset data in tsv format set_tsvz(content**keywordsset data in tsvz format set_url(content**keywordsset data in url format set_xls(content**keywordsset data in xls format set_xlsm(content**keywordsset data in xlsm format set_xlsx(content**keywordsset data in xlsx format to_array(get an array out continued on next page support the project |
6,404 | transpose(vertical(table continued from previous page rotate the data table by degrees default iterator to go through each cell one by one from leftmost column to rightmost row and from top to bottom example attributes array bookdict csv csvz dict fods matrix grid handsontable handsontable_html html matrix json matrix latex matrix latex_booktabs matrix mediawiki matrix ndjson ods matrix orgtbl matrix pipe matrix plain records matrix rst matrix simple stream svg texttable tsv tsvz url xls xlsm xlsx sheetstream(namepayloadbookstream([sheetsfilenamepath]get/set data in/from array format get/set data in/from bookdict format get/set data in/from csv format get/set data in/from csvz format get/set data in/from dict format set data in fods format get data in handsontable format get data in handsontable html format set data in html format get/set data in/from ods format get/set data in/from records format return stream in which the content is properly encoded get data in svg format get data in texttable format get/set data in/from tsv format get/set data in/from tsvz format set data in url format get/set data in/from xls format get/set data in/from xlsm format get/set data in/from xlsx format memory efficient sheet representation memory efficient book representation pyexcel internal generators sheetstream class pyexcel internal generators sheetstream(namepayloadmemory efficient sheet representation this class wraps around the data read from pyexcel-io comparing with pyexcel sheetthe instance of this class does not load all data into memory hence it performs better when dealing with big data api documentation |
6,405 | if you would like to do custom rendering for each row of the two dimensional datayou would need to pass row formatting/rendering function to the parameter "rendererof pyexcel' signature functions __init__(namepayloadinitialize self see help(type(self)for accurate signature methods __init__(namepayloadget_internal_array(to_array(initialize self simply return the generator attributes array array attribute pyexcel internal generators bookstream class pyexcel internal generators bookstream(sheets=nonepath=nonememory efficient book representation filename='memory'comparing with pyexcel bookthe instace of this class uses pyexcel generators sheetstream as its internal repesentation of sheet objects because sheetstream does not read data into memoryit is memory efficient __init__(sheets=nonefilename='memory'path=nonebook constructor selecting specific book according to filename extension :param ordereddict/dict sheetsa dictionary of data :param str filenamethe physical file :param str paththe relative path or absolute path :param set keywordsadditional parameters to be passed on methods __init__([sheetsfilenamepath]load_from_sheets(sheetsnumber_of_sheets(sheet_names(to_dict(book constructor load content from existing sheets return the number of sheets get book data structure as dictionary row representation row(matrixrepresent row of matrix pyexcel internal sheets row class pyexcel internal sheets row(matrixrepresent row of matrix support the project |
6,406 | table "example csv above column manipulation can be performed on rows similarly this section will not repeat the same example but show some advance usages import pyexcel as pe data [[ , , ][ , , ][ , , ] pe internal sheets matrix(datam row[ : [[ ][ ] row[ : [ row[ [ del row[ : row[ [ __init__(matrixinitialize self see help(type(self)for accurate signature methods __init__(matrixformat([row_indexformatterformat_specs]get_converter(theformatterselect(indicesinitialize self format row return the actual converter or built-in converter delete row indices other than specified column representation represent columns of matrix column(matrixpyexcel internal sheets column class pyexcel internal sheets column(matrixrepresent columns of matrix table "example csv let us manipulate the data columns on the above data matriximport pyexcel as pe data [[ , , ][ , , ][ , , ] pe internal sheets matrix(data(continues on next page api documentation |
6,407 | (continued from previous pagem column[ [ column[ [ column[ [ del column[ column[ [ column[ traceback (most recent call last)indexerror __init__(matrixinitialize self see help(type(self)for accurate signature methods __init__(matrixformat([column_indexformatterformat_specs]get_converter(theformatterselect(indicesinitialize self format column return the actual converter or built-in converter examples developer' guide developer' guide development steps for code changes git clone cd pyexcel upgrade your setup tools and pip they are needed for development and testing only pip install -upgrade setuptools pip then install relevant development requirements pip install - rnd_requirements txt if such file exists pip install - requirements txt pip install - tests/requirements txt once you have finished your changesplease provide test case( )relevant documentation and update changelog yml noteas to rnd_requirements txtusuallyit is created when dependent library is not released once the dependecy is installed (will be released)the future version of the dependency in the requirements txt will be valid support the project |
6,408 | how to test your contribution although nose and doctest are both used in code testingit is adviable that unit tests are put in tests doctest is incorporated only to make sure the code examples in documentation remain valid across different development releases on linux/unix systemsplease launch your tests like thismake on windowsplease issue this commandtest bat before you commit please runmake format so as to beautify your code otherwise your build may fail your unit test how to log pyexcel when developing source pluginsit becomes necessary to have log trace available it helps find out what goes wrong quickly the basic step would be to set up logging before pyexcel import statement import logging import logging config logging basicconfig(format='%(asctime) %(name) %(levelname) %(message) 'level=logging debugimport pyexcel and if you would use complex configurationyou can use the following code import logging import logging config logging config fileconfig('log conf'import pyexcel and then save the following content as log conf in your directory[loggerskeys=rootsourcesrenderers [handlerskeys=consolehandler [formatterskeys=custom [logger_root(continues on next page developer' guide |
6,409 | (continued from previous pagelevel=info handlers=consolehandler [logger_sourceslevel=debug handlers=consolehandler qualname=pyexcel sources factory propagate= [logger_rendererslevel=debug handlers=consolehandler qualname=pyexcel renderers factory propagate= [handler_consolehandlerclass=streamhandler level=debug formatter=custom args=(sys stdout,[formatter_customformat=%(asctime) %(name) %(levelname) %(message) datefmtdisable logging in unit testing and django frameworkyou will find the `lmllogging even you have '-not explicitly wanted them you can suppress themimport logging logging getlogger('lml plugin'propagate false here is list of possible modules`lml pluginand `lml loaderpackaging with pyinstaller with pyexcel vthe way to package it has been changed because it uses lml for all plugins and you need to do the same for pyexcel-io plugins too built-in plugins of pyexcel in order to package every built-in plugins of pyexcel-ioyou need to specify--hidden-import pyexcel plugins renderers sqlalchemy --hidden-import pyexcel plugins renderers django --hidden-import pyexcel plugins renderers excel (continues on next page support the project |
6,410 | (continued from previous page--hidden-import pyexcel plugins renderers _texttable --hidden-import pyexcel plugins parsers excel --hidden-import pyexcel plugins parsers sqlalchemy --hidden-import pyexcel plugins sources http --hidden-import pyexcel plugins sources file_input --hidden-import pyexcel plugins sources memory_input --hidden-import pyexcel plugins sources file_output --hidden-import pyexcel plugins sources output_to_memory --hidden-import pyexcel plugins sources pydata bookdict --hidden-import pyexcel plugins sources pydata dictsource --hidden-import pyexcel plugins sources pydata arraysource --hidden-import pyexcel plugins sources pydata records --hidden-import pyexcel plugins sources django --hidden-import pyexcel plugins sources sqlalchemy --hidden-import pyexcel plugins sources querysets how to write plugin for pyexcel noteunder writing stay tuned there are three types of plugins for pyexceldata parserdata renderer and data source tutorial let me walk you through the process of creating pyexcel-pdfr package prerequisites pip install moban yehua git clone git clone let me assume that you have the work directory assetupmobans pyexcel-commons and your_work_directory points to the base directory for both and then please export an environment variableexport yehua_file=$your_work_directory/pyexcel-commons/yehua/yehua yml now let' get started step call yehua to get the basic scaffolding developer' guide |
6,411 | yehua yehua will walk you through creating pyexcel package press ^ to quit at any time what is your project namepyexcel-pdfr what is the descriptionparses tables in pdf file as tabular data what is project type pyexcel plugins command line interface python' externsion ( , , ) what is the nick namepdf step call moban to inflate all project filescd pyexcel-pdfrln - /pyexcel-commonscommons ln - /setupmobanssetupmobans moban templating readme rst to readme rst templating setup py to setup py templating requirements txt to requirements txt templating new_bsd_license jj to license templating manifest in jj to manifest in templating tests/requirements txt to tests/requirements txt templating test script jj to test sh templating test script jj to test bat templating travis yml jj to travis yml templating gitignore jj to gitignore templating docs/source/conf py jj to docs/source/conf py step coding please put your code in pyexcel_pdfr change log what' breaking in the following statements will stop workingimport pyexcel ext ods import pyexcel ext ods import pyexcel ext text import pyexcel ext xls import pyexcel ext xlsx as they were deprecated since support the project |
6,412 | what' breaking in in the following statementssheet_a sheet row rows sheet_b sheet column columns book sheet_a sheet_b sheet_a and sheet_b will no longer have access to the data of sheet book will no longer have access to the data of sheet_a and sheet_b under hyrum' lawthis enhancement in will cause breakage otherwise what' breaking in pyexcel sheet to_records(returns generator instead of list of dictionaries migrate away from get_{{file_type}}_stream functions from pyexcel sheet and pyexcel book were introduced since but were removed since please be advised to use save_to_memory functionssheet io {{file_type}or book io {{file_type}migrate from to filtering and formatting behavior of pyexcel sheet are simplified soft filter and soft formatter are removed extra classes such as iteratorformatterfilter are removed most of formatting tasks could be achieved using format(and map(and filtering with filter(formatting and filtering on row and/or column can be found with row(and column( updated filter function there is no alternative to replace the following codesheet filter(pe oddrowfilter()you will need to remove odd rows by yourselfimport pyexcel as pe data [' '][' '][' ']sheet pe sheet(datato_remove [for index in sheet row_range()if index = to_remove append(indexsheet filter(row_indices=to_removesheet pyexcel sheet(continues on next page change log |
6,413 | (continued from previous page+--- +---oryou could do thisdata [' '][' '][' ']sheet pe sheet(datadef odd_filter(row_index_)return row_index = del sheet row[odd_filtersheet pyexcel sheet+--- +---and the same applies to evenrowfilteroddcolumnfilterevencolumnfilter updated format function replacement of sheetformatter the following formatting codesheet apply_formatter(pe sheets formatters sheetformatter(int)can be replaced bysheet format(int replacement of row formatters the following coderow_formatter pe sheets formatters rowformatter([ ]strsheet add_formatter(row_formattercan be replaced bysheet row format([ ]str replacement of column formatters the following codef namedcolumnformatter(["column ""column "]strsheet apply_formatter( support the project |
6,414 | can be replaced bysheet column format(["column ""column "]strmigrate from to explicit importsno longer needed please forget about these statementsimport pyexcel ext xls import pyexcel ext ods import pyexcel ext xlsx they are no longer needed as long as you have pip-installed themthey will be auto-loaded howeverif you do not want some of the pluginsplease use pip to uninstall them what if you have your code as it isno harm but few warnings showndeprecated usage since vexplicit import is no longer required pyexcel ext ods '-is auto imported invalid environment markerplatform_python_implementation=="pypyyesit is surprise please upgrade setuptools in your environmentpip install --upgrade setuptools at the time of writingsetuptools (or setuptools--py py -none-any whl is installed on author' computer and worked how to keep both pyexcel-xls and pyexcel-xlsx as in issue pyexcel-xls was used for xls and pyexcel-xlsx had to be used for xlsx both must co-exist due to requirements the workaround would failed when auto-import are enabled in henceuser of pyexcel in this situation shall use 'libraryparameter to all signature functionsto instruct pyexcel to use named library for each function call pyexcel get_io is no longer exposed pyexcel get_io was passed on from pyexcel-io cel_io manager rwmanager get_io if you have to howeverit is no longer exposed please use pyexyou are likely to use pyexcel get_io when you do pyexcel sheet save_to_memory(or pyexcel book save_to_memory(where you need to put in io stream but actuallywith latest codeyou could put in none migrate from to "writeris goneplease use save_as here is piece of legacy code change log |
6,415 | pyexcel writer("afile csv"data=[[' '' '' '' '' '' '' '' '' '' ' ] write_array(tablew close(the new code isdata=[[' '' '' '' '' '' '' '' '' '' ' ]pyexcel save_as(array=datadest_file_name="afile csv"here is another piece of legacy codecontent " "[ , , , , ]" "[ , , , , ]" "[ , , , , ] pyexcel writer("afile csv" write_dict(self contentw close(the new code iscontent " "[ , , , , ]" "[ , , , , ]" "[ , , , , ]pyexcel save_as(adict=contentdest_file_name="afile csv"here is yet another piece of legacy codedata [ ][ io stringio( pyexcel writer(("csv",io) write_rows(dataw close(the new code isdata [ ][ io pyexcel save_as(dest_file_type='csv'array=datafor line in io readlines()print(line rstrip() , , , , "bookwriteris gone please use save_book_as here is piece of legacy code support the project |
6,416 | import pyexcel content "sheet "[[ ][ ][ ]]"sheet "[[ ][ ][ ]]"sheet "[[ ' ' ' ' ' '][ ][ ][ ] pyexcel bookwriter("afile csv" write_book_from_dict(contentw close(the replacement code isimport pyexcel content "sheet "[[ ][ ][ ]]"sheet "[[ ][ ][ ]]"sheet "[[ ' ' ' ' ' '][ ][ ][ ]pyexcel save_book_as(bookdict=contentdest_file_name="afile csv"change log fixed # recursionerror raised on deepcopy of sheet updated # pyexcel get_array documentation page seems to be copy of pyexcel get_sheet removed # drop the support for dummy import statements pyexcel ext updated # fix small typo add chardet as explicit dependency updated # dynamically resize the table matrix on set_value sheet['aa ''testwill work in this release updated update queryset source to work with pyexcel-io change log |
6,417 | updated # book created from dict no longer discards order fixed # remove leading and trailing whitespace for column names removed python compatibility have been permanently removed fixed # control the column order when write the data output fixed # texttable was dropped out in as compulsary dependency end user may experience it when sheet/table is printed in shell otherwisenew user of pyexcel won' see it as of release dateno issues were created updated # +in placeshall return new instance # documentation update however small is welcome removed dropping the test support for python version lower than should work with python but is not guaranteed to work please upgrade to python updated # fix bug with http data source the real fix lies in pyexcel-io this release just put the version requirement in updated # support dest_force_file_type on save_as and save_book_as support the project |
6,418 | updated # get_sheet {indexerror}list index out of range /xlsx can' be opened updated # include examples in tarbar updated # remove pyexcel-handsontalbe in test add testsand docs folder in distribution updated # please use scan_plugins_regexwhich lml complains about updated dependency on pyexcel-io to updated to require pyexcel-io and use lml at least version added support __len__ len(bookreturns the number of sheets and len(sheetreturns the number of rows # memory-efficient way to read sheet names # force_file_type is introduced when reading file on diskthis parameter allows you to choose reader csv reader for text file xlsx reader for xlsx file but with blob file suffix finallypyexcel got import pyexcel __version__ updated sheet to_records(returns generator nowsaving memory # fix set membership test to run faster in python # direct writes to cells yield weird results change log |
6,419 | added # sort book sheets updated # dest_sheet_name in save_as will set the sheet name in the output # fix set membership test to run faster in python added pyexcel-io# expose bulk_save to developer removed # remove gease from setup_requiresintroduced by removed testing against python # include license file in manifest inmeaning license file will appear in the released tar ball removed # remove gease from setup_requiresintroduced by removed testing against python # include license file in manifest inmeaning license file will appear in the released tar ball fixed # sheet to_dict(gets out of range error because there is only one row updated updated the baseline of pyexcel-io to added # respect the order of records in iget_recordsisave_as and save_as # new feature to allow intuitive initialization of pyexcel book support the project |
6,420 | updated embeded the enabler for pyexcel-htmlr http source does not support text/html as mime type updated support saving sheetstream and bookstream to database targets this is needed for pyexcel-webio and its downstream projects added sheet top(and sheet top_left(for data browsing add html as default rich display in jupyter notebook when pyexcel-text and pyexcel-chart is installed add svg as default rich display in jupyter notebook when pyexcel-chart and one of its implementation plugin(pyexcel-pygaletc are is installed new dictionary source supporteda dictionary of key value pair could be read into sheet added dynamic external plugin loading meaning if pyexcel plugin is installedit will be loaded implicitly and this change would remove unnecessary info log for those who do not use pyexcel-text and pyexcel-gal save_book_as before becomes isave_book_as and save_book_as in convert bookstream to book before saving # file closing mechanism is enfored free_resource is added and it should be called when iget_arrayiget_recordsisave_as and/or isave_book_as are used updated array is passed to pyexcel sheet as reference it means your array data will be modified removed pyexcel writer and pyexcel bookwriter were removed pyexcel load_book_from_sql and pyexcel load_from_sql were removed pyexcel deprecated load_from_query_setspyexcel deprecated load_book_from_django_models and pyexcel deprecated load_from_django_model were removed removed plugin loading code and lml is used instead updated # remove pyexcel-chart import from change log |
6,421 | updated # regression save_to_memory(should have returned stream instance which has been reset to zero if possible the exception is sys stdoutwhich cannot be reset # not able to handle decimal decimal removed remove get_{{file_type}}_stream functions from pyexcel sheet and pyexcel book introduced since added streamattribute are attached to ~pyexcel sheet and ~pyexcel book to get direct access the underneath stream in responding to file type attributessuch as sheet xls it helps provide custom stream to external worldfor examplesheet stream csv gives text stream that contains csv formatted data book stream xls returns xls format data in byte stream updated better error reporting when an unknown parameters or unsupported file types were given to the signature functions updated raise exception if the incoming sheet does not have column names in other wordsonly sheet with column names could be saved to database sheet with row names cannot be saved the alternative is to transpose the sheetthen name_columns_by_row and then save fix iget_records where non-uniform content should be givene [[" "" "][ ][ ]]some record would become non-uniforme key 'ywould be missing from the second record skip_empty_rows is applicable when saving python data structure to another data source for exampleif your array contains row which is consisted of empty stringsuch as [''''''']please specify skip_empty_rows=false in order to preserve it this becomes subtle when you try save python dictionary where empty rows is not easy to be spotted # better documentation for save_book_as updated # regression save_to_memory(should have returned stream instance added flask-excel# allow sheet_name parameter pyexcel-xls# case-insensitive for file_type xls and xls are treated in the same way support the project |
6,422 | updated # export_columns is ignored update dependency on pyexcel-io updated # cannot display empty sheet(hence book with empty sheetas texttable updated # optional module import error become visible added file type setters for sheet and bookand its documentation iget_records returns generator for list of records and should have better memory performanceespecially dealing with large csv files iget_array returns generator for list of two dimensional array and should have better memory performanceespecially dealing with large csv files enable pagination supportand custom row renderer via pyexcel-io updated take isave_as out from save_as hence two functions are there for save sheet as # encode 'utf- if the console is of ascii encoding # custom row renderer # set cell value does not work pyexcel transpose becomes pyexcel sheets transpose iterator functions of pyexcel sheet were converted to generator functions pyexcel sheet enumerate(pyexcel sheet reverse(pyexcel sheet vertical(pyexcel sheet rvertical(pyexcel sheet rows(pyexcel sheet rrows(pyexcel sheet columns(pyexcel sheet rcolumns(pyexcel sheet named_rows( change log |
6,423 | pyexcel sheet named_columns( ~pyexcel sheet save_to_memory and ~pyexcel book save_to_memory return the actual content no longer they will return io object hence you cannot call getvalue(on them removed content and out_file as function parameters to the signature functions are no longer supported sourcefactory and rendererfactory are removed the following methods are removed pyexcel to_array pyexcel to_dict pyexcel utils to_one_dimensional_array pyexcel dict_to_array pyexcel from_records pyexcel to_records pyexcel sheet filter has been re-implemented and all filters were removedpyexcel filters columnindexfilter pyexcel filters columnfilter pyexcel filters rowfilter pyexcel filters evencolumnfilter pyexcel filters oddcolumnfilter pyexcel filters evenrowfilter pyexcel filters oddrowfilter pyexcel filters rowindexfilter pyexcel filters singlecolumnfilter pyexcel filters rowvaluefilter pyexcel filters namedrowvaluefilter pyexcel filters columnvaluefilter pyexcel filters namedcolumnvaluefilter pyexcel filters singlerowfilter the following functions have been removed add_formatter remove_formatter clear_formatters freeze_formatters add_filter remove_filter clear_filters support the project |
6,424 | freeze_formatters pyexcel sheet filter has been re-implemented and all filters were removedpyexcel formatters sheetformatter updated # texttable should have been made as compulsory requirement updated for python writing to sys stdout by pyexcel-cli raise ioerror updated for python do not seek when saving to memory if sys stdout is passed on henceadding support for sys stdin and sys stdout updated explicit importsno longer needed depends on latest setuptools notimplementederror will be raised if parameters to core functions are not supportedget_sheet(cannot_find_me_option="will be thrown out as notimplementederror" added add pyexcel-text file types as attributes of pyexcel sheet and pyexcel bookrelated to # auto import pyexcel-text if it is pip installed updated code refactoring done for easy addition of sources bug fix # even if the format is string it is displayed as float pyexcel-text is no longer plugin to pyexcel-io but to pyexcel sourcessee pyexcel-text# removed pyexcel presentation is removed no longer the internal decorate @outsource is used related to # change log |
6,425 | updated adopt pyexcel-io yield key word to return generator as content pyexcel save_as and pyexcel save_book_as get performance improvements added support pyramid-excel which does the database commit on its own added get excel data from http url added support django texttable as default renderer added added sqlalchemy support added added csvz and tsvz format updated support python features read and write csvodsxlsxlsx and xlsm files(which are referred later as excel files various iterators for the reader row and column filters for the reader support the project |
6,426 | utilities to get array and dictionary out from excel files cookbok receipes for some common and simple usage of this library change log |
6,427 | contents asking the user for input comments choosing mnemonic variable names debugging glossary exercises conditional execution boolean expressions logical operators conditional execution alternative execution chained conditionals nested conditionals catching exceptions using try and except short-circuit evaluation of logical expressions debugging glossary exercises functions function calls built-in functions type conversion functions math functions random numbers adding new functions definitions and uses flow of execution parameters and arguments fruitful functions and void functions why functions debugging glossary exercises |
6,428 | vii iteration updating variables the while statement infinite loops finishing iterations with continue definite loops using for loop patterns counting and summing loops maximum and minimum loops debugging glossary exercises strings string is sequence getting the length of string using len traversal through string with loop string slices strings are immutable looping and counting the in operator string comparison string methods parsing strings format operator debugging glossary exercises files persistence opening files text files and lines reading files searching through file |
6,429 | contents letting the user choose the file name using tryexceptand open writing files debugging glossary exercises lists list is sequence lists are mutable traversing list list operations list slices list methods deleting elements lists and functions lists and strings parsing lines objects and values aliasing list arguments debugging glossary exercises dictionaries dictionary as set of counters dictionaries and files looping and dictionaries advanced text parsing debugging glossary exercises |
6,430 | ix tuples tuples are immutable comparing tuples tuple assignment dictionaries and tuples multiple assignment with dictionaries the most common words using tuples as keys in dictionaries sequencesstringslistsand tuples oh my list comprehension debugging glossary exercises regular expressions character matching in regular expressions extracting data using regular expressions combining searching and extracting escape character summary bonus section for unix linux users debugging glossary exercises networked programs hypertext transfer protocol http the world' simplest web browser retrieving an image over http retrieving web pages with urllib reading binary files using urllib parsing html and scraping the web parsing html using regular expressions parsing html using beautifulsoup bonus section for unix linux users glossary exercises |
6,431 | contents using web services extensible markup language xml parsing xml looping through nodes javascript object notation json parsing json application programming interfaces security and api usage glossary application google geocoding web service application twitter object-oriented programming managing larger programs getting started using objects starting with programs subdividing problem our first python object classes as types object lifecycle multiple instances inheritance summary glossary using databases and sql what is database database concepts database browser for sqlite creating database table structured query language summary spidering twitter using database basic data modeling programming with multiple tables |
6,432 | xi constraints in database tables retrieve and/or insert record storing the friend relationship three kinds of keys using join to retrieve data summary debugging glossary visualizing data building openstreetmap from geocoded data visualizing networks and interconnections visualizing mail data contributions contributor list for python for everybody contributor list for python for informatics preface for "think python the strange history of "think python acknowledgements for "think python contributor list for "think python copyright detail |
6,433 | why should you learn to write programswriting programs (or programmingis very creative and rewarding activity you can write programs for many reasonsranging from making your living to solving difficult data analysis problem to having fun to helping someone else solve problem this book assumes that everyone needs to know how to programand that once you know how to program you will figure out what you want to do with your newfound skills we are surrounded in our daily lives with computers ranging from laptops to cell phones we can think of these computers as our "personal assistantswho can take care of many things on our behalf the hardware in our current-day computers is essentially built to continuously ask us the question"what would you like me to do next?what nextwhat nextwhat nextwhat nextwhat nextwhat nextfigure personal digital assistant programmers add an operating system and set of applications to the hardware and we end up with personal digital assistant that is quite helpful and capable of helping us do many different things our computers are fast and have vast amounts of memory and could be very helpful to us if we only knew the language to speak to explain to the computer what we would like it to "do nextif we knew this languagewe could tell the computer to do tasks on our behalf that were repetitive interestinglythe kinds of things computers can do best are often the kinds of things that we humans find boring and mind-numbing |
6,434 | why should you learn to write programsfor examplelook at the first three paragraphs of this and tell me the most commonly used word and how many times the word is used while you were able to read and understand the words in few secondscounting them is almost painful because it is not the kind of problem that human minds are designed to solve for computerthe opposite is truereading and understanding text from piece of paper is hard for computer to do but counting the words and telling you how many times the most used word was used is very easy for the computerpython words py enter file:words txt to our "personal information analysis assistantquickly told us that the word "towas used sixteen times in the first three paragraphs of this this very fact that computers are good at things that humans are not is why you need to become skilled at talking "computer languageonce you learn this new languageyou can delegate mundane tasks to your partner (the computer)leaving more time for you to do the things that you are uniquely suited for you bring creativityintuitionand inventiveness to this partnership creativity and motivation while this book is not intended for professional programmersprofessional programming can be very rewarding job both financially and personally building usefulelegantand clever programs for others to use is very creative activity your computer or personal digital assistant (pdausually contains many different programs from many different groups of programmerseach competing for your attention and interest they try their best to meet your needs and give you great user experience in the process in some situationswhen you choose piece of softwarethe programmers are directly compensated because of your choice if we think of programs as the creative output of groups of programmersperhaps the following figure is more sensible version of our pdapick mepick mepick mepick mepick mebuy me :figure programmers talking to you for nowour primary motivation is not to make money or please end usersbut instead for us to be more productive in handling the data and information that we will encounter in our lives when you first startyou will be both the programmer and the end user of your programs as you gain skill as programmer and programming feels more creative to youyour thoughts may turn toward developing programs for others |
6,435 | computer hardware architecture before we start learning the language we speak to give instructions to computers to develop softwarewe need to learn small amount about how computers are built if you were to take apart your computer or cell phone and look deep insideyou would find the following partssoftware input and output devices what nextcentral processing unit network main memory secondary memory figure hardware architecture the high-level definitions of these parts are as followsthe central processing unit (or cpuis the part of the computer that is built to be obsessed with "what is next?if your computer is rated at gigahertzit means that the cpu will ask "what next?three billion times per second you are going to have to learn how to talk fast to keep up with the cpu the main memory is used to store information that the cpu needs in hurry the main memory is nearly as fast as the cpu but the information stored in the main memory vanishes when the computer is turned off the secondary memory is also used to store informationbut it is much slower than the main memory the advantage of the secondary memory is that it can store information even when there is no power to the computer examples of secondary memory are disk drives or flash memory (typically found in usb sticks and portable music playersthe input and output devices are simply our screenkeyboardmousemicrophonespeakertouchpadetc they are all of the ways we interact with the computer these daysmost computers also have network connection to retrieve information over network we can think of the network as very slow place to store and retrieve data that might not always be "upso in sensethe network is slower and at times unreliable form of secondary memory while most of the detail of how these components work is best left to computer buildersit helps to have some terminology so we can talk about these different parts as we write our programs |
6,436 | why should you learn to write programsas programmeryour job is to use and orchestrate each of these resources to solve the problem that you need to solve and analyze the data you get from the solution as programmer you will mostly be "talkingto the cpu and telling it what to do next sometimes you will tell the cpu to use the main memorysecondary memorynetworkor the input/output devices software input and output devices what nextcentral processing unit main memory network secondary memory figure where are youyou need to be the person who answers the cpu' "what next?question but it would be very uncomfortable to shrink you down to mm tall and insert you into the computer just so you could issue command three billion times per second so insteadyou must write down your instructions in advance we call these stored instructions program and the act of writing these instructions down and getting the instructions to be correct programming understanding programming in the rest of this bookwe will try to turn you into person who is skilled in the art of programming in the end you will be programmer perhaps not professional programmerbut at least you will have the skills to look at data/information analysis problem and develop program to solve the problem in senseyou need two skills to be programmerfirstyou need to know the programming language (pythonyou need to know the vocabulary and the grammar you need to be able to spell the words in this new language properly and know how to construct well-formed "sentencesin this new language secondyou need to "tell storyin writing storyyou combine words and sentences to convey an idea to the reader there is skill and art in constructing the storyand skill in story writing is improved by doing some writing and getting some feedback in programmingour program is the "storyand the problem you are trying to solve is the "ideaonce you learn one programming language such as pythonyou will find it much easier to learn second programming language such as javascript or +the |
6,437 | new programming language has very different vocabulary and grammar but the problem-solving skills will be the same across all programming languages you will learn the "vocabularyand "sentencesof python pretty quickly it will take longer for you to be able to write coherent program to solve brand-new problem we teach programming much like we teach writing we start reading and explaining programsthen we write simple programsand then we write increasingly complex programs over time at some point you "get your museand see the patterns on your own and can see more naturally how to take problem and write program that solves that problem and once you get to that pointprogramming becomes very pleasant and creative process we start with the vocabulary and structure of python programs be patient as the simple examples remind you of when you started reading for the first time words and sentences unlike human languagesthe python vocabulary is actually pretty small we call this "vocabularythe "reserved wordsthese are words that have very special meaning to python when python sees these words in python programthey have one and only one meaning to python later as you write programs you will make up your own words that have meaning to you called variables you will have great latitude in choosing your names for your variablesbut you cannot use any of python' reserved words as name for variable when we train dogwe use special words like "sit""stay"and "fetchwhen you talk to dog and don' use any of the reserved wordsthey just look at you with quizzical look on their face until you say reserved word for exampleif you say" wish more people would walk to improve their overall health"what most dogs likely hear is"blah blah blah walk blah blah blah blah that is because "walkis reserved word in dog language many might suggest that the language between humans and cats has no reserved words the reserved words in the language where humans talk to python include the followingand as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield that is itand unlike dogpython is already completely trained when you say "try"python will try every time you say it without fail we will learn these reserved words and how they are used in good timebut for now we will focus on the python equivalent of "speak(in human-to-dog languagethe nice thing about telling python to speak is that we can even tell it what to say by giving it message in quotes |
6,438 | why should you learn to write programsprint('hello world!'and we have even written our first syntactically correct python sentence our sentence starts with the function print followed by string of text of our choosing enclosed in single quotes the strings in the print statements are enclosed in quotes single quotes and double quotes do the same thingmost people use single quotes except in cases like this where single quote (which is also an apostropheappears in the string conversing with python now that we have word and simple sentence that we know in pythonwe need to know how to start conversation with python to test our new language skills before you can converse with pythonyou must first install the python software on your computer and learn how to start python on your computer that is too much detail for this so suggest that you consult www py com where have detailed instructions and screencasts of setting up and starting python on macintosh and windows systems at some pointyou will be in terminal or command window and you will type python and the python interpreter will start executing in interactive mode and appear somewhat as followspython ( : cee dec : : [msc bit (amd )on win type "help""copyright""creditsor "licensefor more information the prompt is the python interpreter' way of asking you"what do you want me to do next?python is ready to have conversation with you all you have to know is how to speak the python language let' say for example that you did not know even the simplest python language words or sentences you might want to use the standard line that astronauts use when they land on faraway planet and try to speak with the inhabitants of the planeti come in peaceplease take me to your leader file ""line come in peaceplease take me to your leader syntaxerrorinvalid syntax this is not going so well unless you think of something quicklythe inhabitants of the planet are likely to stab you with their spearsput you on spitroast you over fireand eat you for dinner luckily you brought copy of this book on your travelsand you thumb to this very page and try again |
6,439 | print('hello world!'hello worldthis is looking much betterso you try to communicate some moreprint('you must be the legendary god that comes from the sky'you must be the legendary god that comes from the sky print('we have been waiting for you for long time'we have been waiting for you for long time print('our legend says you will be very tasty with mustard'our legend says you will be very tasty with mustard print 'we will have feast tonight unless you say file ""line print 'we will have feast tonight unless you say syntaxerrormissing parentheses in call to 'printthe conversation was going so well for while and then you made the tiniest mistake using the python language and python brought the spears back out at this pointyou should also realize that while python is amazingly complex and powerful and very picky about the syntax you use to communicate with itpython is not intelligent you are really just having conversation with yourselfbut using proper syntax in sensewhen you use program written by someone else the conversation is between you and those other programmers with python acting as an intermediary python is way for the creators of programs to express how the conversation is supposed to proceed and in just few more you will be one of those programmers using python to talk to the users of your program before we leave our first conversation with the python interpreteryou should probably know the proper way to say "good-byewhen interacting with the inhabitants of planet pythongood-bye traceback (most recent call last)file ""line in nameerrorname 'goodis not defined if you don' mindi need to leave file ""line if you don' mindi need to leave syntaxerrorinvalid syntax quit(you will notice that the error is different for the first two incorrect attempts the second error is different because if is reserved word and python saw the reserved word and thought we were trying to say something but got the syntax of the sentence wrong |
6,440 | why should you learn to write programsthe proper way to say "good-byeto python is to enter quit(at the interactive chevron prompt it would have probably taken you quite while to guess that oneso having book handy probably will turn out to be helpful terminologyinterpreter and compiler python is high-level language intended to be relatively straightforward for humans to read and write and for computers to read and process other high-level languages include javac++phprubybasicperljavascriptand many more the actual hardware inside the central processing unit (cpudoes not understand any of these high-level languages the cpu understands language we call machine language machine language is very simple and frankly very tiresome to write because it is represented all in zeros and ones machine language seems quite simple on the surfacegiven that there are only zeros and onesbut its syntax is even more complex and far more intricate than python so very few programmers ever write machine language instead we build various translators to allow programmers to write in high-level languages like python or javascript and these translators convert the programs to machine language for actual execution by the cpu since machine language is tied to the computer hardwaremachine language is not portable across different types of hardware programs written in high-level languages can be moved between different computers by using different interpreter on the new machine or recompiling the code to create machine language version of the program for the new machine these programming language translators fall into two general categories( interpreters and ( compilers an interpreter reads the source code of the program as written by the programmerparses the source codeand interprets the instructions on the fly python is an interpreter and when we are running python interactivelywe can type line of python ( sentenceand python processes it immediately and is ready for us to type another line of python some of the lines of python tell python that you want it to remember some value for later we need to pick name for that value to be remembered and we can use that symbolic name to retrieve the value later we use the term variable to refer to the labels we use to refer to this stored data print( |
6,441 | print( in this examplewe ask python to remember the value six and use the label so we can retrieve the value later we verify that python has actually remembered the value using print then we ask python to retrieve and multiply it by seven and put the newly computed value in then we ask python to print out the value currently in even though we are typing these commands into python one line at timepython is treating them as an ordered sequence of statements with later statements able to retrieve data created in earlier statements we are writing our first simple paragraph with four sentences in logical and meaningful order it is the nature of an interpreter to be able to have an interactive conversation as shown above compiler needs to be handed the entire program in fileand then it runs process to translate the high-level source code into machine language and then the compiler puts the resulting machine language into file for later execution if you have windows systemoften these executable machine language programs have suffix of exeor dllwhich stand for "executableand "dynamic link libraryrespectively in linux and macintoshthere is no suffix that uniquely marks file as executable if you were to open an executable file in text editorit would look completely crazy and be unreadable^?elf^ ^ ^ ^@^@^@^@^@^@^@^@^@^ ^@^ ^@^ ^@^@^@\xa \ ^ ^ ^@^@^@\ ^]^@^@^@^@^@^@ ^^@^ ^@(^@$^@!^@^ ^^@^@ ^@^@^@ \ ^ ^ \ ^ ^ \xe ^@^@^@\xe ^@^@^@^ ^@^@^@^ ^@^@^@^ ^@^@^@^ ^ ^@^@^ \ ^ ^ ^ \ ^ ^ ^ ^@^@^@^ ^@^@^@^ ^@^@^@^ ^@^@^@^ \^ ^hqvht\ ^ ^ \xe it is not easy to read or write machine languageso it is nice that we have interpreters and compilers that allow us to write in high-level languages like python or now at this point in our discussion of compilers and interpretersyou should be wondering bit about the python interpreter itself what language is it written inis it written in compiled languagewhen we type "python"what exactly is happeningthe python interpreter is written in high-level language called "cyou can look at the actual source code for the python interpreter by going to www python org and working your way to their source code so python is program itself and it is compiled into machine code when you installed python on your computer (or the vendor installed it)you copied machine-code copy of the translated python program onto your system in windowsthe executable machine code for python itself is likely in file with name likec:\python \python exe |
6,442 | why should you learn to write programsthat is more than you really need to know to be python programmerbut sometimes it pays to answer those little nagging questions right at the beginning writing program typing commands into the python interpreter is great way to experiment with python' featuresbut it is not recommended for solving more complex problems when we want to write programwe use text editor to write the python instructions into filewhich is called script by conventionpython scripts have names that end with py to execute the scriptyou have to tell the python interpreter the name of the file in command windowyou would type python hello py as followscat hello py print('hello world!'python hello py hello worldthe "$is the operating system promptand the "cat hello pyis showing us that the file "hello pyhas one-line python program to print string we call the python interpreter and tell it to read its source code from the file "hello pyinstead of prompting us for lines of python code interactively you will notice that there was no need to have quit(at the end of the python program in the file when python is reading your source code from fileit knows to stop when it reaches the end of the file what is programthe definition of program at its most basic is sequence of python statements that have been crafted to do something even our simple hello py script is program it is one-line program and is not particularly usefulbut in the strictest definitionit is python program it might be easiest to understand what program is by thinking about problem that program might be built to solveand then looking at program that would solve that problem lets say you are doing social computing research on facebook posts and you are interested in the most frequently used word in series of posts you could print out the stream of facebook posts and pore over the text looking for the most common wordbut that would take long time and be very mistake prone you would be smart to write python program to handle the task quickly and accurately so you can spend the weekend doing something fun for examplelook at the following text about clown and car look at the text and figure out the most common word and how many times it occurs |
6,443 | the clown ran after the car and the car ran into the tent and the tent fell down on the clown and the car then imagine that you are doing this task looking at millions of lines of text frankly it would be quicker for you to learn python and write python program to count the words than it would be to manually scan the words the even better news is that already came up with simple program to find the most common word in text file wrote ittested itand now am giving it to you to use so you can save some time name input('enter file:'handle open(name' 'counts dict(for line in handlewords line split(for word in wordscounts[wordcounts get(word bigcount none bigword none for wordcount in list(counts items())if bigcount is none or count bigcountbigword word bigcount count print(bigwordbigcountcodeyou don' even need to know python to use this program you will need to get through of this book to fully understand the awesome python techniques that were used to make the program you are the end useryou simply use the program and marvel at its cleverness and how it saved you so much manual effort you simply type the code into file called words py and run it or you download the source code from this is good example of how python and the python language are acting as an intermediary between you (the end userand me (the programmerpython is way for us to exchange useful instruction sequences ( programsin common language that can be used by anyone who installs python on their computer so neither of us are talking to pythoninstead we are communicating with each other through python the building blocks of programs in the next few we will learn more about the vocabularysentence structureparagraph structureand story structure of python we will learn about the |
6,444 | why should you learn to write programspowerful capabilities of python and how to compose those capabilities together to create useful programs there are some low-level conceptual patterns that we use to construct programs these constructs are not just for python programsthey are part of every programming language from machine language up to the high-level languages input get data from the "outside worldthis might be reading data from fileor even some kind of sensor like microphone or gps in our initial programsour input will come from the user typing data on the keyboard output display the results of the program on screen or store them in file or perhaps write them to device like speaker to play music or speak text sequential execution perform statements one after another in the order they are encountered in the script conditional execution check for certain conditions and then execute or skip sequence of statements repeated execution perform some set of statements repeatedlyusually with some variation reuse write set of instructions once and give them name and then reuse those instructions as needed throughout your program it sounds almost too simple to be trueand of course it is never so simple it is like saying that walking is simply "putting one foot in front of the otherthe "artof writing program is composing and weaving these basic elements together many times over to produce something that is useful to its users the word counting program above directly uses all of these patterns except for one what could possibly go wrongas we saw in our earliest conversations with pythonwe must communicate very precisely when we write python code the smallest deviation or mistake will cause python to give up looking at your program beginning programmers often take the fact that python leaves no room for errors as evidence that python is meanhatefuland cruel while python seems to like everyone elsepython knows them personally and holds grudge against them because of this grudgepython takes our perfectly written programs and rejects them as "unfitjust to torment us primt 'hello world!file ""line primt 'hello world!syntaxerrorinvalid syntax primt ('hello world'traceback (most recent call last)file ""line in nameerrorname 'primtis not defined |
6,445 | hate you pythonfile ""line hate you pythonsyntaxerrorinvalid syntax if you come out of therei would teach you lesson file ""line if you come out of therei would teach you lesson syntaxerrorinvalid syntax there is little to be gained by arguing with python it is just tool it has no emotions and it is happy and ready to serve you whenever you need it its error messages sound harshbut they are just python' call for help it has looked at what you typedand it simply cannot understand what you have entered python is much more like dogloving you unconditionallyhaving few key words that it understandslooking you with sweet look on its face ()and waiting for you to say something it understands when python says "syntaxerrorinvalid syntax"it is simply wagging its tail and saying"you seemed to say something but just don' understand what you meantbut please keep talking to me (as your programs become increasingly sophisticatedyou will encounter three general types of errorssyntax errors these are the first errors you will make and the easiest to fix syntax error means that you have violated the "grammarrules of python python does its best to point right at the line and character where it noticed it was confused the only tricky bit of syntax errors is that sometimes the mistake that needs fixing is actually earlier in the program than where python noticed it was confused so the line and character that python indicates in syntax error may just be starting point for your investigation logic errors logic error is when your program has good syntax but there is mistake in the order of the statements or perhaps mistake in how the statements relate to one another good example of logic error might be"take drink from your water bottleput it in your backpackwalk to the libraryand then put the top back on the bottle semantic errors semantic error is when your description of the steps to take is syntactically perfect and in the right orderbut there is simply mistake in the program the program is perfectly correct but it does not do what you intended for it to do simple example would be if you were giving person directions to restaurant and saidwhen you reach the intersection with the gas stationturn left and go one mile and the restaurant is red building on your left your friend is very late and calls you to tell you that they are on farm and walking around behind barnwith no sign of restaurant then you say "did you turn left or right at the gas station?and they say" followed your directions perfectlyi have them written downit says turn left and go one mile at the gas station then you say" am very sorrybecause while my instructions were syntactically correctthey sadly contained small but undetected semantic error |
6,446 | why should you learn to write programsagain in all three types of errorspython is merely trying its hardest to do exactly what you have asked debugging when python spits out an error or even when it gives you result that is different from what you had intendedthen begins the hunt for the cause of the error debugging is the process of finding the cause of the error in your code when you are debugging programand especially if you are working on hard bugthere are four things to tryreading examine your coderead it back to yourselfand check that it says what you meant to say running experiment by making changes and running different versions often if you display the right thing at the right place in the programthe problem becomes obviousbut sometimes you have to spend some time to build scaffolding ruminating take some time to thinkwhat kind of error is itsyntaxruntimesemanticwhat information can you get from the error messagesor from the output of the programwhat kind of error could cause the problem you're seeingwhat did you change lastbefore the problem appearedretreating at some pointthe best thing to do is back offundoing recent changesuntil you get back to program that works and that you understand then you can start rebuilding beginning programmers sometimes get stuck on one of these activities and forget the others finding hard bug requires readingrunningruminatingand sometimes retreating if you get stuck on one of these activitiestry the others each activity comes with its own failure mode for examplereading your code might help if the problem is typographical errorbut not if the problem is conceptual misunderstanding if you don' understand what your program doesyou can read it times and never see the errorbecause the error is in your head running experiments can helpespecially if you run smallsimple tests but if you run experiments without thinking or reading your codeyou might fall into pattern call "random walk programming"which is the process of making random changes until the program does the right thing needless to sayrandom walk programming can take long time you have to take time to think debugging is like an experimental science you should have at least one hypothesis about what the problem is if there are two or more possibilitiestry to think of test that would eliminate one of them taking break helps with the thinking so does talking if you explain the problem to someone else (or even to yourself)you will sometimes find the answer before you finish asking the question but even the best debugging techniques will fail if there are too many errorsor if the code you are trying to fix is too big and complicated sometimes the best |
6,447 | option is to retreatsimplifying the program until you get to something that works and that you understand beginning programmers are often reluctant to retreat because they can' stand to delete line of code (even if it' wrongif it makes you feel bettercopy your program into another file before you start stripping it down then you can paste the pieces back in little bit at time the learning journey as you progress through the rest of the bookdon' be afraid if the concepts don' seem to fit together well the first time when you were learning to speakit was not problem for your first few years that you just made cute gurgling noises and it was ok if it took six months for you to move from simple vocabulary to simple sentences and took - more years to move from sentences to paragraphsand few more years to be able to write an interesting complete short story on your own we want you to learn python much more rapidlyso we teach it all at the same time over the next few but it is like learning new language that takes time to absorb and understand before it feels natural that leads to some confusion as we visit and revisit topics to try to get you to see the big picture while we are defining the tiny fragments that make up that big picture while the book is written linearlyand if you are taking course it will progress in linear fashiondon' hesitate to be very nonlinear in how you approach the material look forwards and backwards and read with light touch by skimming more advanced material without fully understanding the detailsyou can get better understanding of the "why?of programming by reviewing previous material and even redoing earlier exercisesyou will realize that you actually learned lot of material even if the material you are currently staring at seems bit impenetrable usually when you are learning your first programming languagethere are few wonderful "ah hah!moments where you can look up from pounding away at some rock with hammer and chisel and step away and see that you are indeed building beautiful sculpture if something seems particularly hardthere is usually no value in staying up all night and staring at it take breaktake naphave snackexplain what you are having problem with to someone (or perhaps your dog)and then come back to it with fresh eyes assure you that once you learn the programming concepts in the book you will look back and see that it was all really easy and elegant and it simply took you bit of time to absorb it glossary bug an error in program central processing unit the heart of any computer it is what runs the software that we writealso called "cpuor "the processorcompile to translate program written in high-level language into low-level language all at oncein preparation for later execution |
6,448 | why should you learn to write programshigh-level language programming language like python that is designed to be easy for humans to read and write interactive mode way of using the python interpreter by typing commands and expressions at the prompt interpret to execute program in high-level language by translating it one line at time low-level language programming language that is designed to be easy for computer to executealso called "machine codeor "assembly languagemachine code the lowest-level language for softwarewhich is the language that is directly executed by the central processing unit (cpumain memory stores programs and data main memory loses its information when the power is turned off parse to examine program and analyze the syntactic structure portability property of program that can run on more than one kind of computer print function an instruction that causes the python interpreter to display value on the screen problem solving the process of formulating problemfinding solutionand expressing the solution program set of instructions that specifies computation prompt when program displays message and pauses for the user to type some input to the program secondary memory stores programs and data and retains its information even when the power is turned off generally slower than main memory examples of secondary memory include disk drives and flash memory in usb sticks semantics the meaning of program semantic error an error in program that makes it do something other than what the programmer intended source code program in high-level language exercises exercise what is the function of the secondary memory in computeraexecute all of the computation and logic of the program bretrieve web pages over the internet cstore information for the long termeven beyond power cycle dtake input from the user exercise what is programexercise what is the difference between compiler and an interpreterexercise which of the following contains "machine code"athe python interpreter bthe keyboard cpython source file da word processing document exercise what is wrong with the following code |
6,449 | primt 'hello world!file ""line primt 'hello world!syntaxerrorinvalid syntax exercise where in the computer is variable such as "xstored after the following python line finishesx acentral processing unit bmain memory csecondary memory dinput devices eoutput devices exercise what will the following program print outx print(xa cx derror because is not possible mathematically exercise explain each of the following using an example of human capability( central processing unit( main memory( secondary memory( input deviceand ( output device for example"what is the human equivalent to central processing unit"exercise how do you fix "syntax error" |
6,450 | why should you learn to write programs |
6,451 | variablesexpressionsand statements values and types value is one of the basic things program works withlike letter or number the values we have seen so far are and "helloworld!these values belong to different types is an integerand "helloworld!is stringso called because it contains "stringof letters you (and the interpretercan identify strings because they are enclosed in quotation marks the print statement also works for integers we use the python command to start the interpreter python print( if you are not sure what type value hasthe interpreter can tell you type('helloworld!'type( not surprisinglystrings belong to the type str and integers belong to the type int less obviouslynumbers with decimal point belong to type called floatbecause these numbers are represented in format called floating point type( what about values like " and " "they look like numbersbut they are in quotation marks like strings |
6,452 | variablesexpressionsand statements type(' 'type(' 'they're strings when you type large integeryou might be tempted to use commas between groups of three digitsas in , , this is not legal integer in pythonbut it is legalprint( , , wellthat' not what we expected at allpython interprets , , as commaseparated sequence of integerswhich it prints with spaces between this is the first example we have seen of semantic errorthe code runs without producing an error messagebut it doesn' do the "rightthing variables one of the most powerful features of programming language is the ability to manipulate variables variable is name that refers to value an assignment statement creates new variables and gives them valuesmessage 'and now for something completely differentn pi this example makes three assignments the first assigns string to new variable named messagethe second assigns the integer to nthe third assigns the (approximatevalue of to pi to display the value of variableyou can use print statementprint( print(pi the type of variable is the type of the value it refers to type(messagetype(ntype(pi |
6,453 | variable names and keywords programmers generally choose names for their variables that are meaningful and document what the variable is used for variable names can be arbitrarily long they can contain both letters and numbersbut they cannot start with number it is legal to use uppercase lettersbut it is good idea to begin variable names with lowercase letter (you'll see why laterthe underscore character can appear in name it is often used in names with multiple wordssuch as my_name or airspeed_of_unladen_swallow variable names can start with an underscore characterbut we generally avoid doing this unless we are writing library code for others to use if you give variable an illegal nameyou get syntax error trombones 'big paradesyntaxerrorinvalid syntax more syntaxerrorinvalid syntax class 'advanced theoretical zymurgysyntaxerrorinvalid syntax trombones is illegal because it begins with number moreis illegal because it contains an illegal characterbut what' wrong with classit turns out that class is one of python' keywords the interpreter uses keywords to recognize the structure of the programand they cannot be used as variable names python reserves keywordsand as assert break class continue def del elif else except false finally for from global if import in is lambda none nonlocal not or pass raise return true try while with yield async await you might want to keep this list handy if the interpreter complains about one of your variable names and you don' know whysee if it is on this list statements statement is unit of code that the python interpreter can execute we have seen two kinds of statementsprint being an expression statement and assignment when you type statement in interactive modethe interpreter executes it and displays the resultif there is one |
6,454 | variablesexpressionsand statements script usually contains sequence of statements if there is more than one statementthe results appear one at time as the statements execute for examplethe script print( print(xproduces the output the assignment statement produces no output operators and operands operators are special symbols that represent computations like addition and multiplication the values the operator is applied to are called operands the operators +-*/and *perform additionsubtractionmultiplicationdivisionand exponentiationas in the following examples + hour- hour* +minute minute/ ** ( + )*( - there has been change in the division operator between python and python in python xthe result of this division is floating point resultminute minute/ the division operator in python would divide two integers and truncate the result to an integerminute minute/ to obtain the same answer in python use floored /integerdivision |
6,455 | minute minute// in python integer division functions much more as you would expect if you entered the expression on calculator expressions an expression is combination of valuesvariablesand operators value all by itself is considered an expressionand so is variableso the following are all legal expressions (assuming that the variable has been assigned value) if you type an expression in interactive modethe interpreter evaluates it and displays the result but in scriptan expression all by itself doesn' do anythingthis is common source of confusion for beginners exercise type the following statements in the python interpreter to see what they do order of operations when more than one operator appears in an expressionthe order of evaluation depends on the rules of precedence for mathematical operatorspython follows mathematical convention the acronym pemdas is useful way to remember the rulesparentheses have the highest precedence and can be used to force an expression to evaluate in the order you want since expressions in parentheses are evaluated first ( - is and ( + )**( - is you can also use parentheses to make an expression easier to readas in (minute even if it doesn' change the result |
6,456 | variablesexpressionsand statements exponentiation has the next highest precedenceso ** + is not and * ** is not ultiplication and division have the same precedencewhich is higher than addition and subtractionwhich also have the same precedence so * - is not and + / is not operators with the same precedence are evaluated from left to right so the expression is not because the - happens first and then is subtracted from when in doubtalways put parentheses in your expressions to make sure the computations are performed in the order you intend modulus operator the modulus operator works on integers and yields the remainder when the first operand is divided by the second in pythonthe modulus operator is percent sign (%the syntax is the same as for other operatorsquotient / print(quotient remainder print(remainder so divided by is with left over the modulus operator turns out to be surprisingly useful for exampleyou can check whether one number is divisible by anotherif is zerothen is divisible by you can also extract the right-most digit or digits from number for examplex yields the right-most digit of (in base similarlyx yields the last two digits string operations the operator works with stringsbut it is not addition in the mathematical sense instead it performs concatenationwhich means joining the strings by linking them end to end for examplefirst second print(first+second first ' |
6,457 | second ' print(first second the operator also works with strings by multiplying the content of string by an integer for examplefirst 'test second print(first secondtest test test asking the user for input sometimes we would like to take the value for variable from the user via their keyboard python provides built-in function called input that gets input from the keyboard when this function is calledthe program stops and waits for the user to type something when the user presses return or enterthe program resumes and input returns what the user typed as string inp input(some silly stuff print(inpsome silly stuff before getting input from the userit is good idea to print prompt telling the user what to input you can pass string to input to be displayed to the user before pausing for inputname input('what is your name?\ 'what is your namechuck print(namechuck the sequence \ at the end of the prompt represents newlinewhich is special character that causes line break that' why the user' input appears below the prompt if you expect the user to type an integeryou can try to convert the return value to int using the int(functionprompt 'what is the airspeed velocity of an unladen swallow?\nspeed input(promptwhat is the airspeed velocity of an unladen swallow in python this function was named raw_input |
6,458 | variablesexpressionsand statements int(speed int(speed but if the user types something other than string of digitsyou get an errorspeed input(promptwhat is the airspeed velocity of an unladen swallowwhat do you meanan african or european swallowint(speedvalueerrorinvalid literal for int(with base we will see how to handle this kind of error later comments as programs get bigger and more complicatedthey get more difficult to read formal languages are denseand it is often difficult to look at piece of code and figure out what it is doingor why for this reasonit is good idea to add notes to your programs to explain in natural language what the program is doing these notes are called commentsand in python they start with the symbolcompute the percentage of the hour that has elapsed percentage (minute in this casethe comment appears on line by itself you can also put comments at the end of linepercentage (minute percentage of an hour everything from the to the end of the line is ignoredit has no effect on the program comments are most useful when they document non-obvious features of the code it is reasonable to assume that the reader can figure out what the code doesit is much more useful to explain why this comment is redundant with the code and uselessv assign to this comment contains useful information that is not in the codev velocity in meters/second good variable names can reduce the need for commentsbut long names can make complex expressions hard to readso there is trade-off |
6,459 | choosing mnemonic variable names as long as you follow the simple rules of variable namingand avoid reserved wordsyou have lot of choice when you name your variables in the beginningthis choice can be confusing both when you read program and when you write your own programs for examplethe following three programs are identical in terms of what they accomplishbut very different when you read them and try to understand them print(chours rate pay hours rate print(payx ahd afd afd ahd afd print( afdthe python interpreter sees all three of these programs as exactly the same but humans see and understand these programs quite differently humans will most quickly understand the intent of the second program because the programmer has chosen variable names that reflect their intent regarding what data will be stored in each variable we call these wisely chosen variable names "mnemonic variable namesthe word mnemonic means "memory aidwe choose mnemonic variable names to help us remember why we created the variable in the first place while this all sounds greatand it is very good idea to use mnemonic variable namesmnemonic variable names can get in the way of beginning programmer' ability to parse and understand code this is because beginning programmers have not yet memorized the reserved words (there are only of themand sometimes variables with names that are too descriptive start to look like part of the language and not just well-chosen variable names take quick look at the following python sample code which loops through some data we will cover loops soonbut for now try to just puzzle through what this meansfor word in wordsprint(word see "mnemonic |
6,460 | variablesexpressionsand statements what is happening herewhich of the tokens (forwordinetc are reserved words and which are just variable namesdoes python understand at fundamental level the notion of wordsbeginning programmers have trouble separating what parts of the code must be the same as this example and what parts of the code are simply choices made by the programmer the following code is equivalent to the above codefor slice in pizzaprint(sliceit is easier for the beginning programmer to look at this code and know which parts are reserved words defined by python and which parts are simply variable names chosen by the programmer it is pretty clear that python has no fundamental understanding of pizza and slices and the fact that pizza consists of set of one or more slices but if our program is truly about reading data and looking for words in the datapizza and slice are very un-mnemonic variable names choosing them as variable names distracts from the meaning of the program after pretty short period of timeyou will know the most common reserved words and you will start to see the reserved words jumping out at youthe parts of the code that are defined by python (forinprintand :are in bold and the programmer-chosen variables (word and wordsare not in bold many text editors are aware of python syntax and will color reserved words differently to give you clues to keep your variables and reserved words separate after while you will begin to read python and quickly determine what is variable and what is reserved word debugging at this pointthe syntax error you are most likely to make is an illegal variable namelike class and yieldwhich are keywordsor odd~job and us$which contain illegal characters if you put space in variable namepython thinks it is two operands without an operatorbad name syntaxerrorinvalid syntax month file ""line month syntaxerrorinvalid token |
6,461 | for syntax errorsthe error messages don' help much the most common messages are syntaxerrorinvalid syntax and syntaxerrorinvalid tokenneither of which is very informative the runtime error you are most likely to make is "use before def;that istrying to use variable before you have assigned value this can happen if you spell variable name wrongprincipal interest principle rate nameerrorname 'principleis not defined variables names are case sensitiveso latex is not the same as latex at this pointthe most likely cause of semantic error is the order of operations for exampleto evaluate / pyou might be tempted to write pi but the division happens firstso you would get / which is not the same thingthere is no way for python to know what you meant to writeso in this case you don' get an error messageyou just get the wrong answer glossary assignment statement that assigns value to variable concatenate to join two operands end to end comment information in program that is meant for other programmers (or anyone reading the source codeand has no effect on the execution of the program evaluate to simplify an expression by performing the operations in order to yield single value expression combination of variablesoperatorsand values that represents single result value floating point type that represents numbers with fractional parts integer type that represents whole numbers keyword reserved word that is used by the compiler to parse programyou cannot use keywords like ifdefand while as variable names mnemonic memory aid we often give variables mnemonic names to help us remember what is stored in the variable modulus operator an operatordenoted with percent sign (%)that works on integers and yields the remainder when one number is divided by another operand one of the values on which an operator operates operator special symbol that represents simple computation like additionmultiplicationor string concatenation rules of precedence the set of rules governing the order in which expressions involving multiple operators and operands are evaluated statement section of code that represents command or action so farthe statements we have seen are assignments and print expression statement |
6,462 | variablesexpressionsand statements string type that represents sequences of characters type category of values the types we have seen so far are integers (type int)floating-point numbers (type float)and strings (type strvalue one of the basic units of datalike number or stringthat program manipulates variable name that refers to value exercises exercise write program that uses input to prompt user for their name and then welcomes them enter your namechuck hello chuck exercise write program to prompt the user for hours and rate per hour to compute gross pay enter hours enter rate pay we won' worry about making sure our pay has exactly two digits after the decimal place for now if you wantyou can play with the built-in python round function to properly round the resulting pay to two decimal places exercise assume that we execute the following assignment statementswidth height for each of the following expressionswrite the value of the expression and the type (of the value of the expression width// width/ height/ use the python interpreter to check your answers exercise write program which prompts the user for celsius temperatureconvert the temperature to fahrenheitand print out the converted temperature |
6,463 | conditional execution boolean expressions boolean expression is an expression that is either true or false the following examples use the operator ==which compares two operands and produces true if they are equal and false otherwise = true = false true and false are special values that belong to the class boolthey are not stringstype(truetype(falsethe =operator is one of the comparison operatorsthe others arex ! > < is is not is not equal to is greater than is less than is greater than or equal to is less than or equal to is the same as is not the same as although these operations are probably familiar to youthe python symbols are different from the mathematical symbols for the same operations common error is to use single equal sign (=instead of double equal sign (==remember that is an assignment operator and =is comparison operator there is no such thing as |
6,464 | conditional execution logical operators there are three logical operatorsandorand not the semantics (meaningof these operators is similar to their meaning in english for examplex and is true only if is greater than and less than % = or % = is true if either of the conditions is truethat isif the number is divisible by or finallythe not operator negates boolean expressionso not ( yis true if is falsethat isif is less than or equal to strictly speakingthe operands of the logical operators should be boolean expressionsbut python is not very strict any nonzero number is interpreted as "true and true true this flexibility can be usefulbut there are some subtleties to it that might be confusing you might want to avoid it until you are sure you know what you are doing conditional execution in order to write useful programswe almost always need the ability to check conditions and change the behavior of the program accordingly conditional statements give us this ability the simplest form is the if statementif print(' is positive'the boolean expression after the if statement is called the condition we end the if statement with colon character (:and the line(safter the if statement are indented yes > print(' is postitive'figure if logic |
6,465 | if the logical condition is truethen the indented statement gets executed if the logical condition is falsethe indented statement is skipped if statements have the same structure as function definitions or for loops the statement consists of header line that ends with the colon character (:followed by an indented block statements like this are called compound statements because they stretch across more than one line there is no limit on the number of statements that can appear in the bodybut there must be at least one occasionallyit is useful to have body with no statements (usually as place holder for code you haven' written yetin that caseyou can use the pass statementwhich does nothing if pass need to handle negative valuesif you enter an if statement in the python interpreterthe prompt will change from three chevrons to three dots to indicate you are in the middle of block of statementsas shown belowx if print('small'small when using the python interpreteryou must leave blank line at the end of blockotherwise python will return an errorx if print('small'print('done'file ""line print('done'syntaxerrorinvalid syntax blank line at the end of block of statements is not necessary when writing and executing scriptbut it may improve readability of your code alternative execution second form of the if statement is alternative executionin which there are two possibilities and the condition determines which one gets executed the syntax looks like this we will learn about functions in and loops in |
6,466 | conditional execution if % = print(' is even'else print(' is odd'if the remainder when is divided by is then we know that is evenand the program displays message to that effect if the condition is falsethe second set of statements is executed no yes % = print(' is odd'print(' is even'figure if-then-else logic since the condition must either be true or falseexactly one of the alternatives will be executed the alternatives are called branchesbecause they are branches in the flow of execution chained conditionals sometimes there are more than two possibilities and we need more than two branches one way to express computation like that is chained conditionalif yprint(' is less than 'elif yprint(' is greater than 'elseprint(' and are equal'elif is an abbreviation of "else if againexactly one branch will be executed there is no limit on the number of elif statements if there is an else clauseit has to be at the endbut there doesn' have to be one if choice =' 'print('bad guess'elif choice =' 'print('good guess'elif choice =' 'print('closebut not correct' |
6,467 | < > !!print('less'print ('greater'print('equal'figure if-then-elseif logic each condition is checked in order if the first is falsethe next is checkedand so on if one of them is truethe corresponding branch executesand the statement ends even if more than one condition is trueonly the first true branch executes nested conditionals one conditional can also be nested within another we could have written the three-branch example like thisif =yprint(' and are equal'elseif yprint(' is less than 'elseprint(' is greater than 'the outer conditional contains two branches the first branch contains simple statement the second branch contains another if statementwhich has two branches of its own those two branches are both simple statementsalthough they could have been conditional statements as well although the indentation of the statements makes the structure apparentnested conditionals become difficult to read very quickly in generalit is good idea to avoid them when you can logical operators often provide way to simplify nested conditional statements for examplewe can rewrite the following code using single conditionalif xif print(' is positive single-digit number 'the print statement is executed only if we make it past both conditionalsso we can get the same effect with the and operator |
6,468 | conditional execution yes no = yes no < print('equal'print('less'print''greater'figure nested if statements if and print(' is positive single-digit number ' catching exceptions using try and except earlier we saw code segment where we used the input and int functions to read and parse an integer number entered by the user we also saw how treacherous doing this could beprompt "what is the air velocity of an unladen swallow?\nspeed input(promptwhat is the air velocity of an unladen swallowwhat do you meanan african or european swallowint(speedvalueerrorinvalid literal for int(with base when we are executing these statements in the python interpreterwe get new prompt from the interpreterthink "oops"and move on to our next statement however if you place this code in python script and this error occursyour script immediately stops in its tracks with traceback it does not execute the following statement here is sample program to convert fahrenheit temperature to celsius temperatureinp input('enter fahrenheit temperature'fahr float(inpcel (fahr print(celcode |
6,469 | if we execute this code and give it invalid inputit simply fails with an unfriendly error messagepython fahren py enter fahrenheit temperature: python fahren py enter fahrenheit temperature:fred traceback (most recent call last)file "fahren py"line in fahr float(inpvalueerrorcould not convert string to float'fredthere is conditional execution structure built into python to handle these types of expected and unexpected errors called "try exceptthe idea of try and except is that you know that some sequence of instruction(smay have problem and you want to add some statements to be executed if an error occurs these extra statements (the except blockare ignored if there is no error you can think of the try and except feature in python as an "insurance policyon sequence of statements we can rewrite our temperature converter as followsinp input('enter fahrenheit temperature:'tryfahr float(inpcel (fahr print(celexceptprint('please enter number'codepython starts by executing the sequence of statements in the try block if all goes wellit skips the except block and proceeds if an exception occurs in the try blockpython jumps out of the try block and executes the sequence of statements in the except block python fahren py enter fahrenheit temperature: python fahren py enter fahrenheit temperature:fred please enter number handling an exception with try statement is called catching an exception in this examplethe except clause prints an error message in generalcatching an exception gives you chance to fix the problemor try againor at least end the program gracefully |
6,470 | conditional execution short-circuit evaluation of logical expressions when python is processing logical expression such as > and ( / it evaluates the expression from left to right because of the definition of andif is less than the expression > is false and so the whole expression is false regardless of whether ( / evaluates to true or false when python detects that there is nothing to be gained by evaluating the rest of logical expressionit stops its evaluation and does not do the computations in the rest of the logical expression when the evaluation of logical expression stops because the overall value is already knownit is called short-circuiting the evaluation while this may seem like fine pointthe short-circuit behavior leads to clever technique called the guardian pattern consider the following code sequence in the python interpreterx > and ( / true > and ( / false > and ( / traceback (most recent call last)file ""line in zerodivisionerrordivision by zero the third calculation failed because python was evaluating ( /yand was zerowhich causes runtime error but the first and the second examples did not fail because in the first calculation was non zero and in the second one the first part of these expressions > evaluated to false so the ( /ywas not ever executed due to the short-circuit rule and there was no error we can construct the logical expression to strategically place guard evaluation just before the evaluation that might cause an error as followsx > and ! and ( / false > and ! and ( / false > and ( / and ! |
6,471 | traceback (most recent call last)file ""line in zerodivisionerrordivision by zero in the first logical expressionx > is false so the evaluation stops at the and in the second logical expressionx > is true but ! is false so we never reach ( /yin the third logical expressionthe ! is after the ( /ycalculation so the expression fails with an error in the second expressionwe say that ! acts as guard to insure that we only execute ( /yif is non-zero debugging the traceback python displays when an error occurs contains lot of informationbut it can be overwhelming the most useful parts are usuallywhat kind of error it wasand where it occurred syntax errors are usually easy to findbut there are few gotchas whitespace errors can be tricky because spaces and tabs are invisible and we are used to ignoring them file ""line indentationerrorunexpected indent in this examplethe problem is that the second line is indented by one space but the error message points to ywhich is misleading in generalerror messages indicate where the problem was discoveredbut the actual error might be earlier in the codesometimes on previous line in generalerror messages tell you where the problem was discoveredbut that is often not where it was caused glossary body the sequence of statements within compound statement boolean expression an expression whose value is either true or false |
6,472 | conditional execution branch one of the alternative sequences of statements in conditional statement chained conditional conditional statement with series of alternative branches comparison operator one of the operators that compares its operands==!=>=and <conditional statement statement that controls the flow of execution depending on some condition condition the boolean expression in conditional statement that determines which branch is executed compound statement statement that consists of header and body the header ends with colon (:the body is indented relative to the header guardian pattern where we construct logical expression with additional comparisons to take advantage of the short-circuit behavior logical operator one of the operators that combines boolean expressionsandorand not nested conditional conditional statement that appears in one of the branches of another conditional statement traceback list of the functions that are executingprinted when an exception occurs short circuit when python is part-way through evaluating logical expression and stops the evaluation because python knows the final value for the expression without needing to evaluate the rest of the expression exercises exercise rewrite your pay computation to give the employee times the hourly rate for hours worked above hours enter hours enter rate pay exercise rewrite your pay program using try and except so that your program handles non-numeric input gracefully by printing message and exiting the program the following shows two executions of the programenter hours enter ratenine errorplease enter numeric input enter hoursforty errorplease enter numeric input exercise write program to prompt for score between and if the score is out of rangeprint an error message if the score is between and print grade using the following table |
6,473 | score > > > > grade enter score enter scoreperfect bad score enter score bad score enter score enter score run the program repeatedly as shown above to test the various different values for input |
6,474 | conditional execution |
6,475 | functions function calls in the context of programminga function is named sequence of statements that performs computation when you define functionyou specify the name and the sequence of statements lateryou can "callthe function by name we have already seen one example of function calltype( the name of the function is type the expression in parentheses is called the argument of the function the argument is value or variable that we are passing into the function as input to the function the resultfor the type functionis the type of the argument it is common to say that function "takesan argument and "returnsa result the result is called the return value built-in functions python provides number of important built-in functions that we can use without needing to provide the function definition the creators of python wrote set of functions to solve common problems and included them in python for us to use the max and min functions give us the largest and smallest values in listrespectivelymax('hello world''wmin('hello world' |
6,476 | functions the max function tells us the "largest characterin the string (which turns out to be the letter " "and the min function shows us the smallest character (which turns out to be spaceanother very common built-in function is the len function which tells us how many items are in its argument if the argument to len is stringit returns the number of characters in the string len('hello world' these functions are not limited to looking at strings they can operate on any set of valuesas we will see in later you should treat the names of built-in functions as reserved words ( avoid using "maxas variable name type conversion functions python also provides built-in functions that convert values from one type to another the int function takes any value and converts it to an integerif it canor complains otherwiseint(' ' int('hello'valueerrorinvalid literal for int(with base 'helloint can convert floating-point values to integersbut it doesn' round offit chops off the fraction partint( int(- - float converts integers and strings to floating-point numbersfloat( float(' ' finallystr converts its argument to stringstr( ' str( ' |
6,477 | math functions python has math module that provides most of the familiar mathematical functions before we can use the modulewe have to import itimport math this statement creates module object named math if you print the module objectyou get some information about itprint(maththe module object contains the functions and variables defined in the module to access one of the functionsyou have to specify the name of the module and the name of the functionseparated by dot (also known as periodthis format is called dot notation ratio signal_power noise_power decibels math log (ratioradians height math sin(radiansthe first example computes the logarithm base of the signal-to-noise ratio the math module also provides function called log that computes logarithms base the second example finds the sine of radians the name of the variable is hint that sin and the other trigonometric functions (costanetc take arguments in radians to convert from degrees to radiansdivide by and multiply by pdegrees radians degrees math pi math sin(radians the expression math pi gets the variable pi from the math module the value of this variable is an approximation of paccurate to about digits if you know your trigonometryyou can check the previous result by comparing it to the square root of two divided by twomath sqrt( |
6,478 | functions random numbers given the same inputsmost computer programs generate the same outputs every timeso they are said to be deterministic determinism is usually good thingsince we expect the same calculation to yield the same result for some applicationsthoughwe want the computer to be unpredictable games are an obvious examplebut there are more making program truly nondeterministic turns out to be not so easybut there are ways to make it at least seem nondeterministic one of them is to use algorithms that generate pseudorandom numbers pseudorandom numbers are not truly random because they are generated by deterministic computationbut just by looking at the numbers it is all but impossible to distinguish them from random the random module provides functions that generate pseudorandom numbers (which will simply call "randomfrom here onthe function random returns random float between and (including but not each time you call randomyou get the next number in long series to see samplerun this loopimport random for in range( ) random random(print(xthis program produces the following list of random numbers between and up to but not including exercise run the program on your system and see what numbers you get run the program more than once and see what numbers you get the random function is only one of many functions that handle random numbers the function randint takes the parameters low and highand returns an integer between low and high (including bothrandom randint( random randint( |
6,479 | to choose an element from sequence at randomyou can use choicet [ random choice( random choice( the random module also provides functions to generate random values from continuous distributions including gaussianexponentialgammaand few more adding new functions so farwe have only been using the functions that come with pythonbut it is also possible to add new functions function definition specifies the name of new function and the sequence of statements that execute when the function is called once we define functionwe can reuse the function over and over throughout our program here is an exampledef print_lyrics()print(" ' lumberjackand ' okay "print(' sleep all night and work all day 'def is keyword that indicates that this is function definition the name of the function is print_lyrics the rules for function names are the same as for variable nameslettersnumbers and some punctuation marks are legalbut the first character can' be number you can' use keyword as the name of functionand you should avoid having variable and function with the same name the empty parentheses after the name indicate that this function doesn' take any arguments later we will build functions that take arguments as their inputs the first line of the function definition is called the headerthe rest is called the body the header has to end with colon and the body has to be indented by conventionthe indentation is always four spaces the body can contain any number of statements if you type function definition in interactive modethe interpreter prints ellipses to let you know that the definition isn' completedef print_lyrics()print(" ' lumberjackand ' okay "print(' sleep all night and work all day 'to end the functionyou have to enter an empty line (this is not necessary in scriptdefining function creates variable with the same name |
6,480 | functions print(print_lyricsprint(type(print_lyrics)the value of print_lyrics is function objectwhich has type "functionthe syntax for calling the new function is the same as for built-in functionsprint_lyrics( ' lumberjackand ' okay sleep all night and work all day once you have defined functionyou can use it inside another function for exampleto repeat the previous refrainwe could write function called repeat_lyricsdef repeat_lyrics()print_lyrics(print_lyrics(and then call repeat_lyricsrepeat_lyrics( ' lumberjackand ' okay sleep all night and work all day ' lumberjackand ' okay sleep all night and work all day but that' not really how the song goes definitions and uses pulling together the code fragments from the previous sectionthe whole program looks like thisdef print_lyrics()print(" ' lumberjackand ' okay "print(' sleep all night and work all day 'def repeat_lyrics()print_lyrics(print_lyrics(repeat_lyrics(code |
6,481 | this program contains two function definitionsprint_lyrics and repeat_lyrics function definitions get executed just like other statementsbut the effect is to create function objects the statements inside the function do not get executed until the function is calledand the function definition generates no output as you might expectyou have to create function before you can execute it in other wordsthe function definition has to be executed before the first time it is called exercise move the last line of this program to the topso the function call appears before the definitions run the program and see what error message you get exercise move the function call back to the bottom and move the definition of print_lyrics after the definition of repeat_lyrics what happens when you run this program flow of execution in order to ensure that function is defined before its first useyou have to know the order in which statements are executedwhich is called the flow of execution execution always begins at the first statement of the program statements are executed one at timein order from top to bottom function definitions do not alter the flow of execution of the programbut remember that statements inside the function are not executed until the function is called function call is like detour in the flow of execution instead of going to the next statementthe flow jumps to the body of the functionexecutes all the statements thereand then comes back to pick up where it left off that sounds simple enoughuntil you remember that one function can call another while in the middle of one functionthe program might have to execute the statements in another function but while executing that new functionthe program might have to execute yet another functionfortunatelypython is good at keeping track of where it isso each time function completesthe program picks up where it left off in the function that called it when it gets to the end of the programit terminates what' the moral of this sordid talewhen you read programyou don' always want to read from top to bottom sometimes it makes more sense if you follow the flow of execution parameters and arguments some of the built-in functions we have seen require arguments for examplewhen you call math sin you pass number as an argument some functions take more than one argumentmath pow takes twothe base and the exponent |
6,482 | functions inside the functionthe arguments are assigned to variables called parameters here is an example of user-defined function that takes an argumentdef print_twice(bruce)print(bruceprint(brucethis function assigns the argument to parameter named bruce when the function is calledit prints the value of the parameter (whatever it istwice this function works with any value that can be printed print_twice('spam'spam spam print_twice( import math print_twice(math pi the same rules of composition that apply to built-in functions also apply to user-defined functionsso we can use any kind of expression as an argument for print_twiceprint_twice('spam '* spam spam spam spam spam spam spam spam print_twice(math cos(math pi)- - the argument is evaluated before the function is calledso in the examples the expressions 'spam '* and math cos(math piare only evaluated once you can also use variable as an argumentmichael 'ericthe half bee print_twice(michaelericthe half bee ericthe half bee the name of the variable we pass as an argument (michaelhas nothing to do with the name of the parameter (bruceit doesn' matter what the value was called back home (in the caller)here in print_twicewe call everybody bruce |
6,483 | fruitful functions and void functions some of the functions we are usingsuch as the math functionsyield resultsfor lack of better namei call them fruitful functions other functionslike print_twiceperform an action but don' return value they are called void functions when you call fruitful functionyou almost always want to do something with the resultfor exampleyou might assign it to variable or use it as part of an expressionx math cos(radiansgolden (math sqrt( when you call function in interactive modepython displays the resultmath sqrt( but in scriptif you call fruitful function and do not store the result of the function in variablethe return value vanishes into the mistmath sqrt( this script computes the square root of but since it doesn' store the result in variable or display the resultit is not very useful void functions might display something on the screen or have some other effectbut they don' have return value if you try to assign the result to variableyou get special value called none result print_twice('bing'bing bing print(resultnone the value none is not the same as the string "noneit is special value that has its own typeprint(type(none)to return result from functionwe use the return statement in our function for examplewe could make very simple function called addtwo that adds two numbers together and returns result |
6,484 | functions def addtwo(ab)added return added addtwo( print(xcodewhen this script executesthe print statement will print out " because the addtwo function was called with and as arguments within the functionthe parameters and were and respectively the function computed the sum of the two numbers and placed it in the local function variable named added then it used the return statement to send the computed value back to the calling code as the function resultwhich was assigned to the variable and printed out why functionsit may not be clear why it is worth the trouble to divide program into functions there are several reasonscreating new function gives you an opportunity to name group of statementswhich makes your program easier to readunderstandand debug functions can make program smaller by eliminating repetitive code laterif you make changeyou only have to make it in one place dividing long program into functions allows you to debug the parts one at time and then assemble them into working whole well-designed functions are often useful for many programs once you write and debug oneyou can reuse it throughout the rest of the bookoften we will use function definition to explain concept part of the skill of creating and using functions is to have function properly capture an idea such as "find the smallest value in list of valueslater we will show you code that finds the smallest in list of values and we will present it to you as function named min which takes list of values as its argument and returns the smallest value in the list debugging if you are using text editor to write your scriptsyou might run into problems with spaces and tabs the best way to avoid these problems is to use spaces exclusively (no tabsmost text editors that know about python do this by defaultbut some don' tabs and spaces are usually invisiblewhich makes them hard to debugso try to find an editor that manages indentation for you |
6,485 | alsodon' forget to save your program before you run it some development environments do this automaticallybut some don' in that casethe program you are looking at in the text editor is not the same as the program you are running debugging can take long time if you keep running the same incorrect program over and overmake sure that the code you are looking at is the code you are running if you're not sureput something like print("hello"at the beginning of the program and run it again if you don' see helloyou're not running the right program glossary algorithm general process for solving category of problems argument value provided to function when the function is called this value is assigned to the corresponding parameter in the function body the sequence of statements inside function definition composition using an expression as part of larger expressionor statement as part of larger statement deterministic pertaining to program that does the same thing each time it runsgiven the same inputs dot notation the syntax for calling function in another module by specifying the module name followed by dot (periodand the function name flow of execution the order in which statements are executed during program run fruitful function function that returns value function named sequence of statements that performs some useful operation functions may or may not take arguments and may or may not produce result function call statement that executes function it consists of the function name followed by an argument list function definition statement that creates new functionspecifying its nameparametersand the statements it executes function object value created by function definition the name of the function is variable that refers to function object header the first line of function definition import statement statement that reads module file and creates module object module object value created by an import statement that provides access to the data and code defined in module parameter name used inside function to refer to the value passed as an argument pseudorandom pertaining to sequence of numbers that appear to be randombut are generated by deterministic program return value the result of function if function call is used as an expressionthe return value is the value of the expression void function function that does not return value |
6,486 | functions exercises exercise what is the purpose of the "defkeyword in pythonait is slang that means "the following code is really coolbit indicates the start of function cit indicates that the following indented section of code is to be stored for later db and are both true enone of the above exercise what will the following python program print outdef fred()print("zap"def jane()print("abc"jane(fred(jane(azap abc jane fred jane bzap abc zap cabc zap jane dabc zap abc ezap zap zap exercise rewrite your pay computation with time-and- -half for overtime and create function called computepay which takes two parameters (hours and rateenter hours enter rate pay exercise rewrite the grade program from the previous using function called computegrade that takes score as its parameter and returns grade as string score > > > > grade enter score enter scoreperfect bad score |
6,487 | enter score bad score enter score enter score run the program repeatedly to test the various different values for input |
6,488 | functions |
6,489 | iteration updating variables common pattern in assignment statements is an assignment statement that updates variablewhere the new value of the variable depends on the old this means "get the current value of xadd and then update with the new value if you try to update variable that doesn' existyou get an errorbecause python evaluates the right side before it assigns value to xx nameerrorname 'xis not defined before you can update variableyou have to initialize itusually with simple assignmentx updating variable by adding is called an incrementsubtracting is called decrement the while statement computers are often used to automate repetitive tasks repeating identical or similar tasks without making errors is something that computers do well and people do poorly because iteration is so commonpython provides several language features to make it easier one form of iteration in python is the while statement here is simple program that counts down from five and then says "blastoff! |
6,490 | iteration while print(nn print('blastoff!'you can almost read the while statement as if it were english it means"while is greater than display the value of and then reduce the value of by when you get to exit the while statement and display the word blastoff!more formallyhere is the flow of execution for while statement evaluate the conditionyielding true or false if the condition is falseexit the while statement and continue execution at the next statement if the condition is trueexecute the body and then go back to step this type of flow is called loop because the third step loops back around to the top we call each time we execute the body of the loop an iteration for the above loopwe would say"it had five iterations"which means that the body of the loop was executed five times the body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates we call the variable that changes each time the loop executes and controls when the loop finishes the iteration variable if there is no iteration variablethe loop will repeat foreverresulting in an infinite loop infinite loops an endless source of amusement for programmers is the observation that the directions on shampoo"latherrinserepeat,are an infinite loop because there is no iteration variable telling you how many times to execute the loop in the case of countdownwe can prove that the loop terminates because we know that the value of is finiteand we can see that the value of gets smaller each time through the loopso eventually we have to get to other times loop is obviously infinite because it has no iteration variable at all sometimes you don' know it' time to end loop until you get half way through the body in that case you can write an infinite loop on purpose and then use the break statement to jump out of the loop this loop is obviously an infinite loop because the logical expression on the while statement is simply the logical constant truen while trueprint(nend=' print('done!' |
6,491 | if you make the mistake and run this codeyou will learn quickly how to stop runaway python process on your system or find where the power-off button is on your computer this program will run forever or until your battery runs out because the logical expression at the top of the loop is always true by virtue of the fact that the expression is the constant value true while this is dysfunctional infinite loopwe can still use this pattern to build useful loops as long as we carefully add code to the body of the loop to explicitly exit the loop using break when we have reached the exit condition for examplesuppose you want to take input from the user until they type done you could writewhile trueline input(''if line ='done'break print(lineprint('done!'codethe loop condition is truewhich is always trueso the loop runs repeatedly until it hits the break statement each time throughit prompts the user with an angle bracket if the user types donethe break statement exits the loop otherwise the program echoes whatever the user types and goes back to the top of the loop here' sample runhello there hello there finished finished done donethis way of writing while loops is common because you can check the condition anywhere in the loop (not just at the topand you can express the stop condition affirmatively ("stop when this happens"rather than negatively ("keep going until that happens " finishing iterations with continue sometimes you are in an iteration of loop and want to finish the current iteration and immediately jump to the next iteration in that case you can use the continue statement to skip to the next iteration without finishing the body of the loop for the current iteration here is an example of loop that copies its input until the user types "done"but treats lines that start with the hash character as lines not to be printed (kind of like python comments |
6,492 | iteration while trueline input(''if line[ ='#'continue if line ='done'break print(lineprint('done!'codehere is sample run of this new program with continue added hello there hello there don' print this print thisprint thisdone doneall the lines are printed except the one that starts with the hash sign because when the continue is executedit ends the current iteration and jumps back to the while statement to start the next iterationthus skipping the print statement definite loops using for sometimes we want to loop through set of things such as list of wordsthe lines in fileor list of numbers when we have list of things to loop throughwe can construct definite loop using for statement we call the while statement an indefinite loop because it simply loops until some condition becomes falsewhereas the for loop is looping through known set of items so it runs through as many iterations as there are items in the set the syntax of for loop is similar to the while loop in that there is for statement and loop bodyfriends ['joseph''glenn''sally'for friend in friendsprint('happy new year:'friendprint('done!'in python termsthe variable friends is list of three strings and the for loop goes through the list and executes the body once for each of the three strings in the list resulting in this output we will examine lists in more detail in later |
6,493 | happy new yearjoseph happy new yearglenn happy new yearsally donetranslating this for loop to english is not as direct as the whilebut if you think of friends as setit goes like this"run the statements in the body of the for loop once for each friend in the set named friends looking at the for loopfor and in are reserved python keywordsand friend and friends are variables for friend in friendsprint('happy new year:'friendin particularfriend is the iteration variable for the for loop the variable friend changes for each iteration of the loop and controls when the for loop completes the iteration variable steps successively through the three strings stored in the friends variable loop patterns often we use for or while loop to go through list of items or the contents of file and we are looking for something such as the largest or smallest value of the data we scan through these loops are generally constructed byinitializing one or more variables before the loop starts performing some computation on each item in the loop bodypossibly changing the variables in the body of the loop looking at the resulting variables when the loop completes we will use list of numbers to demonstrate the concepts and construction of these loop patterns counting and summing loops for exampleto count the number of items in listwe would write the following for loopcount for itervar in [ ]count count print('count'count |
6,494 | iteration we set the variable count to zero before the loop startsthen we write for loop to run through the list of numbers our iteration variable is named itervar and while we do not use itervar in the loopit does control the loop and cause the loop body to be executed once for each of the values in the list in the body of the loopwe add to the current value of count for each of the values in the list while the loop is executingthe value of count is the number of values we have seen "so faronce the loop completesthe value of count is the total number of items the total number "falls in our lapat the end of the loop we construct the loop so that we have what we want when the loop finishes another similar loop that computes the total of set of numbers is as followstotal for itervar in [ ]total total itervar print('total'totalin this loop we do use the iteration variable instead of simply adding one to the count as in the previous loopwe add the actual number ( etc to the running total during each loop iteration if you think about the variable totalit contains the "running total of the values so farso before the loop starts total is zero because we have not yet seen any valuesduring the loop total is the running totaland at the end of the loop total is the overall total of all the values in the list as the loop executestotal accumulates the sum of the elementsa variable used this way is sometimes called an accumulator neither the counting loop nor the summing loop are particularly useful in practice because there are built-in functions len(and sum(that compute the number of items in list and the total of the items in the list respectively maximum and minimum loops to find the largest value in list or sequencewe construct the following looplargest none print('before:'largestfor itervar in [ ]if largest is none or itervar largest largest itervar print('loop:'itervarlargestprint('largest:'largestwhen the program executesthe output is as followsbeforenone loop |
6,495 | loop loop loop loop loop largest the variable largest is best thought of as the "largest value we have seen so farbefore the loopwe set largest to the constant none none is special constant value which we can store in variable to mark the variable as "emptybefore the loop startsthe largest value we have seen so far is none since we have not yet seen any values while the loop is executingif largest is none then we take the first value we see as the largest so far you can see in the first iteration when the value of itervar is since largest is nonewe immediately set largest to be after the first iterationlargest is no longer noneso the second part of the compound logical expression that checks itervar largest triggers only when we see value that is larger than the "largest so farwhen we see new "even largervalue we take that new value for largest you can see in the program output that largest progresses from to to at the end of the loopwe have scanned all of the values and the variable largest now does contain the largest value in the list to compute the smallest numberthe code is very similar with one small changesmallest none print('before:'smallestfor itervar in [ ]if smallest is none or itervar smallestsmallest itervar print('loop:'itervarsmallestprint('smallest:'smallestagainsmallest is the "smallest so farbeforeduringand after the loop executes when the loop has completedsmallest contains the minimum value in the list again as in counting and summingthe built-in functions max(and min(make writing these exact loops unnecessary the following is simple version of the python built-in min(functiondef min(values)smallest none for value in valuesif smallest is none or value smallestsmallest value return smallest in the function version of the smallest codewe removed all of the print statements so as to be equivalent to the min function which is already built in to python |
6,496 | iteration debugging as you start writing bigger programsyou might find yourself spending more time debugging more code means more chances to make an error and more places for bugs to hide one way to cut your debugging time is "debugging by bisection for exampleif there are lines in your program and you check them one at timeit would take steps insteadtry to break the problem in half look at the middle of the programor near itfor an intermediate value you can check add print statement (or something else that has verifiable effectand run the program if the mid-point check is incorrectthe problem must be in the first half of the program if it is correctthe problem is in the second half every time you perform check like thisyou halve the number of lines you have to search after six steps (which is much less than )you would be down to one or two lines of codeat least in theory in practice it is not always clear what the "middle of the programis and not always possible to check it it doesn' make sense to count lines and find the exact midpoint insteadthink about places in the program where there might be errors and places where it is easy to put check then choose spot where you think the chances are about the same that the bug is before or after the check glossary accumulator variable used in loop to add up or accumulate result counter variable used in loop to count the number of times something happened we initialize counter to zero and then increment the counter each time we want to "countsomething decrement an update that decreases the value of variable initialize an assignment that gives an initial value to variable that will be updated increment an update that increases the value of variable (often by oneinfinite loop loop in which the terminating condition is never satisfied or for which there is no terminating condition iteration repeated execution of set of statements using either function that calls itself or loop exercises exercise write program which repeatedly reads numbers until the user enters "doneonce "doneis enteredprint out the totalcountand average of the numbers if the user enters anything other than numberdetect their mistake using try and except and print an error message and skip to the next number |
6,497 | enter number enter number enter numberbad data invalid input enter number enter numberdone exercise write another program that prompts for list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average |
6,498 | iteration |
6,499 | strings string is sequence string is sequence of characters you can access the characters one at time with the bracket operatorfruit 'bananaletter fruit[ the second statement extracts the character at index position from the fruit variable and assigns it to the letter variable the expression in brackets is called an index the index indicates which character in the sequence you want (hence the namebut you might not get what you expectprint(lettera for most peoplethe first letter of "bananais " "not "abut in pythonthe index is an offset from the beginning of the stringand the offset of the first letter is zero letter fruit[ print(letterb so "bis the th letter ("zero-th"of "banana""ais the th letter ("one-th")and "nis the th ("two-th"letter you can use any expressionincluding variables and operatorsas an indexbut the value of the index has to be an integer otherwise you getletter fruit[ typeerrorstring indices must be integers |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.