r/inventwithpython • u/new4514 • Jul 06 '18
how to output to input reverse python
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 • u/new4514 • Jul 06 '18
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 • u/PatXPS • Mar 16 '18
I tried to run this program that I download from your site.
import pyperclip, simpleSubKeyword, detectEnglish
It fails with the message:
RESTART: D:\Users\patjd\My Software Projects\Python\Tutorial\simpleSubDictionaryHacker.py Traceback (most recent call last): File "D:\Users\patjd\My Software Projects\Python\Tutorial\simpleSubDictionaryHacker.py", line 2, in <module> import pyperclip, simpleSubKeyword, detectEnglish ModuleNotFoundError: No module named 'simpleSubKeyword'
I bought the Kindle edition of your book from Amazon.
r/inventwithpython • u/bsneddon • Mar 05 '18
I want use openpyxl to evaluate years of estimate spreadsheets. The spreadsheets use lots of formulas. One thought I could create new sheets say sheetname_values in each spreadsheet and then go manually cut and paste special by value to the new sheet. Any thoughts on how to automate the task?
r/inventwithpython • u/FeistyCounter • Mar 05 '18
on page 236-7 the text has you testing the simpleSubHacker.addLettersToMapping function in the interactive shell. It has lines like: letterMapping1 = simpleSubHacker.addLettersToMapping(letterMapping1, 'OLQIHXIRCKGNZ', candidates[0]) in three places The addLettersToMapping function modifies the directory and doesn't return anything (see page 227), so the letterMapping1 = part of the line causes letterMapping1 to be set to None. When addLettersToMapping is called in the main program (page 229 line126) it is called without the assignment, ie simpleSubHacker.addLettersToMapping(letterMapping1, 'OLQIHXIRCKGNZ', candidates[0])
r/inventwithpython • u/SenseiRAM • Feb 23 '18
Hi there,
I'm confused about a particular bit of code in the 'Invent Your Own Computer Games' book. Chapter 13 (Sonar game), the text makes reference to the function makeMove returning False if the player makes an invalid move. As near as I can tell though, the function would never return False. Am I missing something? I've included the code below and at this pastebin: https://pastebin.com/ChmKEvdk
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 the string of the result of this move.
smallestDistance = 100 # Any chest will be closer than 100.
for cx, cy in chests: # For 'value 1' and 'value 2' in each index of the list
# If each index didn't have two values, this wouldn't work.
# This isn't a nested loop or anything.
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 • u/tian2992 • Feb 20 '18
r/inventwithpython • u/stever777 • Feb 12 '18
Hope I didn't inadvertently mis-title the orginal post as 'Hacking Secret Ciphers with Python'....I didn't have the book in front of me while posting.
Repeating original question here Hello Mr. Sweigart,
Just finished the book - I've never seen the math behind public key encryption, so really appreciated the clear and detailed walkthrough
Had a question regarding the 'Converting a block to a String' section. In this section, you state that in order to retrieve the original message text, the length of the original message must be known.
Is there another way to recover the original message text ? It seemed a odd that the length of the original text must be exposed to the person decrypting the message. Granted, you stated in the beginning of the chapter that this approach was only based on the RSA cipher, and there may be a part of the process you didn't talk about in your book - but if the original message length is something that has to be communicated to the person decrypting the message, how is this usually accomplished ? is it sent along with the encrypted message ?
Appreciate any additional insight you can provide on this part of the process.
r/inventwithpython • u/Isabella7604 • Feb 12 '18
import random import time
def displayIntro(): print('''You are in land full of dragons. In frount of you, you see two caves. In one cave, the dragon is frendly and will share his treaseure with you. The other dragon is greedy and hungry, and will eat you on sight.''')
print()def chooseCave(): cave = '' while cave != '1' and cave != '2': print('which cave will you go into? (1 or 2)') cave = input()
return cavedef checkCave(chosenCave): print('you approach the cave...') time.sleep(2) print('its dark and spooky...') time.sleep(2) print('A large dragon jumps out in frount of you! He opens his jaws and...') print() time.sleep(2)
frendlyCave = random.randint(1,2)
if chosenCave == str(friendlyCave):
print('throws up all his treasure all over you!')
else:
print('Gobbles you down in one bite!')playAgain = 'yes' while playAgain =='yes' or playAgain == 'y': displayIntro() caveNumber = chosenCave() checkCave(caveNumber)
print('do you want to play again? (yes/no)')
playAgain = input()what it says about the problem
====== RESTART: /Users/Bella/Documents/python programing/dragon game.py ====== You are in land full of dragons. In frount of you, you see two caves. In one cave, the dragon is frendly and will share his treaseure with you. The other dragon is greedy and hungry, and will eat you on sight.
Traceback (most recent call last): File "/Users/Bella/Documents/python programing/dragon game.py", line 38, in <module> caveNumber = chosenCave() NameError: name 'chosenCave' is not defined
r/inventwithpython • u/stussll • Jan 02 '18
What bugs did you identify and fix?
I'm wanting to double check my solution to the Ch. 10 Practice Project: Debugging Coin Toss
Here's what I came up with: https://pastebin.com/X5wvWGSL
r/inventwithpython • u/Nick_Aaron • Dec 31 '17
I found it's hard to find mistakes in my program, so I install pylint to find errors. But it show me this:
E: 5, 0: Module 'pygame' has no 'init' member (no-member)
E: 13,25: Module 'pygame' has no 'QUIT' member (no-member)
E: 14,12: Module 'pygame' has no 'quit' member (no-member)
These are not errors at all!Please give some suggestions, any help will be appreciated!
r/inventwithpython • u/dakdaketydak • Jul 23 '17
Hey this was the first thing in the book that was actaully quite challenging, this is my code. Probs really hard to read, but it works quite well no matter how long the text is. Also do we have to make it handle more than 3 lists and more than 3 list items, or do we just have to make it work with the example.
CODE
tableData = [['Alicegaetgeag','Bffffffffffob','Carffffffffffffffffffffffffffffol', 'David'],['affffffffffffffffpples', 'orangfeaaaaaaaaaaaaaes', 'cherries', 'bannanas'],['Dogs', 'Catf eaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas', 'Moose', 'Goose']]
col = [0] *len(tableData) a = 0 length = 0 length1 = 0 length2 = 0
for i in range(((len(tableData))*len(tableData[0]))): if i < 4: a = 0 if len(tableData[a][i]) > length: length = len(tableData[a][i]) col[0] = len(tableData[a][i])
if i > 3 and i < 8:
a = 1
i -= 4
if len(tableData[a][i]) > length1:
length1 = len(tableData[a][i])
col[1] = len(tableData[a][i])
elif i > 7 :
a = 2
i -= 8
if len(tableData[a][i]) > length2:
length2 = len(tableData[a][i])
col[2] = len(tableData[a][i])
if i+1%(len(tableData)+1) == 0:
a += 1
if a == 3:
breakprint(col) for i in range(len(tableData[0])): print(tableData[0][i].ljust(col[0]) + tableData[1][i].rjust(col[1]+1) + tableData[2][i].rjust((col[2])+1))
r/inventwithpython • u/ChemengerUK2 • Jul 02 '17
Hi all; I'm attempting the problem I've listed in the title (link here: https://gyazo.com/984db9a628c9670a0181a0c22209fcfe).
Here is my script (https://gyazo.com/b38fe7a832c98aa198850fb590d7fec4) but when I run it I don't seem to get an output, getting this screen (https://gyazo.com/074dc02ec3924d3458da5e84dbbcaf90).
Any help would be brilliant, thanks in advance!
r/inventwithpython • u/ThisIsMyLastAccount • Jun 06 '17
Hi All,
I've been working through Automate the Boring Stuff after picking up a humble bundle for it ages ago. I love the writing style and the way things are explained, but I feel starved for practice opportunities to really drill loops into my head - I'm on Chapter 5 and for the last couple of chapters, I feel like I understand the concepts easily enough, I can answer the questions quickly and correctly, but then I stutter when I come to write it.
So I guess this post is both a comment for Al (I see you're kind enough to read this sub frequently), as well as a request for a recommendation for somewhere that just drills you on the stuff I've learnt in the last five chapters, so I can get them further ingrained in my head. Otherwise I worry that I'm building shaky foundations.
Thanks all!
r/inventwithpython • u/[deleted] • May 07 '17
r/inventwithpython • u/[deleted] • Apr 22 '17
I am having issues understanding how to run the script from Windows 10. I believe I correctly added the path to the environment variables. I created a batch file for this program. When I go to type pw email into the WIN-R window, it just comes back saying that Windows cannot find pw.
At this point I just am lost in this whole process. Can someone give me a step-by-step instruction on how to run a python script from Windows 10?
r/inventwithpython • u/thewallris • Apr 20 '17
I am working on the email unsubscriber program that uses imap, pyzmail, and beautifulsoup. I ran a couple tests and it seemed to be working fine. However, on another test (in which I didn’t change anything), I got an error message:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 21188: ordinal not in range(128)
This is the specific line it was failing on:
html=message.html_part.get_payload().decode(msg.html_part.charset)From the best of my understanding, one of the emails it was trying to parse had a non-ASCII character that it was trying to convert to an ASCII character and failing to do. I saw a few workarounds that said to add this to the code:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')However, I am using python 3.5.2 and this solution seems to only work for python 2.7.
I looked into the pyzmail docs and swapped out a bit of the line that was failing so that it now looks like this:
html=message.html_part.get_payload().decode ('utf-8')I ran another test and it seemed to work. However, I’m concerned that some of the html data is either being lost or altered. After getting the html, I am parsing it with regex to find words in the a tag like unsubscribe, optout, etc, and then getting the href in said tag. Am I just being paranoid, or do I need to be concerned about this conversion?
r/inventwithpython • u/null_endian • Apr 18 '17
Hello,
I have this as my code for the Transposition Hacker, which is not working...
import detectEnglish, trans_decrypter
def main():
myMessage = """Cb b rssti aieih rooaopbrtnsceee er es no npfgcwu plri ch nitaalr eiuengiteehb(e1 hilincegeoamn fubehgtarndcstudmd nM eu
eacBoltaeteeoinebcdkyremdteghn.aa2r81a condari fmps" tad l t oisn sit u1rnd stara nvhn fsedbh ee,n e necrg6 8nmisv l nc muiftegiitm tutmg cm
shSs9fcie ebintcaets h aihda cctrhe ele 1O7 aaoem waoaatdahretnhechaopnooeapece9etfncdbgsoeb uuteitgna.rteoh add e,D7c1Etnpneehtn beete" evecoal
lsfmcrl iu1cifgo ai. sl1rchdnheev sh meBd ies e9t)nh,htcnoecplrrh ,ide hmtlme. pheaLem,toeinfgn t e9yce da' eN eMp a ffn Fc1o ge eohg dere.eec s nfap
yox hla yon. lnrnsreaBoa t,e eitsw il ulpbdofgBRe bwlmprraio po droB wtinue r Pieno nc ayieeto'lulcih sfnc ownaSserbereiaSm-eaiah, nnrttgcC maciiritvledastinideI
nn rms iehn tsigaBmuoetcetias rn"""
hackedMessage = hackTransposition(myMessage)
if hackedMessage == None:
print("Failed to hack encryption")
else:
print("Copying hacked message to clipboard")
print(hackedMessage)
def hackTransposition(message):
print("Hacking...")
print('(press CTRL+D or CTRL+C to quit at any time)')
for key in range(1, len(message)):
print("Trying key #%s..." % (key))
decryptedText = trans_decrypter.decryptMessage(key, message)
if key == 10:
print(decryptedText)
if detectEnglish.isEnglish(decryptedText):
print()
print("Possible encryption hack...")
print("Key %s: %s" % (key,decryptedText[:100]))
print("Enter D for done or just press ENTER to continue hacking:")
response = input(">")
if response.strip().upper().startswith("D"):
return decryptedText
return None
if __name__ == '__main__':
main()The decrypter for key 10 is producing this text, despite it working during the actual Transposition Decryption chapter:
myMessage = """Cb b rssti aieih rooaopbrtnsceee er es no npfgcwu plri ch nitaalr eiuengiteehb(e1 hilincegeoamn fubehgtarndcstudmd nM eu eacBoltaeteeoinebcdkyremdteghn.aa2r81a condari fmps" tad l t oisn sit u1rnd stara nvhn fsedbh ee,n e necrg6 8nmisv l nc muiftegiitm tutmg cm shSs9fcie ebintcaets h aihda cctrhe ele 1O7 aaoem waoaatdahretnhechaopnooeapece9etfncdbgsoeb uuteitgna.rteoh add e,D7c1Etnpneehtn beete" evecoal lsfmcrl iu1cifgo ai. sl1rchdnheev sh meBd ies e9t)nh,htcnoecplrrh ,ide hmtlme. pheaLem,toeinfgn t e9yce da' eN eMp a ffn Fc1o ge eohg dere.eec s nfap yox hla yon. lnrnsreaBoa t,e eitsw il ulpbdofgBRe bwlmprraio po droB wtinue r Pieno nc ayieeto'lulcih sfnc ownaSserbereiaSm-eaiah, nnrttgcC maciiritvledastinideI nn rms iehn tsigaBmuoetcetias rn"""
Thus, there is no distinguishable English word, despite seeing remnants of bits and pieces of English, which tells me that the reason the Transposition hacker is failing has to do with the decryption process text or key being off. I tried the text as both a multi-line and single-line string.
I copied and pasted the text word-for-word multiple times from This page .
I'm stuck. Anyone else struggle with this? Thanks.
r/inventwithpython • u/[deleted] • Mar 15 '17
What is a easy way I can make a scoreboard for this game?
r/inventwithpython • u/[deleted] • Mar 09 '17
I follow the steps in the lecture but I get to this conn.login('[email protected]','Password!21!') and I get an error message
error Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> conn.login('####gmail.com','Password') File "C:\Users\flatwoods\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 729, in login raise last_exception File "C:\Users\flatwoods\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 720, in login initial_response_ok=initial_response_ok) File "C:\Users\flatwoods\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 641, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu0\n5.7.14 NKFUCpcSofwu-eYFpQLPYk16p6IDG7Yw_80luBxOCC_XkPWETsZ-KAfIUytctZYmVcHXvl\n5.7.14 DIcC_EqwIriGUrHrhvW5mYR2Ot_jD_nmK-wKZFZGmsusdB1JDJJfqkK6T_kPOYVxQOmR-c\n5.7.14 Le-oApg21W60tYt_3e8FY-mhkLGY5lfnxgYH0UGac89tZTlmMNP9hInDTUCGhL3gd6ZtUW\n5.7.14 dvjzuGsV-EBXBMSDcCOjwAQ2MYNuA> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 32sm1689645uaw.14 - gsmtp')
r/inventwithpython • u/Stosswalkinator • Feb 24 '17
I'm going through Automate the Boring stuff and I'm following along with the Backup to Zip project. When I get to the third part about walking through the directory tree and adding the files and folders to the zip file I get this error:
NameError: name 'newBase' is not definedfor the for loop:
for filename in filenames:
newBase / os.path.basename(folder) + '_'
if filename.startswith(newBase) and filename.endswith('.zip')
continue
backupZip.write(os.path.join(foldername, filename))At the end of the if statement I went ahead and added in a colon because it needs it, but I can't figure out how to get it to use newBase. I'm using Python 3 on Fedora 25.
r/inventwithpython • u/shonu-FF • Feb 20 '17
Hello World! first post ever to Reddit!
Just wanted to know how you guys found a solution to the Comma Code exercise in ch. 4 of automate the boring stuff.
I did a quick search for a solution but couldn't find one.
I know the exercise states to make a function but my solution was this...
name = input("Gimme a list value: ")
newName = name[0:-1] + " and " + name[-1]
print(newName)Any (constructive) comments? I'll be mashing away trying to find a solution with a function in the mean time.
r/inventwithpython • u/randomstudnet1337 • Jan 17 '17
i'm trying to make movement in pygame. I want my charcter to move the whole time ,but i'm not sure how to do it. My friends said to keep loop the different sprites, but i'm not sure how to do it.
r/inventwithpython • u/[deleted] • Dec 26 '16
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 • u/normandantzig • Dec 11 '16
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)))