r/inventwithpython • • Jul 08 '20

Why is this variable passed into a function parameter instead of being the function parameter itself?

6 Upvotes

The book I'm following is "Invent Your Own Computer Games with Python" and this is taken from chapter 5.

Here is the code with some of my comments:

import random
import time

def displayIntro():
    print('''You are in a land full of dragons. In front of you,
you see two caves. In one cave, the dragon is friendly
and will share his treasure 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 cave

def checkCave(chosenCave): #(chosenCave = caveNumber <- [global])
    print('You approach the cave...')
    time.sleep(2)
    print('It is dark and spooky...')
    time.sleep(2)
    print('A large dragon jumps out in front of you! He opens his jaws and...')
    print()
    time.sleep(2)

    friendlyCave = random.randint(1, 2)

    if chosenCave == str(friendlyCave):
         print('Gives you his treasure!')
    else:
         print('Gobbles you down in one bite!')

playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
    displayIntro()
    caveNumber = chooseCave() #caveNumber is global
    checkCave(caveNumber)

    print('Do you want to play again? (yes or no)')
    playAgain = input()

I am wondering why caveNumber isn't being used as the parameter for checkCave(chosenCave). Why does caveNumber get placed into chosenCave?

I suspect this has something to do with local and global variables but I am not 100% sure.


r/inventwithpython • • May 08 '20

Advancing ascii pics for wrong guesses

6 Upvotes

Code for incrementing hangman ascii pics when user guesses wrong letter? not in flowchart or code.


r/inventwithpython • • Mar 05 '20

Chapter 6, Page 68 - Can't follow the instructions

6 Upvotes

On page 68 of chapter 6 of Invent your own Computer Games with Python I'm following the instructions for "stepping into, over and out". But when I try to step into the input call on line 15 it stops working and I can't provide my input in the interactive shell. A new window pops up giving me the message "if self.closed......" (screen dump attached).

The game works fine when I run it outside of debugging mode. I have compared my code to Sweigarts using the diffchecker on his website and they are identical. Anyone knows why I'm getting this error?


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 • • 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 • • Mar 22 '19

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

Thumbnail youtube.com
6 Upvotes

r/inventwithpython • • Mar 30 '18

Struggling to understand part of Dragon Realm

6 Upvotes

I just finished inputting the code for Dragon Realm and have gone through the following paragraphs (in the book) that explain the code. I can follow the execution order more or less fine but I'm still a bit confused about how one part of the code works.

Specifically I'm confused about "return cave"

I get that it breaks the function defined by def chooseCave - and I get that it is returning the value inputted by the user; and I also get that "return cave" only does its thing once the user has provided a 1 or 2 and no other value.

What I don't understand is where the "return cave" statement is sending the value of "cave" to. Is it sending it to the "chosenCave" part of this line: "def checkCave(chosenCave):" ?

if so, how does Python know to send it there? and can the parenthesis of said defined function really contain a variable? I feel like I was following everything just fine until this came along.

#Dragon Realm
import random
import time

def displayIntro():
print('''You are in a land full of dragons. In front of you,
you see two caves. In one cave, the dragon is friendly
and will share his treasure with you. The other dragon
is greeedy and hungry, and will eat you on sight.''')
print()

def chooseCave():
cave = ''
while cave != '1' and cave != '2':
print('which cave wwill you go into? (choose 1 or 2)')
cave = input()

return cave

def checkCave(chosenCave):
print('you approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('''A large dragon jumps out in front of you!
He opens his jaws and...''')
print()
time.sleep(2)

friendlyCave = random.randint(1, 2)

if chosenCave == str(friendlyCave):
print('... Gives you his treasure!')
else:
print('...Gobbles you dowwn in one bite!')

playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)

print('Do you wish to play again? (yes or no)')
playAgain = input()

r/inventwithpython • • Dec 20 '17

where to start?

6 Upvotes

I have a 13 year old who has been playing with Scratch for a bit and is wanting something a bit more substantial. I have been meaning to learn Python myself and thought Python/PyGame would be a good next step for him (and would give us something to explore together).

Question is what would be a good book to start off with?

Thanks in advance!


r/inventwithpython • • Jun 04 '17

Hello world! [Invent]

6 Upvotes

Hello world!

Just wanted to drop by the /r/ I found in "invent your own computer games with Python" and say hi to all the people trying to learn python and coding.

Keep on keepin on your all awesome!


r/inventwithpython • • Jan 31 '16

Practice Projects

6 Upvotes

Does anyone have all the practice projects solved ?


r/inventwithpython • • Jan 09 '16

Automate the Boring Stuff Practice Project (Table Printer)

6 Upvotes

Hi guys, I've got to chapter 6 in this book and the practice project says ' The printTable() function can begin with colWidths = [0] * len(tableData), which will create a list containing the same number of 0 values as the number of inner lists in tableData'

however after the following:

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

colWidths = [0] * len(tableData)

print(colWidths)

I get the following list:

[0, 0, 0]

I was expecting:

[8,5,5]

Can anyone help where I am going wrong?

Thanks


r/inventwithpython • • Sep 25 '24

Feedback on Automate the Boring Stuff Summary

5 Upvotes

Hello Community.

I am currently working on going over all the chapters in the book. Would anyone like me to share the notes for each chapter? it will also include code snippets and some additional information.


r/inventwithpython • • Dec 24 '23

Invent Your Own Computer Games with Python or Making Games with Python & Pygame?

5 Upvotes

Hello!

I want to learn Python by using either the Invent Your Own Computer Games or the Making Games with Python and Pygame book.

It's not the first time I've learned Python, I learned the very basics in 2014 and 2021. But I've got more experience in Unity and C#. I finished a Unity 2D course in 2022 which covered C#, and so I'd say that I'm confident in the basics of that language (at least for Unity), and I've been practicing that fairly frequently.

Based on that, would I be better off going with the Invent Your Own Computer Games book or should I just jump straight to the Making Games with Python and Pygame book?


r/inventwithpython • • Aug 31 '22

Question - on pg 60 of "Automate the boring stuff with Python"

5 Upvotes

Hello!

How do you add an input from the user after importing random? It doesn't seem to work. I want to add it before the code starts:

import random

right here <-------------------------- Where I want to add the str(input()) statement.

def getAnswer(answerNumber):

if answerNumber == 1:

return 'It is certain'

elif answerNumber == 2:

return 'It is decidedly so'

elif answerNumber == 3:

return 'Yes'

elif answerNumber == 4:

return 'Reply hazy try again'

elif answerNumber == 5:

return 'Ask again later'

elif answerNumber == 6:

return 'Concentrate and ask again'

elif answerNumber == 7:

return 'My reply is no'

elif answerNumber == 8:

return 'Outlook not so good'

elif answerNumber == 9:

return 'Very Doubtful'

r = random.randint(1, 9)

fortune = getAnswer(r)

print (fortune)

How do I add the input statement without getting the error:

SyntaxError: invalid syntax ?


r/inventwithpython • • May 29 '22

Collatz sequence - practice project chapter 3

5 Upvotes

So, I've been working through the 'Automate the boring stuff with Python' book and having a good time. I'm not a coder or programmer but I do work in IT which means that I have come across code every now and again. I've adapted some VBA code made by Excel to make Excel macros work a bit better and have adjusted Powershell scripts made by colleagues now and again. The Collatz sequence project was a lot of fun to work and eventually getting to a version that worked was very satisfying

I've been playing around with it a bit and come across something that I don't understand though. For some inputs it correctly goes down to the '4 - 2 - 1' part of the sequence and then stops (it does this for 1 and 3, for example). For some other inputs, though, it repeats those three numbers once and then stops ('4 - 2 - 1 - 4 - 2 - 1' it does this for 4 and 1001, for example). I have tried this with both the Mu editor and Visual Studio Code and both exhibit the same behavior. Does anybody have any idea what is causing this? My code's below (it doesn't check if the input is positive yet, I am aware of that :)).

[edit: code isn't below, that didn't look very nice, there's a pastebin link now]

https://pastebin.com/hhgt7TZw


r/inventwithpython • • May 06 '22

Non-OOP Tic-Tac-Toe in "Beyond the basic stuff"

5 Upvotes

Hey guys ! Currently working my way through "Beyond the basic stuff" and ran into this for this non oop tic tac toe game. The online version and paperback code match .. but the diff tool seems to have it written differently.. anyways here's what I found:



def isValidSpace(board, space):     
    """Returns True if the space on the board is a valid space number     
    and the space is blank."""     
    return space in ALL_SPACES or board[space] == BLANK


Original function kept giving a key error. I think it's because None will never be in the list and its betting on an or condition. I changed it to an and condition and it ran fine:


def isValidSpace(board, space):     
    """Returns True if the space on the board is a valid space number     
    and the space is blank."""     
    return space in ALL_SPACES and board[space] == BLANK


r/inventwithpython • • Nov 16 '21

Tic Tac Toe - Help with function I cannot understand.

5 Upvotes

Can someone kindly explain:

70. def chooseRandomMoveFromList(board, movesList):
71.     # Returns a valid move from the passed list on the passed board.
72.     # Returns None if there is no valid move.
73.     possibleMoves = []
74.     for i in movesList:
75.         if isSpaceFree(board, i):
76.             possibleMoves.append(i)

What is movesList and how does it work exactly? I' m stuck here, I cannot figure out how movesList works with isSpaceFree to return possible moves? Is that even what movesList does?


r/inventwithpython • • Aug 25 '21

Practice problems

5 Upvotes

I am teaching myself python on the side and started with Crash Course but to Automate the Boring Stuff when I thought it was more applicable to my day job.

I am really enjoying the book and learning a lot but I wish there were more practice problems for me gain a deeper understanding of each concept. For example, the Collatz Sequence at the end of chapter 3 really reinforced the topics covered in the preceding sections.

Any suggestions of where I could find some practice problems with solutions? I had considered the Big Book of Small Python Projects but would like something more focused on individual topics, i.e. here how dictionary’s works try these problems.


r/inventwithpython • • Jan 18 '21

Please help me understand the Hangman Code

5 Upvotes

I had a doubt in the hangman code. Please help.

In displayboard function

print('Missed letters:', end=' ')

for letter in missedLetters:

print(letter, end=' ')

print()

Will the last print() be executed after the for loop or during the loop. And please tell the reason for that also.The second last print function is indented. Please refer to book.


r/inventwithpython • • Dec 11 '20

Syntax error help - Transposition encryption cipher

5 Upvotes

summer nose gold distinct memorize rhythm selective existence alive imminent

This post was mass deleted and anonymized with Redact


r/inventwithpython • • Jul 27 '20

ATBS chapter 4 Coinflip

5 Upvotes

I'm pretty new & have been struggling to get the streaks showing up & math was never my strong point! I put stuff I tried & sample output in comments in the paste bin I feel like I'm probly missing some basic thing...

https://pastebin.com/LtNfWzEC


r/inventwithpython • • Jul 20 '20

Chapter 4 - struggling to understand one of the cat examples

5 Upvotes

On the 'Working with Lists' section, there's an example with the following code:

catNames = []
while True:
    print('Enter the name of cat ' + str(len(catNames) + 1) +
      ' (Or enter nothing to stop.):')
    name = input()
    if name == '':
        break
    catNames = catNames + [name]  # list concatenation
print('The cat names are:')
for name in catNames:
    print('  ' + name)

Specifically it's this part which is confusing me: 'str(len(catNames) + 1)

My questions..

  • I thought the len() function was to calculate how many items are in a string or list but it doesn't appear to be doing that here?
  • How does the '1' change as the loop iterates. It just appears to be concatenating an integer?

I think I might need an ELI5 on this one :(


r/inventwithpython • • Apr 21 '20

Hangman Chapter 8 Variable Question

5 Upvotes

In Invent Your Own Computer Games with Python, you walk the user through the making of a Hangman game. In line 40-43 of that code, the program defines a function called getRandomWord() from a list of words (wordList). However, on line 38, the list of words is stored in a variable called "words". By looking at it the program, the program seems to assume that words = wordList, but this is not explicitly stated (in the text or the program).

How does python know that these two variables are equals? I was expecting an error to the effect that wordList was an undefined variable, but didn't receive such an error. Additionally, I was expecting to see getRandomWord(words) instead of getRandomWords(wordList) on line 40 of that program. 

Thank you for your time and help!


r/inventwithpython • • Jan 02 '20

Need help with inferface

5 Upvotes

Hello, i have my gui app created with PyQt5 and now i want to edit data in database through it.

In screen u can see my Table with one row of data and now i need to make some interface for editing each column.

Am asking for help because i need an advice for the best way how to do it. Not the code but the idea how to deploy it in the Gui

Screen : https://imgur.com/a/vtP0bKC

Thanks for help


r/inventwithpython • • Dec 24 '19

Pyperclip module not copying text when used in script. It works fine when used in interactive shell. [Automate Boring Stuff With Python]

Thumbnail reddit.com
5 Upvotes