r/inventwithpython • • Dec 26 '16

How to import a homemade Python module.

2 Upvotes

I am trying to import a custom Python function. The book I am reading says you can just do import function

This doesn't seem to work for my interpreter, The book is from 2016, but Python can change quickly. What's the new way to do this?


r/inventwithpython • • Dec 11 '16

Problem with Chapter 14 openweather activity work around.

2 Upvotes

See link for more details.
You will need to sign up for an openweatherapi key. #! python3 # quickWeather.py - Prints the weather for a location from the command line.

import json, requests, sys, bs4

# Compute location from command line arguments.
if len(sys.argv) < 2:
    print('Usage: quickWeather.py zip')
    sys.exit()
zipCode = ' '.join(sys.argv[1:])

#find the id a city
countryCode = 'us'
location = str(zipCode)+ ',' + countryCode

APPID = '[PUT YOUR API KEY HERE WITHOUT SQUARE BRACKETS]'

# Download the JSON data from OpenWeatherMap.org's API.
url = 'http://api.openweathermap.org/data/2.5/weather?zip='+ location +  '&APPID=' + APPID
response = requests.get(url)
response.raise_for_status()

# TODO: Load JSON data into a Python variable.
weatherData = json.loads(response.text)
# Print weather descriptions.


w = weatherData#weatherData.sorted()
main = weatherData['main']

print('The temp in {0} is {1}'.format(weatherData.get('name', 0), main.get('temp',0)))

r/inventwithpython • • Oct 07 '16

Openpyxl - Writing to Empty/New Spreadsheet (automate the boring stuff w/ python)

2 Upvotes

I'm having problems with writing to an empty excel sheet. I use the cell method to write something to the cells but I can get an error: 'function' object has no attribute 'cell. I sort of understand based on this error but I just don't understand how to write to the cells without the cell method. Any ideas/help would be greatly appreciated.


r/inventwithpython • • Sep 30 '16

Chapter 6 Project - Table Printer

2 Upvotes

After banging my head on the wall, I gave in and found this code written by another user:

def printTable(inputList):
     colWidths = [0] * len(inputList)
    for i in range(len(inputList)):
    for j in range(len(inputList[i])):
        if len(inputList[i][j]) > colWidths[i]:
        colWidths[i] = len(inputList[i][j])
    for x in range(len(inputList[0])):
        for y in range(len(inputList)):
            print(inputList[y][x].rjust(colWidths[y]), end = ' ')
    print('')

What I still don't understand is the "rjust(colWidths[y]", I know when the loops iterate it will print the [y][x] variable, but what I dont understand is how it doesnt right justify each and every time it prints. I feel like it should be adding 5-8 spaces to the left of each word and spacing them WAY out each time it prints. Maybe I'm missing something simple?

Also sorry for the formatting - I have no damn clue how to make it pretty


r/inventwithpython • • Sep 29 '16

Copy clipboard without Pyperclip?

2 Upvotes

Is there any way to copy the clipboard in windows WITHOUT using pyperclip? (I love it, but in my job i can't have pyperclip module installed :( so i need a native python module or some code that gets the clipboard data (text).

Thanks


r/inventwithpython • • Sep 21 '16

Did pyperclip change?

2 Upvotes

None of the examples in the book with pyperclip works. I installed pyperclip with no problem (py3.5) and I can import it without the problem. But I get errors trying to use it:

> text = pyperclip.paste()
> pyperclip.copy()

Error: text = pyperclip.paste() AttributeError: module 'pyperclip' has no attribute 'paste'

pyperclip version = 1.5.27-1

Since I'm running Linux, I did install xclip.


r/inventwithpython • • Aug 19 '16

[Automate] TypeError: must be str, not list for birthdays example

2 Upvotes

I'm trying to execute an example from the ATBS book and it's not working in Python 3.6. I've tried Googling but haven't got far at all.

I would type in "Alice" the key in the dictionary and I would get an error, see below for code + error.

Code:

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}

print(birthdays)

while True:

print('Enter a name: (blank to quit)')

name = input()

if name == '':

    break


if name in birthdays:

     print(birthdays[name] + ' is the birthday of ' + [name])

else:

    print('I do not have that in our records')

    print('What is their birthday?')

    bday = input()

    birthdays[name] = bday

    print('Birthday database updated.')

Error:

Traceback (most recent call last): File "C:/Users/seyi/AppData/Local/Programs/Python/Python36/Scripts/Ch5 dictionaries.py", line 10, in <module> print(birthdays[name] + ' is the birthday of ' + [name]) TypeError: must be str, not list

Any assistance would be helpful


r/inventwithpython • • Aug 18 '16

CH 3 The Collatz Sequence

2 Upvotes

Here is what I came up with, It's the first "program" I've written from scratch. The exception handling doesn't work. I'm thinking it needs to be moved but not sure where to. Let me know what you guys think and what i can do to improve.

The Collatz Sequence

def collatz(number): if number % 2 == 0: #even number return number // 2

elif number % 2 == 1:    #odd number
    return 3 * number + 1

try: number = input("Please input an integer.") while number !=1: number = collatz(int(number))
print(number)
except ValueError: print("This program accepts integers only! Plese input an integer")


r/inventwithpython • • Aug 17 '16

my solution to Ch 4 practice comma code

2 Upvotes

Sharing this as I googled/reddited other answers with for loops built into them and couldn't wrap my head around that approach, and found an alternative way. I probably used too many variables but it was just easier to break it down that way for me.

import copy

spam = ['buttmonkeys','dsfdsfs','dsfsfsdfsfdfdsf','gggggg','dddddd','fff','ttt','123','789']

def thefunction(anylist):
	length=len(anylist)
	anylist.insert(length-1, 'and ') 
	lastitem= copy.copy(anylist[-1]) 
	stringedlist= ', '.join(anylist[:-1]) 
	lastlist= str(stringedlist)+str(lastitem)
	print(lastlist)
	
thefunction(spam)

Any helpful feedback is welcome.


r/inventwithpython • • Aug 09 '16

Tic Tac Toe function I don't understand

2 Upvotes

Hi.

There's a certain function whose inner workings I don't understand.

I refer to this one:

'def getPlayerMove(board): # Let the player type in their move. move = " " while move not in "1 2 3 4 5 6 7 8 9".split() or not isSpaceFree(board, int(move)): print("What is your next move? (1-9)") move = input() return int(move)'

I understand the 'while move not in "1 2 3 4 5 6 7 8 9".split()'. It won't leave the while loop until the user inputs something in the list of integers from 1 to 9, that's easy.

However, I don't understand how the 'or not isSpaceFree(board, int(move))' part works. I've deleted it in the hopes of figuring how it works, but it doesn't seem obvious to me. Upon these arguments deletion, I can choose the same spot on the board, even after choosing the same spot on a previous turn.

I assume it won't let the player choose a spot on the board which was already taken but I don't really get how it works. Shouldn't that 'or' be an 'and'? Because the player must choose an integer from 1 to 9 AND it must be on a spot that wasn't taken. That function works with another reasoning I'm having problems to fully grasp, so I humbly ask for guidance on this matter.


r/inventwithpython • • Jul 28 '16

[Automate] Ch. 7 strip() project: more efficient way to write?

2 Upvotes

Hope this finds you all well. I've been working on the strip() project at the end of Ch 7, and I would love some ways to improve my code. As of now, I'm able to take off whatever I put it in as my second argument off from the left side, but can't completely do so on the right side. I'm using multiple regexes to address each extra character on the left side so I would appreciate some advice on how I can get this all down in a single Regex.

http://pastebin.com/M8igY6Tu

Regards,


r/inventwithpython • • Jul 21 '16

Chapter 10 - Found a way to get rid of 4 lines in getComputerMove(board, computerLetter) - what do you think?

2 Upvotes

Creating the Computer’s Artificial Intelligence

96. def getComputerMove(board, computerLetter): (LINE 96) 97. # Given a board and the computer's letter, determine where to move and return that move.(LINE 97) 98. if computerLetter == 'X': (LINE 98) 99. playerLetter = 'O' (LINE 99) 100. else: (LINE 100) 101. playerLetter = 'X' (LINE 101)

I deleted these lines and instead of it added to a line 96 def getComputerMove(board, computerLetter): an argument "playerLetter" and to a line 171 move = getComputerMove(theBoard, computerLetter)
an argument "playerLetter".

It seems to work pretty well, what are your thoughts?


r/inventwithpython • • Jun 27 '16

Chapter 9 - Hangman - How are these functions called?

2 Upvotes

I'm trying to go through every line in this example and figure out what is happening exactly. So far i have been succesful but their are two things I can't figure out.

On line 116 he states guess is equal to the getGuess function but for some reason this calls the function as when running the program it asks the player to enter a letter. How does setting this function to a variable run it. Very confused

112. while True: 113. displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord) 114. 115. # Let the player type in a letter. 116. guess = getGuess(missedLetters + correctLetters) 117. 118. if guess in secretWord: 119. correctLetters = correctLetters + guess

The same thing goes for on line 141 when he states an if function containing the playAgain variable. This also calls the function.

139. # Ask the player if they want to play again (but only if the game is done). 140. if gameIsDone: 141. if playAgain(): 142. missedLetters = '' 143. correctLetters = '' 144. gameIsDone = False 145. secretWord = getRandomWord(words) 146. else: 147. break

How does this work. I thought you actually had to type the function like on line 113 to run it.


r/inventwithpython • • Jun 19 '16

Corse format: book vs udemy

2 Upvotes

I've bought the book 'Automate the boring stuff with Python' - is it worth buying the udemy course too? Does the udemy course compliment the book or just cover the same material?


r/inventwithpython • • May 04 '16

Checking availability of library book using beautifulsoup

2 Upvotes

I'm learning python. And I'm trying to use it to automate the process of checking a library book's availability.

I tried executing it with bs4, request, and partition.

This is the link that I am trying to parse from: [http://catalogue.nlb.gov.sg/cgi-bin/spydus.exe/FULL/EXPNOS/BIBENQ/1592917/156302298,2][1]

I view its source code, and here's a snippet of it:

<tr> <td valign="top"><a href="/cgi-bin/spydus.exe/ENQ/EXPNOS/GENENQ/1564461?LOCX=BIPL">**Bishan Public Library**</a> <br /> </td> <td valign="top"> <book-location data-title="The opposite of everyone" data-branch="BIPL" data-usagelevel="001" data-coursecode="" data-language="English" data-materialtype="BOOK" data-callnumber="JAC" data-itemcategory="" data-itemstatus="" data-lastreturndate="20160322" data-accession="B31189097E" data-defaultLoc="Adult Lending">Adult Lending</book-location> </td> <td valign="top"><a href="/cgi-bin/spydus.exe/ENQ/EXPNOS/BIBENQ/1564461?CGS=E*English">English</a> <br /><a href="/cgi-bin/spydus.exe/WBT/EXPNOS/BIBENQ/1564461?CNO=JAC&amp;CNO_TYPE=B">JAC</a> <br /> </td> <td valign="top">**Available** <br /> </td> </tr> <tr> <td valign="top"><a href="/cgi-bin/spydus.exe/ENQ/EXPNOS/GENENQ/1564461?LOCX=BMPL">**Bukit Merah Public Library**</a> <br /> </td> <td valign="top"> <book-location data-title="The opposite of everyone" data-branch="BMPL" data-usagelevel="001" data-coursecode="" data-language="English" data-materialtype="BOOK" data-callnumber="JAC" data-itemcategory="" data-itemstatus="" data-lastreturndate="20160405" data-accession="B31189102C" data-defaultLoc="Adult Lending">Adult Lending</book-location> </td> <td valign="top"><a href="/cgi-bin/spydus.exe/ENQ/EXPNOS/BIBENQ/1564461?CGS=E*English">English</a> <br /><a href="/cgi-bin/spydus.exe/WBT/EXPNOS/BIBENQ/1564461?CNO=JAC&amp;CNO_TYPE=B">JAC</a> <br /> </td> <td valign="top">**Available** <br /> </td> </tr> The information that i am trying to parse is which library the book is available at.

Here's what I did:

import requests, bs4

res = requests.get('http://catalogue.nlb.gov.sg/cgi-bin/spydus.exe/FULL/EXPNOS/BIBENQ/1592917/156302298,2') string = bs4.BeautifulSoup(res.text) Then I try to make string into a string:

str(string) And it printed the whole source code out and severely lagged my IDLE!

After it stopped lagging, I did this:

keyword = '<a href="/cgi-bin/spydus.exe/ENQ/EXPNOS/GENENQ/1564461?LOCX=' string.partition('keyword') Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> string.partition('keyword') TypeError: 'NoneType' object is not callable I don't know why it caused an error, I did make the string into a string, right?

Also, I used that keyword because it is right before the "library branch" and right after "availability". So i thought even if it churns out a lot of other redundant code, I'll be able to see in the first line which library branch the book is available at.

I am sure the way I did it is not the most efficient way, and if you could point me to the right way, or show it to me, i will be extremely grateful!

I'm sorry this is a very long post, but i'm trying to be as detailed about my situation as possible. Thank you for bearing with me.


r/inventwithpython • • Apr 12 '16

I've downloaded and installed Pygame from four different websites now, but each time I try to import it IDLE tells me there is no module named 'pygame'.

2 Upvotes

I have Python 3.5.1 (32 bit) installed, and installed above mentioned downloads in the same directory. But I'm a noob, so I might very well have overlooked something.

I also tried the method that this user who had the same problem links to, but it didn't work for me either. In the same thread, somebody also tried to explain it, but used all kinds of terms that I didn't understand as a noob.

Any help would be appreciated.


r/inventwithpython • • Mar 21 '16

I don't understand a part of the Hangman code

2 Upvotes

I'm working my way through the book and really liking it so far but I have a question about part of the Hangman code. You create a variable titled words and in it you put the words for the game. Then in the next block, you define the function 'getRandomWord' with the argument of 'wordList'. How does Python know that the words you want it to pick from are in the 'words' variable since you never call it or reference it again?

Here is a copy of the code:

words = '''mylittlepony fluttershy twilightsparkle pinkiepie
    rainbowdash applejack celestia luna rarity cadence'''.split()

def getRandomWord(wordList):
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]

For the record, the program did work just fine but I'm just trying to understand how it knows those are the words it should be choosing from.


r/inventwithpython • • Mar 12 '16

Auth needed for weather site?

2 Upvotes

I am on Ch.14 doing the JSON project using requests to get the JSON data but I am getting a error 401 on the raise_for_status()

I looked at the website and it seems you need to register for a key now? Is this a recent change? I tried multiple strings/cities, same 401 response every time

File "C:\Python 3.5\lib\site-packages\requests\models.py", line 840, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: http://api.openweathermap.org/data/2.5/forecast/daily?q=Eureka&cnt=3


r/inventwithpython • • Feb 28 '16

why can't modify or erase expression or text after pressing enter?

2 Upvotes

title self explanatory.


r/inventwithpython • • Feb 09 '16

Mad Lib Practice Project

2 Upvotes

I'm trying to practice using a regex to find all occurrences of a specifically formatted part of speech, and then replace those parts of speech with new user provide parts of speech.

The code is here.

The big problem I'm having is that I'm unable to get the program to effectively replace each new occurrence of the part of speech. I tried using the regex.sub() method, however, despite still using multiple inputs it only iterated the last input over the entire text.

And here's the text for the madlib that I grabbed off a random website:

Mad Libs!

A DAY AT THE ZOO!

Today I went to the zoo. I saw a ADJECTIVE NOUN jumping up and down in its tree. He VERB ADVERB through the large tunnel that led to its ADJECTIVE NOUN. I got some peanuts and passed them through the cage to a gigantic gray NOUN towering above my head. Feeding that animal made me hungry. I went to get a ADJECTIVE scoop of ice cream. It filled my stomach. Afterwards I had to VERB ADJECTIVE to catch our bus. When I got home I VERB my mom for a ADJECTIVE day at the zoo.


r/inventwithpython • • Jan 25 '16

[x-post from /r/computervision/] [Help] Bag of visual words - Python

Thumbnail
reddit.com
2 Upvotes

r/inventwithpython • • Jan 19 '16

Warning when I create a bs4 object, with Beautiful Soup, Ch.11

2 Upvotes

First I get this warning when I create a bs4 object, saying something is wrong with my parser?

Warning (from warnings module): File "C:\Users\Poison\AppData\Local\Programs\Python\Python35\lib\site-packages\bs4_init_.py", line 166 markup_type=markup_type)) UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

To get rid of this warning, change this:

BeautifulSoup([your markup])

to this:

BeautifulSoup([your markup], "html.parser")

Should I worry about this bad boy?


r/inventwithpython • • Jan 12 '16

Invent With Python Ch. 6: Dragon Realm issue with something I added

2 Upvotes

Hey guys!

I'm having a slight issue with Chapter 6: Dragon Realm. I've made a slightly different version of the game using the provided source code. I had no issues and tested every aspect of it to find that it was working perfectly. After that, however, I went back and edited the portion where we define:

friendlyCave = random.randint(1, 2)

In my version, I am not using the random module and instead have separate outcomes depending on if you select cave 1 or 2, with 2 always being the friendly cave. However, I wanted different versions of these inputs to work for the user -- whether uppercase, numerical, alphabetical, etc. So my line of code looks like this:

friendlyCave = 2 or second or Second or 2nd

The issue I am having is that 2, second, and Second all work as intended, but for some reason typing in 2nd while playing the game prints my else outcome, rather than the if/friendlyCave outcome. I would have expected it to at least initiate the loop and ask the question again of which cave they choose if there was some problem. Why is it bringing the user to cave 1 rather than friendlyCave 2?


r/inventwithpython • • Dec 23 '15

Why doesn't this work? Chapter 6 Practice Project (Table Printer) TypeError

2 Upvotes

Here's my code:

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

def printTable(L):
    colWidths = [0] * len(L)
    colWidths[0] = max(L[0], key=len)
    colWidths[1] = max(L[1], key=len)
    colWidths[2] = max(L[2], key=len)
    for y in range(len(L[0])):
        for x in range(len(L)):
            word = L[x][y]
            print word.rjust(len(colWidths[x]), end= ' ')
        print

printTable(tableData)

It says this when I run it ----> "TypeError: rjust() takes no keyword arguments"


r/inventwithpython • • Dec 20 '15

chapter 9: Hangman

2 Upvotes

I have typed the program but it doesn't run.showing ''inconsistent use of tabs and spaces in indentation" on line 73. I have enter the the program exactly as it is given in the book.

70. print('Missed letters:', end=' ') 71. for letter in missedLetters: 72. print(letter, end=' ') 73. print()