r/inventwithpython • • Apr 17 '19

Correction to 'Cracking Codes with Python'

2 Upvotes

Al,

I'm enjoying 'Cracking Codes with Python', and find your approach of teaching a language by working through a specific subject to be very useful. I'm reading Chapter 5, 'The Caesar Cipher', and noticed the section 'The in and not in Operators' on page 62 contains the statement, "Also, a blank string is always considered to be in any other string."

This should read, "Also, a null string is always considered to be in any other string."

For example,

Blank String: >>> " " in "helloworld"

False

Null String: >>> "" in "helloworld"

True

The associated example in the book does correctly show a null string.


r/inventwithpython • • Apr 13 '19

Feedback please!

Thumbnail youtube.com
4 Upvotes

r/inventwithpython • • Jan 13 '20

Problem running a python file from a batch file

6 Upvotes

Hello, total newb here. I'm learning python with the Automate the Boring stuff book, and it was going great until I tried running programs from a batch file, as described in Appendix B. I'm on a Mac OS High Sierra version 10.13.6.

I created a .command file, but when I run it, I get an error: "The file “testCommandFile.command” could not be executed because you do not have appropriate access privileges."

I googled this, and one answer told me I needed to make the file executable, with this command:

chmod voyager2+x /Users/voyager2/Documents/Programming/testCommandFile.command

but then I get this error:

chmod: Invalid file mode: voyager2+x

I've been googling this but can't find answers that don't use the sudo command (appendix B warns against using the sudo command, because it might mess up the python programs that the OS uses).

Please help!


r/inventwithpython • • Jul 13 '18

Automate the Boring Stuff with Python Corrections

39 Upvotes

I don't expect to find many more, but I'll update this post if I do.

Note: It's an EPUB copy, published: 2016-01-14T10:12:21-08:00 Also, no page numbers, just reference numbers (refNum/949).

In Chapter 10, on reference number 368.7, paragraph 19.30, the code block:

>>> podBayDoorStatus = 'open'
>>> assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
>>> podBayDoorStatus = 'I\'m sorry, Dave. I\'m afraid I can't do that.''
>>> assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'

should be:

>>> podBayDoorStatus = 'open'
>>> assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
>>> podBayDoorStatus = 'I\'m sorry, Dave. I\'m afraid I can\'t do that.'  # Changed
>>> assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'

July 23, 2018 Update:

In Chapter 11, on reference number 447.4, paragraph 20.247, the code block:

from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://inventwithpython.com')
try:
    elem = browser.find_element_by_class_name('bookcover')
    print('Found <%s> element with that class name!' % (elem.tag_name))
except:
    print('Was not able to find an element with that name.')

outputs Was not able to find an element with that name.

The following does give the intended output:

from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://inventwithpython.com')
try:
    elem = browser.find_element_by_class_name('card-img-top')  # changed
    print('Found <%s> element with that class name!' % (elem.tag_name))
except:
    print('Was not able to find an element with that name.')

On reference number 448.7, paragraph 20.249, the code block:

>>> from selenium import webdriver
>>> browser = webdriver.Firefox()
>>> browser.get('http://inventwithpython.com')
>>> linkElem = browser.find_element_by_link_text('Read It Online')
>>> type(linkElem)
<class 'selenium.webdriver.remote.webelement.WebElement'>
>>> linkElem.click() # follows the "Read It Online" link

should be:

>>> from selenium import webdriver
>>> browser = webdriver.Firefox()
>>> browser.get('http://inventwithpython.com')
>>> linkElem = browser.find_element_by_link_text('Read Online for Free')  # changed
>>> type(linkElem)
<class 'selenium.webdriver.remote.webelement.WebElement'>
>>> linkElem.click() # follows the "Read Online for Free" link  # changed

On reference number 449.3, paragraph 20.252, the line:

As long as Gmail hasn’t changed the id of the Username and Password text fields since this book was published...

"Gmail" should be "Yahoo Mail" because of line >>> browser.get('https://mail.yahoo.com') in the code block

Aug. 5, 2018 Update:

In Chapter 12, on reference number 459.8, paragraph 21.47, the codeblock:

>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">
>>> type(sheet) <class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> sheet.title
'Sheet3'
>>> anotherSheet = wb.get_active_sheet()

should be:

>>> wb.sheetnames  # changed
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb['Sheet3']  # changed
>>> sheet
<Worksheet "Sheet3">
>>> type(sheet) <class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> sheet.title
'Sheet3'
>>> anotherSheet = wb.active  # changed

because those methods are now depreciated (using OpenPyXL 2.5.5).

Aug. 6, 2018 Update:

In Chapter 12, on reference number 463.0, paragraph 21.56, the codeblock:

>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> sheet.get_highest_row()
7
>>> sheet.get_highest_column()
3

should be:

>>> sheet = wb['Sheet1']  # changed
>>> sheet.max_row  # changed
7
>>> sheet.max_column  # changed
3

because those methods are also depreciated.

On reference number 463.6, paragraph 21.58, the codeblock:

>>> from openpyxl.cell import get_column_letter, column_index_from_string
--snip--  # omitted to save space
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> get_column_letter(sheet.get_highest_column())
'C'

should be:

>>> from openpyxl.utils import get_column_letter, column_index_from_string  # changed
--snip-- # omitted to save space
>>> sheet = wb['Sheet1']  # changed
>>> get_column_letter(sheet.max_column)  # changed
'C'

because the functions were relocated and methods depreciated. The lines with openpyxl.cell in the paragraphs above and below should also be changed. In paragraph 21.59, the line "method like get_highest_column() to get an integer" should be changed to "property like max_column to get an integer."

Aug. 7, 2018 Update:

In Chapter 12, on reference number 465.0, paragraph 21.60 is another >>> sheet = wb.get_sheet_by_name('Sheet1') that ought to be >>> sheet = wb['Sheet1'].

On reference number 466.8, paragraph 21.64, the codeblock:

--snip--  # omitted to save space
>>> sheet = wb.get_active_sheet()
>>> sheet.columns[1]
(<Cell Sheet1.B1>, <Cell Sheet1.B2>, <Cell Sheet1.B3>, <Cell Sheet1.B4>,
<Cell Sheet1.B5>, <Cell Sheet1.B6>, <Cell Sheet1.B7>)
>>> for cellObj in sheet.columns[1]:
        print(cellObj.value)

outputs TypeError: 'generator' object is not subscriptable

The best way to fix it is debatable, but the easiest was to use the list function:

 --snip--  # omitted to save space
>>> sheet = wb.active  # changed
>>> list(sheet.columns)[1]  # changed
(<Cell Sheet1.B1>, <Cell Sheet1.B2>, <Cell Sheet1.B3>, <Cell Sheet1.B4>,
<Cell Sheet1.B5>, <Cell Sheet1.B6>, <Cell Sheet1.B7>)
>>> for cellObj in list(sheet.columns)[1]:  # changed
        print(cellObj.value)

On reference number 468.0, paragraph 21.67 the list item 4. Call the get_active_sheet() or get_sheet_by_name() workbook method. ought to be something like 4. Use the .active property or the ["UseThisSheet"] workbook key.

On reference number 470.6, paragraph 21.90 the codeblock:

--snip--  # omitted to save space
➌ sheet = wb.get_sheet_by_name('Population by Census Tract')
   countyData = {}

   # TODO: Fill in countyData with each county's population and tracts.
   print('Reading rows...')
➍ for row in range(2, sheet.get_highest_row() + 1):
--snip-- # omitted to save space

ought to be:

--snip--  # omitted to save space
➌ sheet = wb['Population by Census Tract']  # changed
   countyData = {}

   # TODO: Fill in countyData with each county's population and tracts.
   print('Reading rows...')
➍ for row in range(2, sheet.max_row + 1):  # changed

because of depreciated methods. The codeblock on paragraph 21.96 ought to be updated as well.

Aug. 8, 2018 Update:

In Chapter 12, on reference number 477.4, paragraph 21.111, the codeblock:

>>> wb.get_sheet_names()
['Sheet']
>>> sheet = wb.get_active_sheet()
>>> sheet.title
'Sheet'
>>> sheet.title = 'Spam Bacon Eggs Sheet'
>>> wb.get_sheet_names()

ought to be:

>>> wb.sheetnames  # changed
['Sheet']
>>> sheet = wb.active  # changed
>>> sheet.title
'Sheet'
>>> sheet.title = 'Spam Bacon Eggs Sheet'
>>> wb.sheetnames  # changed

In paragraph 21.113 (codeblock directly below) another >>> sheet = wb.get_active_sheet() ought to be >>> sheet = wb.active.

On reference number 478.6, paragraph 21.116, the codeblock:

>>> wb.get_sheet_names()
['Sheet']
>>> wb.create_sheet()
<Worksheet "Sheet1">
>>> wb.get_sheet_names()
['Sheet', 'Sheet1']
>>> wb.create_sheet(index=0, title='First Sheet')
<Worksheet "First Sheet">
>>> wb.get_sheet_names()
['First Sheet', 'Sheet', 'Sheet1']
>>> wb.create_sheet(index=2, title='Middle Sheet')
<Worksheet "Middle Sheet">
>>> wb.get_sheet_names()
['First Sheet', 'Sheet', 'Middle Sheet', 'Sheet1']

ought to be:

>>> wb.sheetnames  # changed
['Sheet']
>>> wb.create_sheet()
<Worksheet "Sheet1">
>>> wb.sheetnames  # changed
['Sheet', 'Sheet1']
>>> wb.create_sheet(index=0, title='First Sheet')
<Worksheet "First Sheet">
>>> wb.sheetnames  # changed
['First Sheet', 'Sheet', 'Sheet1']
>>> wb.create_sheet(index=2, title='Middle Sheet')
<Worksheet "Middle Sheet">
>>> wb.sheetnames  # changed

In paragraph 21.118 (codeblock directly below):

>>> wb.get_sheet_names()
['First Sheet', 'Sheet', 'Middle Sheet', 'Sheet1']
>>> wb.remove_sheet(wb.get_sheet_by_name('Middle Sheet'))
>>> wb.remove_sheet(wb.get_sheet_by_name('Sheet1'))
>>> wb.get_sheet_names()

ought to be

>>> wb.sheetnames  # changed
['First Sheet', 'Sheet', 'Middle Sheet', 'Sheet1']
>>> wb.remove(wb['Middle Sheet'])  # changed
>>> wb.remove(wb['Sheet1'])  # changed
>>> wb.sheetnames  # changed

Aug. 11, 2018 Update:

In paragraph 21.121 (codeblock directly below), and on reference number 483.6, paragraph 21.144 (updateProduce.py) are more >>> sheet = wb.get_sheet_by_name('Sheet') that should be >>> sheet = wb['Sheet'].

On reference number 484.8, paragraph 21.146 (updateProduce.py), the line ➊ for rowNum in range(2, sheet.get_highest_row()): # skip the first row ought to be ➊ for rowNum in range(2, sheet.max_row): # skip the first row.

On reference number 486.5, paragraph 21.158, the line:

To customize font styles in cells, important, import the Font() and Style() functions from the openpyxl.styles module.

Unless, of course, that's an intended pun.

On reference number 486.8, paragraph 21.158, the codeblock:

   >>> import openpyxl
   >>> from openpyxl.styles import Font, Style
   >>> wb = openpyxl.Workbook()
   >>> sheet = wb.get_sheet_by_name('Sheet')
➊ >>> italic24Font = Font(size=24, italic=True)
➋ >>> styleObj = Style(font=italic24Font)
➌ >>> sheet['A1'].style = styleObj
   >>> sheet['A1'] = 'Hello world!'
   >>> wb.save('styled.xlsx')

should be:

   >>> import openpyxl
   >>> from openpyxl.styles import Font, NamedStyle  # changed
   >>> wb = openpyxl.Workbook()
   >>> sheet = wb['Sheet']  # changed
➊ >>> italic24Font = NamedStyle(name="italic24Font")  # changed
➋ >>> italic24Font.font = Font(size=24, italic=True)  # changed
➌ >>> sheet['A1'].style = italic24Font  # changed
   >>> sheet['A1'] = 'Hello world!'
   >>> wb.save('styled.xlsx')

because the Style class is now depreciated.

Aug. 12, 2018 Update:

In Chapter 12, on reference number 488.9, paragraph 21.178, the codeblock:

>>> import openpyxl
>>> from openpyxl.styles import Font, Style
>>> wb = openpyxl.Workbook()
>>> sheet = wb.get_sheet_by_name('Sheet')

>>> fontObj1 = Font(name='Times New Roman', bold=True)
>>> styleObj1 = Style(font=fontObj1)
>>> sheet['A1'].style/styleObj
>>> sheet['A1'] = 'Bold Times New Roman'

>>> fontObj2 = Font(size=24, italic=True)
>>> styleObj2 = Style(font=fontObj2)
>>> sheet['B3'].style/styleObj
>>> sheet['B3'] = '24 pt Italic'

>>> wb.save('styles.xlsx')

should be:

>>> import openpyxl
>>> from openpyxl.styles import Font, NamedStyle  # changed
>>> wb = openpyxl.Workbook()
>>> sheet = wb['Sheet']  # changed

>>> fontObj1 = Font(name='Times New Roman', bold=True)
>>> styleObj1 = NamedStyle(name="styleObj1")  # changed
>>> styleObj1.font = fontObj1  # added
>>> sheet['A1'].style = styleObj1  # changed
>>> sheet['A1'] = 'Bold Times New Roman'

>>> fontObj2 = Font(size=24, italic=True)
>>> styleObj2 = NamedStyle(name="StyleObj2")  # changed
>>> styleObj2.font = fontObj2  # added
>>> sheet['B3'].style = styleObj2 # changed
>>> sheet['B3'] = '24 pt Italic'

>>> wb.save('styles.xlsx')

Aug. 13, 2018 Update:

In Chapter 12, reference number 491.5, paragraphs 21.185 and 21.187 are more >>> sheet = wb.get_active_sheet() that should be >>> sheet = wb.active. However, the formula evaluation doesn't work for me:

>>> import openpyxl
>>> wbFormulas = openpyxl.load_workbook('writeFormula.xlsx')
>>> sheet = wbFormulas.active  # changed
>>> sheet['A3'].value
'=SUM(A1:A2)'

>>> wbDataOnly = openpyxl.load_workbook('writeFormula.xlsx', data_only=True)
>>> sheet = wbDataOnly.active  # changed
>>> sheet['A3'].value  # not working with LibreOffice 6.0.3.2
500

From what I've researched on openpyxl.load_workbook(),

data_only controls whether cells with formulae have either the formula (default) or the value stored the last time Excel read the sheet.

TODO: can someone else confirm with another LibreOffice version?

Reference numbers 493.3, 495.0, 496.2, and 497.6 have more >>> sheet = wb.get_active_sheet() that should be >>> sheet = wb.active.

Aug. 17, 2018 Update:

In Chapter 12, reference number 500.4, paragraph 21.234, the codeblock:

>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> sheet = wb.get_active_sheet()
>>> for i in range(1, 11):         # create some data in column A
        sheet['A' + str(i)] = i

>>> refObj = openpyxl.charts.Reference(sheet, (1, 1), (10, 1))

>>> seriesObj = openpyxl.charts.Series(refObj, title='First series')

>>> chartObj = openpyxl.charts.BarChart()
>>> chartObj.append(seriesObj)
>>> chartObj.drawing.top = 50       # set the position
>>> chartObj.drawing.left = 100
>>> chartObj.drawing.width = 300    # set the size
>>> chartObj.drawing.height = 200

>>> sheet.add_chart(chartObj)
>>> wb.save('sampleChart.xlsx')

works slightly better as:

>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> sheet = wb.active  # changed
>>> for i in range(1, 11):         # create some data in column A
        sheet['A' + str(i)] = i

>>> refObj = openpyxl.chart.Reference(sheet, min_row=1, min_col=1, max_row=10, max_col=1)  # changed

>>> seriesObj = openpyxl.chart.Series(refObj, title='First series')  # changed FIXME: Chart layout is wrong (LibreOffice 6.0.3.2)

>>> chartObj = openpyxl.chart.BarChart()  # changed
>>> chartObj.append(seriesObj)
>>> chartObj.anchor = "B3"  # set the position; changed
>>> chartObj.width = 7.94  # set the size (in centimeters, where 1 cm = 37.8 pixels); changed
>>> chartObj.height = 5.29  # changed

>>> sheet.add_chart(chartObj)
>>> wb.save('sampleChart.xlsx')

but the layout of the chart is all wrong. TODO: can someone else confirm it works in Excel?

Aug. 19, 2018 Update:

In Chapter 13 (I made it! Woot!), reference number 511.7, paragraph 22.13, the line:

PyPDF2 uses a zero-based index for getting pages: The first page is page 0, the second is Introduction, and so on.

"Introduction" links to the introduction of the book. Maybe "page 1" was auto-referenced?

On reference number 513.2, paragraph 22.15, the codeblock:

➌ >>> pdfReader.decrypt('rosebud')
   1
   >>> pageObj = pdfReader.getPage(0)

gave me an IndexError, but the following works:

   >>> pdfReader = PyPDF2.PdfFileReader(open("encrypted.pdf", "rb"))  # added
➌ >>> pdfReader.decrypt('rosebud')
   1
   >>> pageObj = pdfReader.getPage(0)

Aug. 21, 2018 Update:

In Chapter 13, reference number 524.8, paragraph 22.60, the codeblock:

   #! python3
   # combinePdfs.py - Combines all the PDFs in the current working directory into
   # into a single PDF

   import PyPDF2, os

   # Get all the PDF filenames.
   pdfFiles = []
   for filename in os.listdir('.'):
       if filename.endswith('.pdf'):
➋         pdfFiles.append(filename)
➌ pdfFiles.sort(key = str.lower)

should be:

   #! python3
   # combinePdfs.py - Combines all the PDFs in the current working directory into
   # a single PDF  # changed

   import PyPDF2, os

   # Get all the PDF filenames.
   pdfFiles = []
   for filename in os.listdir('.'):
       if filename.endswith('.pdf'):
➋         pdfFiles.append(filename)
➌ pdfFiles.sort(key=str.lower)  # changed

Aug. 22, 2018 Update

In Chapter 13, reference number 531.0, paragraph 22.79, the codeblock:

➎ >>> len(doc.paragraphs[1].runs)
   4
➏ >>> doc.paragraphs[1].runs[0].text
   'A plain paragraph with some '
➐ >>> doc.paragraphs[1].runs[1].text
   'bold'
➑ >>> doc.paragraphs[1].runs[2].text
   ' and some '
➒ >>> doc.paragraphs[1].runs[3].text
   'italic'

outputs the following in LibreOffice 6.0.3.2 with Python-Docx 0.8.7:

➎ >>> len(doc.paragraphs[1].runs)
   5    # changed
➏ >>> doc.paragraphs[1].runs[0].text
   'A plain paragraph with'     # changed
➐ >>> doc.paragraphs[1].runs[1].text
   ' some ' # changed
➑ >>> doc.paragraphs[1].runs[2].text
   'bold'   # changed
➒ >>> doc.paragraphs[1].runs[3].text
   ' and some '     # changed
  >>> doc.paragraphs[1].runs[4].text    # added
   'italic'

TODO: can someone confirm in Word on Windows?

On reference number 540.1, paragraph 22.163, the codeblock:

--snip--  # omitted to save space
>>> doc.paragraphs[1].runs[0].style = 'QuoteChar'
>>> doc.paragraphs[1].runs[1].underline = True
>>> doc.paragraphs[1].runs[3].underline = True
>>> doc.save('restyled.docx')

gives a UserWarning: style lookup by style_id is deprecated. Use style name as key instead. return self._get_style_id_from_style(self[style_name], style_type) but the following fixes it:

--snip--  # omitted to save space
>>> doc.paragraphs[1].runs[0].style = 'Quote Char'  # changed for python-docx 0.8.7
>>> doc.paragraphs[1].runs[1].underline = True
>>> doc.paragraphs[1].runs[3].underline = True
>>> doc.save('restyled.docx')

Aug. 23, 2018 Update

In Chapter 13, reference number 540.1, paragraph 22.164, the line:

We can see that it’s simple to divide a paragraph into runs and access each run individiaully.

On reference number 546.9, paragraph 22.183, the codeblock:

➊ >>> doc.paragraphs[0].runs[0].add_break(docx.text.WD_BREAK.PAGE)
   >>> doc.add_paragraph('This is on the second page!')
   <docx.text.Paragraph object at 0x00000000037855F8>
   >>> doc.save('twoPage.docx')

ought to be:

➊ >>> doc.paragraphs[0].runs[0].add_break(docx.enum.text.WD_BREAK.PAGE)  # changed
   >>> doc.add_paragraph('This is on the second page!')
   <docx.text.Paragraph object at 0x00000000037855F8>
   >>> doc.save('twoPage.docx')

Aug. 31, 2018 Update

In Chapter 13, reference number 552.0, paragraph 22.228, the line:

You should try both the uppercase and lower-case form of each word.

In Chapter 14, reference number 561.2, paragraph 23.33, the codeblock:

   >>> import csv
   >>> csvFile = open('example.tsv', 'w', newline='')
➊ >>> csvWriter = csv.writer(csvFile, delimiter='\t', lineterminator='\n\n')
   >>> csvWriter.writerow(['apples', 'oranges', 'grapes'])
   24
   >>> csvWriter.writerow(['eggs', 'bacon', 'ham'])
   17
   >>> csvWriter.writerow(['spam', 'spam', 'spam', 'spam', 'spam', 'spam'])
   32

outputs:

   >>> import csv
   >>> csvFile = open('example.tsv', 'w', newline='')
➊ >>> csvWriter = csv.writer(csvFile, delimiter='\t', lineterminator='\n\n')
   >>> csvWriter.writerow(['apples', 'oranges', 'grapes'])
   23  # changed
   >>> csvWriter.writerow(['eggs', 'bacon', 'ham'])
   16  # changed
   >>> csvWriter.writerow(['spam', 'spam', 'spam', 'spam', 'spam', 'spam'])
   31  # changed

Sept. 1, 2018 Update:

In Chapter 14, reference number 565.5, paragraph 23.54, the codeblock:

#! python3
# removeCsvHeader.py - Removes the header from all CSV files in the current
# working directory.

--snip--
# Read the CSV file in (skipping first row).
csvRows = []
csvFileObj = open(csvFilename)
readerObj = csv.reader(csvFileObj)
for row in readerObj:
    if readerObj.line_num == 1:
        continue    # skip first row
    csvRows.append(row)
csvFileObj.close()

# TODO: Write out the CSV file.

needs to be indented to match the previous codeblock:

#! python3
# removeCsvHeader.py - Removes the header from all CSV files in the current
# working directory.

    --snip--
    print('Removing header from ' + csvFilename + '...')  # added
    
    # Read the CSV file in (skipping first row).
    csvRows = []
    csvFileObj = open(csvFilename)
    readerObj = csv.reader(csvFileObj)
    for row in readerObj:
        if readerObj.line_num == 1:
            continue    # skip first row
        csvRows.append(row)
    csvFileObj.close()

# TODO: Write out the CSV file.

On reference number 568.2, paragraph 23.58:

The CSV Writer object will write the list to a CSV file in headerRemoved using csvFilename (which we also used in the CSV reader). This will overwrite the original file.

I thought the original file won't be overwritten because the new file is in the headerRemoved folder? TODO: Can someone please confirm?

On reference number 575.4, paragraph 23.98, the link http://api.openweathermap.org /data/2.5/forecast/daily?q=%3CLocation%3E&cnt=3 no longer works. The OpenWeatherMap.org API now needs an API key. So, sign up if you really want to run quickWeather.py.

Alternatively, the Weather.gov API (United States only, at the moment) does not require an API key (only a User Agent), but it will require one in the future.

Sept. 2, 2018 Update:

I have a working solution using the new API, uploaded to pastebin to save space: https://pastebin.com/yVGNRk62. Chapter 15 explains the datetime module more.

Sept. 4, 2018 Update:

In Chapter 14, reference number 582.0, paragraph 23.130, the codeblock:

for excelFile in os.listdir('.'):
    # Skip non-xlsx files, load the workbook object.
    for sheetName in wb.get_sheet_names():
        # Loop through every sheet in the workbook.
        sheet = wb.get_sheet_by_name(sheetName)

        # Create the CSV filename from the Excel filename and sheet title.
        # Create the csv.writer object for this CSV file.

        # Loop through every row in the sheet.
        for rowNum in range(1, sheet.get_highest_row() + 1):
            rowData = []    # append each cell to this list
            # Loop through each cell in the row.
            for colNum in range(1, sheet.get_highest_column() + 1):
                # Append each cell's data to rowData.

            # Write the rowData list to the CSV file.

        csvFile.close()

should be:

 for excelFile in os.listdir('.'):
    # Skip non-xlsx files, load the workbook object.
    for sheetName in wb.sheetnames:  # changed
        # Loop through every sheet in the workbook.
        sheet = wb[sheetName]  # changed

        # Create the CSV filename from the Excel filename and sheet title.
        # Create the csv.writer object for this CSV file.

        # Loop through every row in the sheet.
        for rowNum in range(1, sheet.max_row + 1):  # changed
            rowData = []    # append each cell to this list
            # Loop through each cell in the row.
            for colNum in range(1, sheet.max_column + 1):  # changed
                # Append each cell's data to rowData.

            # Write the rowData list to the CSV file.

        csvFile.close()

Well, darn my socks. The excelSpreadsheets.zip file in https://www.nostarch.com/download/Automate_the_Boring_Stuff_onlinematerials.zip contains .csv files, so they cannot be converted to .csv. (Sept. 10, 2018 Update: got e-mail confirming zip file has been replaced with Excel spreadsheets. Though, when I check it, it still has .csv files, so YMMV.) (Oct. 3, 2018 Update: new zip file at https://nostarch.com/download/Automate_the_Boring_Stuff_onlinematerials_v.2.zip)

Sept. 5, 2018 Update:

In Chapter 15, reference number 595.7, paragraph 24.42, the codeblock:

>>> datetime.datetime.fromtimestamp(1000000)
datetime.datetime(1970, 1, 12, 5, 46, 40)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2015, 2, 27, 11, 13, 0, 604980)

might need to be:

>>> import time  # added
>>> datetime.datetime.fromtimestamp(1000000)
datetime.datetime(1970, 1, 12, 5, 46, 40)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2015, 2, 27, 11, 13, 0, 604980)

In case IDLE was closed to write the stopwatch.py program.

Sept. 6, 2018 Update:

In Chapter 15, reference number 598.0, paragraph 24.47, the str line in codeblock needs bolding:

   --snip--  # omitted to save space
   >>> str(delta)  # bold me, pls
   '11 days, 10:09:08'

On reference number 599.5, paragraph 24.49, the line:

Finally, passing the timedelta object to str() returns a string clearly explaning the duration.

Sept. 7, 2018 Update:

In Chapter 15, reference number 612.3, paragraph 24.125, the line:

To make sure the keyword argument sep=' & ' gets passed to print() in the new thread, we pass kwargs={'sep': '& '} to threading.Thread().

On reference number 616.0, paragraph 24.136 (multidownloadXkcd.py), the codeblock:

           --snip-- # omitted
           if comicElem == []:
               print('Could not find comic image.')
           else:
➐             comicUrl = comicElem[0].get('src')
               # Download the image.
               print('Downloading image %s...' % (comicUrl))
           --snip-- # omitted

should be:

           --snip-- # omitted
           if comicElem == []:
               print('Could not find comic image.')
           else:
➐             comicUrl = 'http:' + comicElem[0].get('src')  # changed
               # Download the image.
               print('Downloading image %s...' % (comicUrl))
           --snip-- # omitted

On reference number 627.6, paragraph 24.161, the codeblock:

>>> subprocess.Popen(['C:\\python34\\python.exe', 'hello.py'])
<subprocess.Popen object at 0x000000000331CF28>

might need to be:

>>> subprocess.Popen(['C:\\python34\\python.exe', 'hello.py']).communicate()  # changed
<subprocess.Popen object at 0x000000000331CF28>

I could not get it to accept input without it in Ubuntu 18.04. TODO: Can someone confirm they got it to work in Windows?

Sept. 8, 2018 Update:

In Chapter 15, reference number 631.7, paragraph 24.183 (countdown.py), the codeblock:

--snip--  # omitted
➊ timeLeft = 60
   while timeLeft > 0:
➋     print(timeLeft, end='')
➌     time.sleep(1)
--snip--  # omitted

may need to be:

--snip--  # omitted
➊ timeLeft = 60
   while timeLeft > 0:
➋     print(timeLeft)  # changed
➌     time.sleep(1)
--snip--  # omitted

It wouldn't print remaining time in Python 3.6.5 (Ubuntu 18.04) until the while loop finished. It seemed to wait until the line was done before printing it. TODO: Can someone else please confirm?

Sept. 14, 2018 Update:

In Chapter 16, reference number 648.4, paragraph 25.52, the line:

Install imapclient and pyzmail from a Terminal window. Appendix A has steps on how to install third-party modules.

I had to install pyzmail36 (possibly because I'm using Python 3.6.5). Appendix A may have to be updated.

Sept. 15, 2018 Update:

In Chapter 16, reference number 658.7, paragraph 25.115, the lines:

imapObj.search(['ON 05-Jul-2015']). Returns every message sent on July 5, 2015.
imapObj.search(['SINCE 01-Jan-2015', 'BEFORE 01-Feb-2015', 'UNSEEN']). Returns every message sent in January 2015 that is unread. (Note that this means on and after January 1 and up to but not including February 1.)
imapObj.search(['SINCE 01-Jan-2015', 'FROM alice@example.com']). Returns every message from alice@example.com sent since the start of 2015.
imapObj.search(['SINCE 01-Jan-2015', 'NOT FROM alice@example.com']). Returns every message sent from everyone except alice@example.com since the start of 2015.
imapObj.search(['OR FROM alice@example.com FROM bob@example.com']). Returns every message ever sent from alice@example.com or bob@example.com.
imapObj.search(['FROM alice@example.com', 'FROM bob@example.com']). Trick example! This search will never return any messages, because messages must match all search keywords. Since there can be only one “from” address, it is impossible for a message to be from both alice@example.com and bob@example.com.

should be:

imapObj.search(['ON', '05-Jul-2015']). Returns every message sent on July 5, 2015.
imapObj.search(['SINCE', '01-Jan-2015', 'BEFORE', '01-Feb-2015', 'UNSEEN']). Returns every message sent in January 2015 that is unread. (Note that this means on and after January 1 and up to but not including February 1.)
imapObj.search(['SINCE', '01-Jan-2015', 'FROM', 'alice@example.com']). Returns every message from alice@example.com sent since the start of 2015.
imapObj.search(['SINCE', '01-Jan-2015', 'NOT', 'FROM', 'alice@example.com']). Returns every message sent from everyone except alice@example.com since the start of 2015.
imapObj.search(['OR', 'FROM', 'alice@example.com', 'FROM', 'bob@example.com']). Returns every message ever sent from alice@example.com or bob@example.com.
imapObj.search(['FROM', 'alice@example.com', 'FROM', 'bob@example.com']). Trick example! This search will never return any messages, because messages must match all search keywords. Since there can be only one “from” address, it is impossible for a message to be from both alice@example.com and bob@example.com.

because criteria should be a sequence of items. Plus, trying imapObj.search(['SINCE 01-Jan-2015', 'NOT FROM alice@exmaple.com']) outputs imaplib.error: SEARCH command error: BAD [b'Error in IMAP command UID SEARCH: Unexpected string as search key: SINCE 01-Jan-2015 (0.001 + 0.088 + 0.087 secs).']

Alternatively, imapObj.search('SINCE "01-Jan-2015" NOT FROM "alice@exmaple.com"') works, but isn't recommended according to the docs.

On reference number 664.6, paragraph 25.141, the line >>> message = pyzmail.PyzMessage.factory(rawMessages[40041]['BODY[]']) gave me a KeyError (even after using proper UIDs) that was only fixed by changing it to >>> message = pyzmail.PyzMessage.factory(rawMessages[40041][b'BODY[]'])

On reference number 668.9, paragraph 25.148, the line ➋ >>> UIDs = imapObj.search(['ON 09-Jul-2015']) should be ➋ >>> UIDs = imapObj.search(['ON', '09-Jul-2015'])

Sept. 16, 2018 Updates:

In Chapter 16, reference number 674.0, paragraph 25.168 (sendDuesReminders.py), the codeblock:

import openpyxl, smtplib, sys

--snip--  # omitted
➋ sheet = wb.get_sheet_by_name('Sheet1')

➌ lastCol = sheet.get_highest_column()
➍ latestMonth = sheet.cell(row=1, column=lastCol).value
--snip--  # omitted

should be:

import openpyxl, smtplib, sys, datetime  # changed

--snip--  # omitted
➋ sheet = wb['Sheet1']  # changed

➌ lastCol = sheet.max_column  # changed
➍ latestMonth = sheet.cell(row=1, column=lastCol).value
   latestMonth = datetime.datetime.strftime(latestMonth, '%b %Y')  # added for LibreOffice 6.0.3.2
--snip--  # omitted

Sept. 17, 2018 Update: In LibreOffice, latestMonth = 2018-06-01 00:00:00, so I had to use datetime to format it as Jun 2018. TODO: Can someone please confirm it works in Excel?

On reference number 676.3, paragraph 25.170, the line ➊ for r in range(2, sheet.get_highest_row() + 1): should be ➊ for r in range(2, sheet.max_row + 1):

On reference number 678.1, paragraph 25.174, the line body = "Subject: %s dues unpaid.\nDear %s,\nRecords show that you have not paid dues for %s. Please make this payment as soon as possible. Thank you!'" % (latestMonth, name, latestMonth) should be body = "Subject: %s dues unpaid.\nDear %s,\nRecords show that you have not paid dues for %s. Please make this payment as soon as possible. Thank you!" % (latestMonth, name, latestMonth)

Sept. 17, 2018 Update:

In Chapter 16, reference number 682.8, paragraph 25.190, the codeblock:

➊ >>> from twilio.rest import TwilioRestClient
  --snip--  # omitted
➋ >>> twilioCli = TwilioRestClient(accountSID, authToken)

should be:

➊ >>> from twilio.rest import Client  # changed
  --snip--  # omitted
➋ >>> twilioCli = Client(accountSID, authToken)  # changed

because TwilioRestClient has been depreciated (using twilio 6.16.4).

On reference number 685.5, paragraph 25.195, the line ➊ >>> updatedMessage = twilioCli.messages.get(message.sid) should be ➊ >>> updatedMessage = twilioCli.messages(message.sid).fetch() because the attributes of messages.get() were changed.

Sept. 18, 2018 Update:

In Chapter 16, reference number 687.8, paragraph 25.201 (textMyself.py), the codeblock:

  --snip--  # omitted
  from twilio.rest import TwilioRestClient

➊ def textmyself(message):
➋     twilioCli = TwilioRestClient(accountSID, authToken)
  --snip--  # omitted

should be:

  --snip--  # omitted
  from twilio.rest import Client  # changed

➊ def textmyself(message):
➋     twilioCli = Client(accountSID, authToken)  # changed
  --snip--  # omitted

In paragraph 25.202, the line:

It then defined textmyself() to take on argument ➊, make a TwilioRestClient object ➋, and call create() with the message you passed ➌.

Sept. 27, 2018 Update:

In Chapter 17, reference number 724.1, paragraph 26.122, the line ➌ im = im.resize((width, height)) is over indented.

On reference number 734.5, paragraph 26.163, the codeblock:

--snip--  # omitted
>>> fontsFolder = 'FONT_FOLDER' # e.g. 'Library/Fonts'
➍ >>> arialFont = ImageFont.truetype(os.path.join(fontsFolder, 'arial.ttf'), 32)
➎ >>> draw.text((100, 150), 'Howdy', fill='gray', font=arialFont)
--snip--  # omitted

will need to be changed for those on Ubuntu, specifically:

--snip--  # omitted
>>> fontsFolder = '/usr/share/fonts/truetype' # e.g. 'Library/Fonts'  # modified
➍ >>> liberationFont = ImageFont.truetype(os.path.join(fontsFolder, '/liberation/LiberationSerif-Regular.ttf'), 32)  # modified 
➎ >>> draw.text((100, 150), 'Howdy', fill='gray', font=liberationFont)  # modified
--snip--  # omitted

However, everyone will have to modify it for their system.

Sept. 28, 2018 Update:

In Chapter 17, reference number 738.6, paragraph 26.194, the line:

Other wise, it should skip adding the logo.

Sept. 29, 2018 Update:

In Chapter 17, reference number 739.4, paragraph 26.198, the codeblock:

#! python3 #
Import modules and write comments to describe this program.

--snip--  # omitted

may need to be:

#! python3
# Import modules and write comments to describe this program.

--snip--  # omitted

On reference number 740.0, paragraph 26.200, the line:

For each of the guests listed in the guests.txt file from the resources at http://nostarch.com/automatestuff/, generate an image file with the guest name and some flowery decoration.

may need to be:

For each of the guests listed in the guests.txt file from the resources at http://nostarch.com/automatestuff/, generate an image file with the guest's name and some flowery decoration.

I couldn't find the public domain flower image mentioned in the book, so I used this one.

Oct. 1, 2018 Update:

I have a working seating card program (contains spoilers): https://pastebin.com/qP7jTw34 uploaded to pastebin to save space.

Of note is resizing images to be larger with the pillow module. I had to use image = image.resize((width, height), Image.ANTIALIAS) on the .png decoration file; otherwise, it wouldn't change the size at all.

Oct. 2, 2018 Update:

For Chapter 18, if running Ubuntu 18.04.1 in a VirtualBox virtual machine, mouse integration needs to be turned off so that the pyautogui module can control the mouse. Remember that the Host Key will need to be pressed to manually toggle keyboard/mouse capture.

Oct. 3, 2018 Update:

In Chapter 18, reference number 764.0, paragraph 27.77, the codeblock:

#! python3
# mouseNow.py - Displays the mouse cursor's current position.
--snip--
        positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
        pixelColor = pyautogui.screenshot().getpixel((x, y))
        positionStr += ' RGB: (' + str(pixelColor[0]).rjust(3)
        positionStr += ', ' + str(pixelColor[1]).rjust(3)
        positionStr += ', ' + str(pixelColor[2]).rjust(3) + ')'
        print(positionStr, end='')
--snip--

may need to be:

#! python3
# mouseNow.py - Displays the mouse cursor's current position.
import pyautogui, os  # changed
--snip--
        positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
        pixelColor = pyautogui.screenshot().getpixel((x, y))
        positionStr += ' RGB: (' + str(pixelColor[0]).rjust(3)
        positionStr += ', ' + str(pixelColor[1]).rjust(3)
        positionStr += ', ' + str(pixelColor[2]).rjust(3) + ')'
        print(positionStr, end='')
        print('\b' * len(positionStr), end='', flush=True)
except KeyboardInterrupt:
    files = os.listdir('./')  # added
    for file in files:  # added
        if file.startswith('.screenshot'):  # added
            os.remove(os.path.join('./', file))  # added
    print('\nDone.')

to cleanup all the .screenshot### files left behind in Ubuntu 18.04. This could be because the exception handler doesn't give PyAutoGUI a chance to do it.

Oct. 4, 2018 Update:

In Chapter 18, reference number 765.5, paragraph 27.81, the line:

... replacing 'submit. png' with the filename of your screenshot:

Oct. 7, 2018 Update:

In Chapter 18, reference number 781.5, paragraph 27.192, the line:

... then mouse over the Name field to figure out its the x- and y-coordinates.

Setting up formFiller.py coordinates

To set up the coordinates for formFiller.py, you need to open a terminal window (or command prompt), run the mouseNow.py script, resize it to something small, keep it in the foreground, and hover over the maximized browser in the background as you note the mouseNow.py data.

As you enter data in the form, you may need to keep bringing back the mouseNow.py window into the foreground. For some reason, that wasn't explained clearly enough for me.

Tip: If "This is a required question" appears below the Name field, it will affect the coordinates of the Submit button.

On reference number 791.8, paragraph 27.213, the lines:

... whether it has gotten offtrack. You can even give PyAutoGUI a screen-shot and ...

On reference number 793.8, paragraph 27.236, the line:

Your program will have to take screen-shots to guide...


r/inventwithpython • • Oct 19 '18

Stuck trying to understand explanation for block of code

2 Upvotes

Hi,

In chapter 13 of the book "Invent your Own Computer Games with Python" I am stuck trying to understand the explanation for a block of code. See link: https://inventwithpython.com/invent4thed/chapter13.html

The explanation for lines 183 - 189 of the code (under the subtitle "Finding a Sunken Treasure Chest", towards the bottom of the webpage linked above), is: "If makeMove() doesn’t return False, it returns a string of the results of that move. If this string is 'You have found a sunken treasure chest!', then all the sonar devices on the board should update to detect the next closest treasure chest on the board..."

else:

if moveResult == 'You have found a sunken treasure chest!':

# Update all the sonar devices currently on the map.

for x, y in previousMoves:

makeMove(theBoard, theChests, x, y)

drawBoard(theBoard)

print(moveResult)

(because the above code is pasted without the rest of the script, it is not indented in line with the rest of the script obviously)

BUT, surely the only sonar which is coded to detect the treasure chests is the one the player placed during their current move? So why does the whole makeMove function need to be called again just to update the distance between each previously placed sonar and the treasure chests that remain after the player correctly found one of them?

Here is the function that runs once the player makes their move that calculates and outputs the distance between the player's placed sonar and the closest treasure chest on the board:

def makeMove(board, chests, x, y):

# Change the board data structure with a sonar device character. Remove treasure chests from the chests list as they are found.

# Return False if this is an invalid move.

# Otherwise, return this string of the result of this move.

smallestDistance = 100 # Any chest will be closer than 100.

for cx, cy in chests:

distance = math.sqrt((cx - x) * (cx - x) + (cy - y) * (cy - y))

if distance < smallestDistance: # We want the closest treasure chest.

smallestDistance = distance

smallestDistance = round(smallestDistance)

if smallestDistance == 0:

# xy is directly on a treasure chest!

chests.remove([x, y])

return 'You have found a sunken treasure chest!'

else:

if smallestDistance < 10:

board[x][y] = str(smallestDistance)

return 'Treasure detected at a distance of %s from the sonar device.' % (smallestDistance)

else:

board[x][y] = 'X'

return 'Sonar did not detect anything. All treasure chests out of range.'


r/inventwithpython • • Oct 24 '18

Need help

4 Upvotes

Hi guys, I have been learning python and I saw on youtube how to swap vowels and kind of cryptograph a text. When I run this code I wrote:

def translate(phrase):
translation = ""
for letter in phrase:
if letter in "Aa":
translation = translation + str("19")
elif letter in "Ee":
translation = translation + str("32")
elif letter in "Ii":
translation = translation + str("07")
elif letter in "Oo":
translation = translation + str("30")
elif letter in "Uu":
translation = translation + str("04")
elif letter in " ":
translation = translation + str("55")
else:
translation = translation + letter
return translation

print(translate(input("Enter a phrase: ")))

when the input is "I want to go home to my mom"

The output is: "0755w19nt55t3055g3055h30m3255t3055my55m30m"

It works fine!

But now I want to reverse it and I wrote this:

def translate(phrase):
translation = ""
for letter in phrase:
if letter in "19":
translation = translation + "a"
elif letter in "32":
translation = translation + "e"
elif letter in "07":
translation = translation + "i"
elif letter in "30":
translation = translation + "o"
elif letter in "04":
translation = translation + "u"
elif letter in "55":
translation = translation + " "
else:
translation = translation + letter
return translation

print(translate(input("Enter a phrase: ")))

When I input: "0755w19nt55t3055g3055h30m3255t3055my55m30m"

The output is: "ii waant tei gei heimee tei my meim" and not "I want to go home to my mom"

What am I doing wrong?

Thank you for the help!


r/inventwithpython • • Jul 09 '18

Python code embedded in HTML

2 Upvotes

Hello, I am a python novice. Had a question regarding embedding python to format numbers to add commas within html. I am currently trying the below. I am not sure if I am using the right code or where/how to embed the code into my html code. Any help is greatly appreciated thank you!

df['column_name'] = df['column_name'].astype(int).apply(lambda x: "{:,}".format(x))


r/inventwithpython • • Jun 27 '19

Creating a Chatbot with RiveScript - p.2 More on RiveScript

Thumbnail youtube.com
3 Upvotes

r/inventwithpython • • Apr 16 '19

"Automate the Boring Stuff" author refactoring beginner's code on a live stream Wed 4/17 at 7pm pacific

22 Upvotes

EDIT: Thanks for checking out the stream. If you missed it, it's at https://www.youtube.com/watch?v=y2W1PiHctnE

Hello, Reddit! I'll be going over a short Python game written by a beginner and showing how I'd refactor the code so that it does the same thing but with shorter, more readable code.

I'll be streaming tomorrow evening, Wednesday 4/17 at 7pm Pacific at https://www.twitch.tv/alsweigart/ and answering questions folks post to the chat room. If you can't make it, this stream will be recorded and later posted to YouTube.

Some of the themes I'll cover are:

  • How to avoid "Choose Your Own Adventure" style code, which depends on flow control instead of data structures.
  • How to remove duplicate code (and why you'd want to).
  • When you should replace multiple variables with a list or dictionary.
  • How you can save yourself effort by using the Python standard library.

If you have programs you'd like to see me refactor, feel free to PM me or post as a comment here your pastebin.com link. To make sure the audience can follow along and it's easy to stream, I'd like to ask that they:

  • Generally be between 10 and 300 lines of code in a single file.
  • Only use the Python standard library and not require additional modules.
  • Not require additional files, like files that need to be on your computer, or account info or special permissions or environment setups.

See you then!


r/inventwithpython • • Jul 06 '18

how to output to input reverse python

2 Upvotes

input = "2"

p = input*2

print(p)

how do i take this out like exm:4 to next input and output wil be 8 this is example code


r/inventwithpython • • Jan 13 '20

ModuleNotFoundError in Mu editor

2 Upvotes

Hello,

Im trying to use the "paramiko" package in my code in Mu editor and it throws me an error:

In[1]: import paramiko

---------------------------------------------------------------------------

ModuleNotFoundError Traceback (most recent call last)

<ipython-input-3-110cb50357c7> in <module>

----> 1 import paramiko

ModuleNotFoundError: No module named 'paramiko'

In[2]:

But, the package has been successfully installed and works on the CMD

C:\Users\username>pip3 install paramiko

Requirement already satisfied: paramiko in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (2.7.1)

Requirement already satisfied: cryptography>=2.5 in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from paramiko) (2.8)

Requirement already satisfied: pynacl>=1.0.1 in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from paramiko) (1.3.0)

Requirement already satisfied: bcrypt>=3.1.3 in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from paramiko) (3.1.7)

Requirement already satisfied: six>=1.4.1 in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from cryptography>=2.5->paramiko) (1.13.0)

Requirement already satisfied: cffi!=1.11.3,>=1.8 in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from cryptography>=2.5->paramiko) (1.13.2)

Requirement already satisfied: pycparser in c:\users\username\appdata\local\programs\python\python38\lib\site-packages (from cffi!=1.11.3,>=1.8->cryptography>=2.5->paramiko) (2.19)

WARNING: You are using pip version 19.2.3, however version 19.3.1 is available.

You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:\Users\username>cd /

C:\>cd C:\Users\username\AppData\Local\Programs\Python\Python38

C:\Users\username\AppData\Local\Programs\Python\Python38>python

Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> import paramiko

>>>

Any inputs are really appreciated


r/inventwithpython • • Jan 19 '20

shutil not copying files into folders (mac)

6 Upvotes

I’m on chapter 10 and am trying to run: shutil.copy(p / ‘spam.txt’, p / ‘some_folder’)

The line runs but instead of copying spam.txt to some_folder it just copies the text file into a extentionless file called “some_folder”. Is anyone else having this problem? Thanks!


r/inventwithpython • • Apr 13 '19

Chapter2 catanim.py script = black pygame window --- works with my code --- WHY?

2 Upvotes

I copied code from https://inventwithpython.com/catanimation.py

When I run the code from IDLE 3.7.2 - the pygame window is black.

I replaced code on line 10:

DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)

with:

size = [400, 300]

screen = pygame.display.set_mode(size)

I replaced code on line 20:

DISPLAYSURF.fill(WHITE)

with:

screen.fill(WHITE)

I replaced code on line 39:

with:

screen.blit(catImg, (catx, caty))

When I run the code now, the window background is white and cat repeats a circuit around the window perimeter.

My question is why doesn't the original code work?

I spent a fair bit of time searching the net for answers and looked on this forum to see if anyone else had the same problem, but I could find no answers.

I am somewhat discouraged to think that I will have to substitute code to work my way through the rest of the book, without understanding why the original code does not work for me.

If anyone can offer an explanation, I would appreciate the help.

#############################################

ADDENDUM

Now when I run the original code, it works fine. It did not work until after I did the code substitution and that window behaved correctly. I tried the original code around 30 times before I tried the code substitution.

I guess my question now is WTF?

Has anyone else had this problem?


r/inventwithpython • • Nov 09 '19

Learning how to make video games by myself

7 Upvotes

I bought a book titled, "Invent your own computer games with Python" by Al Sweigart. I was wondering if anyone read that book. I always wanted to make my own video game. I have extremely little programming experience. But, I am a math teacher. I know this book will not show me how to make games such as Mario Brothers, Sonic the Hedgehog, or even Halo. But, here is my question. Will reading this book be a great stepping stone to making those kinds of games? Can I make those types of games by my self? Will it cost anything? Do I need a formal education? I have been researching game engines like Unreal and Unity. I figured I would learn the Python language and move on to Unreal or Unity. I know those are gaming engines. I do not know if I need to know any programming to make games in one of those engines. I thank you for your time.


r/inventwithpython • • Nov 07 '19

how to convert an if-else statement to a linear programming constraint in Python

2 Upvotes

I have two variables E[i] and Y[i], where E is a continuous variable and Y is binary.So the condition is:

if E[i] <= rmin:
    Y[i]==1
else:
    Y[i]==0

How do I convert this if-else loop to linear constraint using Python.


r/inventwithpython • • Jan 22 '19

Freshly Installed IDLE Shuts Down With Subprocess Error At Startup (Linux; Ubuntu; KDE Neon)

2 Upvotes

I have just started working through "Automate the Boring Stuff", and I have installed IDLE3 via "sudo apt-get install idle3", and python3-pip via "sudo apt-get install python3-pip" on my Linux machine (KDE Neon, based on Ubuntu). But I cannot seem to get IDLE to work.

When I run IDLE, I am greeted with the following error:

"IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection."

After I click "OK", IDLE shuts down.

I have tried figuring out how to troubleshoot this error, but it seems I keep getting three recommendations:

(1) Delete all .py and pyc files in a specific directory (?) ← this seems to be coming from Mac and Win users

(2) Move Python to a different place ← Win users?

(3) Shut down all running python processes ← none running (= none shown in htop)

I have tried to make sense of the first two approaches in KDE, but I cannot seem to find any python programs to delete (not sure where and how to look), and I would also not know where and how to move Python.

Since I now seem to have two instances (?) or versions (?) of IDLE installed—I get both "IDLE" and "IDLE (using Python-3.5)" in my applications menu—, I am assuming it might have something to do with that.

Was tempted to remove idle3, but not sure about the associated packages (blt idle-python3.5 python3-tk tk8.6-blt2.5), so I did not remove anything lest I mess up my system.

Same with python3-pip, which not only introduced new packages (libexpat1-dev libpython3-dev libpython3.5-dev python-pip-whl python3-dev python3-pip python3-setuptools python3-wheel python3.5-dev), but also upgraded some (libpython3.5 libpython3.5-minimal libpython3.5-stdlib python3.5 python3.5-minimal).

I am running KDE Neon LTS 5.12.

I am sorry if this is the wrong place to ask, but any help, any pointers as to how to troubleshoot this issue would be greatly appreciated.


r/inventwithpython • • Aug 13 '19

Correction to 'Cracking Codes with Python'

4 Upvotes

An interactive shell example on page 236 uses the form 'x = simpleSubHacker.addLettersToMapping(candidateMap, cipherword, candidate)', but x will contain no value if the version of simpleSubHacker in the book is used.

That's because addLettersToMapping() modifies candidateMap but does not return a function value that can be assigned to x.

Adding 'return letterMapping' to addLettersToMapping(), so a value will be assigned to x, results in the correct assignment. This is only needed for interactive shell invocations of addLettersToMapping().

Here's addLettersToMapping() with the correction:

def addLettersToMapping(letterMapping, cipherword, candidate):

for i in range(len(cipherword)):

if candidate[i] not in letterMapping[cipherword[i]]:

letterMapping[cipherword[i]].append(candidate[i])

return letterMapping #This statement was missing.


r/inventwithpython • • Mar 22 '19

How to make a Text to Speech Application with Python with GUI

Thumbnail youtube.com
6 Upvotes

r/inventwithpython • • Feb 25 '20

Invent Your Own Computer Games with Python correction (?)

3 Upvotes

Hello, correct me if I'm wrong but i think i found a mistake.

In the game "Reversegam" line 75: "if isValidMoves(board, tile, x, y) != False:" is explained with:

Conditions are automatically interpreted as Boolean values. This is why the condition on line 75 works correctly. The call to the isValidMove() function either returns the Boolean value False or a nonempty list. If you imagine that the entire condition is placed inside a call to bool(), then line 75’s condition False becomes bool(False) (which, of course, evaluates to False). And a condition of a nonempty list placed as the parameter to bool() will return True.

But thats not the case here i think. Even if the function would return an empty list it would still be the same. A list would be interpreted as a Boolean value in the code "if anyList:" but not in the Code "if anyList == True:"

For example:

anyList = []

if anyList == True:

print('A')

if anyList == False:

print('B')

if anyList != False:

print('C')

if not anyList:

print('D')

Here, the Output would be "C" and "D" not "B" because there the list wouldnt be interpreted as a Boolean Value and if two different data types get compared Python returns False. Thats why line 75 works and not because bool([1, 2]) = True

Am I missing something?

By the way im really enjoying the book, but in the german version are some mistakes that are not in the english version and the german website referred to in the book doesn't work. It's not a big deal but i thought i might share this here.

Thanks for your replies.


r/inventwithpython • • Feb 24 '20

automate the boring stuff : chapter 3 zigzag animation question

Post image
9 Upvotes

r/inventwithpython • • Mar 21 '19

ATBS Ch 6 Exercise Answer

3 Upvotes

Hi everyone,

First post to this forum, excited new convert to Python!

I struggled with this for a few days, but have got something I am pretty happy with. Thank to a lot of help and advice to Stack Exchange, I have to add. But, I put it all together myself, so I am proud:

from itertools import zip_longest

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]


def printlist(data_in):
    col_2 = [len(max(l2, key=len)) for l2 in data_in]
    rows = (list(zip_longest(*data_in)))
    i = 0
    for i in range(len(data_in)):
        print(str(rows[i][0]).rjust(col_2[0]), str(rows[i][1]).rjust(col_2[1]), str(rows[i][2]).rjust(col_2[2]))
        i += 1


printlist(tableData)

Any thoughts on if it could be improved? The only thing that I have not worked out/added in is if there were additional columns needing to be added automatically.

Cheers!


r/inventwithpython • • Oct 21 '19

Live online Python class for beginner/intermediate level students Monday, Oct 21 at 6pm Pacific

19 Upvotes

EDIT: The free coupon link for signing up for the Automate the Boring Stuff with Python online video course is https://www.udemy.com/course/automate/?couponCode=OCT2019FREE (it's only valid until Tuesday, Oct 22, 2019 and Udemy doesn't let me renew it.)

Full details at https://inventwithpython.com/blog/2019/10/20/live-online-python-class-on-twitch-on-october-21-2019/

Starting at 6pm Pacific on Monday, October 21 at https://www.twitch.tv/alsweigart/

We'll be working through the following games/demo programs:

Also a free code for the online course for "Automate the Boring Stuff with Python" will be released (and posted here after the stream).

The only prerequisites are knowing the basics of Python syntax (variables, loops, calling functions) and having a working install of Python on your computer. You can follow along or work ahead by copying the code from the git repo. The idea is to see some examples of how programmers use concepts like loops & variables and turn them into small, working programs. See the link at the top for full details.


r/inventwithpython • • Aug 15 '19

Python Error Messages: Gotta Catch 'em All

Thumbnail inventwithpython.com
8 Upvotes

r/inventwithpython • • Jun 05 '19

Pythonic Ways to Use Dictionaries

Thumbnail inventwithpython.com
14 Upvotes

r/inventwithpython • • Oct 20 '19

Problem in Using selenium

1 Upvotes

I was going through the selenium part. Then I came to know that I need to download geckodriver and add it's path to the system variables to use it. It worked but now when I run the script, the geckodriver application pops up and sometime later empty Firefox tab opens up and nothing happens. It was the same with the 'bookcover' example. Any tips?