r/inventwithpython • • Dec 18 '20

I am getting name error i.e., NameError: name 'computerMove' is not defined

Thumbnail
pastebin.com
4 Upvotes

r/inventwithpython • • Nov 25 '20

Unused variable in sonar

4 Upvotes

Question from how to invent computer games. In my Sonar file my IDE Visual Studio Code says there is a problem with line 12 saying the y variable is unused even though the program works perfectly and that line is being executed. Nbd just an angry yellow bar in my code. Any idea why?

Def getNewboard():
    board = []
    for x in range(60):
        board.append([])
        for y in range(15): # this line here has the issue
            if random.randint(0, 1) == 0:
                board[x].append('~')
            else:
                board[x].append('`')
    return board

r/inventwithpython • • Oct 31 '20

python programming

4 Upvotes

Use library tools_4211 to cut a random set Z of 35 objects, with the respective labels stored in Y. Hint: To find the number of elements of a 1D array, e.g., Labels, use len(Labels).


r/inventwithpython • • Oct 08 '20

How to use the invent with python dictionary?

4 Upvotes

I am trying to use the dictionary located at https://inventwithpython.com/dictionary.txt, and it is loading as a file without spaces. So when I run

with open(file) as f:
    real_words = f.read()
    real_words.replace('\n', ' ').split()

word = random.choice(real_words)

I only get single letter responses. If I print the dictionary, it prints each word on its own line, but random treats the file as a single entry. How do I get random to call a whole word?


r/inventwithpython • • Sep 29 '20

Mu version 1.10.0 required?

4 Upvotes

Here http://automatetheboringstuff.com/2e/chapter0/ it says

You’ll need to download Mu version 1.10.0 or later in order to install the third-party modules featured in this book. As of this writing, 1.10.0 is an alpha release and is listed on the download page as a separate link from the main download links.

When I go to the Mu website (https://codewith.mu/en/download) it seems that the regular version is 1.0.3 and the alpha version is 1.1.0.

Is that a typo? Should it say 1.1.0 is needed?


r/inventwithpython • • Sep 17 '20

HELP It's me AGAIN xD

4 Upvotes

Hi guys you helped me 2 days ago and I apreciate it so much, but today I was 'coding' (if we can say writing 2 more lines) and I have a problem, what i wanna do with the '''''app''''' is to take a list and there you can write some names or take off it if you don't want, so here it begins my headache, what I wanna do is, if I write no to the program it tell me if I'm sure about that, then writing No or no the continue sentence return me to the 17th line and what I want is returning me to the start of the while. Someone can help? Yes I'm noob se my name.

Agenda = ['Juan', 'Alvaro', 'Lucia']
elem = Agenda
print ('Contacts: ')
for elem in Agenda:
print ('- ' + elem)
res = input('Do you want to add any contact?')
while True: #here is where I wanna start again
if res == ('yes') or res == ('Yes'):
input('What contact do you wanna add?')
break
else:
res1 = input('¿Are you sure you dont want to add any contact ?')
if res1 == ('No') or res1 == ('no'): #the continue returns me to this line and I wanna start again the while sentence
print('Ok')
else:
break
continue

Si entendeis el español, que lo dudo, si me hablais en español mejor, pero aun asín me da un poco igual.

Thanks.


r/inventwithpython • • Jul 01 '20

Hello

4 Upvotes

Hello Everyone I'm new here, and i just wanted to say Hi!!


r/inventwithpython • • Jun 26 '20

Website Github links dead

4 Upvotes

Data brokers and AI scrapers were using my info. Not anymore. Redact let me bulk delete posts across Reddit, Twitter, Discord and Instagram while handling broker opt outs too.

birds tidy theory recognise sharp depend outgoing ghost vanish shaggy


r/inventwithpython • • May 04 '20

How to Create an executable app for the RPS Game?

4 Upvotes

I was working on the 'RPS Game' from Chp 2. I wanted to share this game with a non-programmer friend of mine. How do I convert it into an executable program, such that my friend wouldn't have to use python or CLI or any of the technical stuff?


r/inventwithpython • • May 03 '20

Question about Chapter 3 of Automate and the Zigzag program, using Mu editor (1.0.3)

4 Upvotes

Chapter 3

https://pastebin.com/RJDTZjMF

When I run the program in Mu and press ctrl+c, it quits the program like how it does when pressing ctrl+c and not what the program should do which is to call the sys.exit() function. The message that appears at the end is:

---------- FINISHED ----------
exit code: 2 status: 0

which is always the message when pressing ctrl+c to end a program. The sys.exit() produces this message when it is properly executed:

Traceback (most recent call last):
File "c:\users\...
sys.exit()
SystemExit

What seems to be happening is that regardless of the except KeyboardInterrupt block in the program or anything to anticipate and stop it, the editor just quits the program whenever ctrl+c is pressed. When I open the actual file of the program and it opens in something like a command window, the program properly executes the except block to exit the program. I confirmed this by adding the time.sleep(3.0) delay before calling the sys.exit() function.

Is this a problem with the editor? If so, then that means it may not be able to properly run programs in the future that stops a ctrl+c command. Should I use another editor?


r/inventwithpython • • Apr 29 '20

CommaCode Challenge - Query for Al, but whoever else will do.

4 Upvotes

UPDATE

Sadly, I almost immediately found a solution after posting this...

Changing the final line of code to:

commaCode(function)

removed the superfluous 'None' at the end of the program. However, my question is now similar but a little different:

Why did:

print(commaCode(function))

result in 'None' or anything at all?

ORIGINAL POST

Hi there.

Been working through Al Sweigart's 'Automate the Boring Stuff' book. Chapter 4 on lists was the first one I've had a bit of trouble with (still not sure if my Conway's game of life is working as it's meant to), but my query is just a small one about his challenge at the end called Comma Code.

It's short... Here's my code. You can see the goal of the program in the opening comments:

# Breif: Write a function that takes a list value
#as an argument and returns a string with all the items
#separated by a comma and a space, with and inserted
#before the last item. 
def commaCode(function):
    myString = ''
    if function == []:
        print("Nothing, nothing, and a whole lot of nothing.")
    else:
        for i in range(len(function) -1):
            myString += (function[i] + ', ')
        myString += ('and ' + function[-1] + '.')
    return print(myString)

function = []
print("Add words to your list (to end list, just press Enter):")
while True:
    nextInList = input()
    if nextInList == '':
        break
    else:
        function.append(nextInList)

print(commaCode(function))

Basically, the program works as desired with one little flaw. At the end of every run, it adds the word 'None'. EG, from program start:

Add words to your list (to end list, just press Enter):

Me

myself

I

Me, myself, and I.

None

>>>

I'm somehow sure Al has covered this in the preceding chapters, but I can't seem to workout how to get rid of it or why it's happening for me.

Can anyone point me in the right direction? (I'm using Python 3.8 64-bit on Win10, coding in Mu.)

(Also, Al's book has been great so far. Good teaching method! Highly recommended. Thanks Al!)

duck


r/inventwithpython • • Apr 07 '20

EZSheets returning error 403 when attempting to create spreadsheet object.

4 Upvotes

Webpage is telling me that I 'did not include a valid API key'.

I've gone through and gotten all the verification codes and tokens. Still not letting me in. Anybody seen anything like this?

https://i.imgur.com/rI4vK00.png

https://i.imgur.com/iy8paD0.png

Edit: Submitted a github issue.


r/inventwithpython • • Feb 02 '20

[automate]Chapter 8, revised, make your own multiplication Quiz, can't do timeout

4 Upvotes

Trying to take on the challenge of doing a multiplication quiz without using PyInputPlus.

Have done everything except the 8 second timeout. I've looked all over the Interwebz for a way to do it, but just can't wrap my brain around it. I managed to do the 1 second pause with the correct answer.

Any hints? Here's my code so far:

#mymultiplicationquiz
#tries to recreate a multiplication quiz WITHOUT PyInputPlus

import random, time

number_Questions = 10
answer = 0
i = 0

for questionNumber in range(1, (number_Questions + 1)):
    num1 = random.randint(0,9)
    num2 = random.randint(0,9)
    prompt = '#%s: %s x %s = ' %(questionNumber, num1, num2)
    print(prompt)
    for i in range(1,4):
        answer=input()
        if answer==str((num1*num2)):
            print('good')
            time.sleep(1)
            break
        print('incorrect')

r/inventwithpython • • Oct 30 '19

What's up with the second edition of "Automate The Boring Stuff With Python"? Can't see it on the website.

4 Upvotes

I live in Asia. And I am an unemployed college student. I really cannot afford the print version of the book. So I am in need of the website/ebook version of the newest 2nd Edition of the book. And I can't seem to find the same on the website.

When will be the new version up on the website and/or ebook version available?


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 • • Apr 13 '19

Feedback please!

Thumbnail
youtube.com
4 Upvotes

r/inventwithpython • • Jan 15 '19

Problem in the last line of Python code

4 Upvotes

from random import randint,seed

equal_distances=0

for n in range(5000):

seed(n)

res_sum=0

distr_num=[]

t=0

for i in range(10):

g=randint(0,1000)

res_sum+=g

distr_num.append(g)

t+=1

mean=res_sum/t

higher_sum=0

lower_sum=0

for item in distr_num:

if item<mean:

s_lower=mean-item

lower_sum+=round(s_lower,1)

else:

s_higher=item-mean

higher_sum+=round(s_higher,1)

if lower_sum==higher_sum:

equal_distances+=1

In the last line of the above code the variable equal_distances counts how many times variable lower_sum is equal to higher_sum. Because of the method used in the code the result is suppose to be 5000. Unfortunately the result is 3957. In spite the fact that the both variable respectively are always the same increment in the last line has been skipped many times. If you try to print the value of equal_distances in every step it is looks like this 1-2-3-3-3-4-5-6-6-7-8-9-10 and so on. At the end of the day I have 5000 attempts of addition but because of skipping only 3957 increments. What is the problem in the above code?


r/inventwithpython • • Nov 29 '18

Cracking Codes with Python printing problem on chpt 15?

4 Upvotes

I'm working through the affine cipher and instead of getting the expected result I'm getting no result. After writing out the code, correcting the code, adjusting the indentation a couple times, and then ultimately just copy/pasting the source code to see if there was a problem with the source code itself, and I still have the same printing problem

def main():

myMessage = """"A computer would deserve to be called intelligent if it could deceive a human into believing that it was human." -Alan Turing"""

myKey = 2023

myMode = 'encrypt'

if myMode == 'encrypt':

translated = encryptMessage(myKey, myMessage)

elif myMode == 'decrypt':

translated = decryptMessage(myKey, myMessage)

print('Key: %s' % (myKey))

print('%sed text:' % (myMode.title()))

print(translated)

pyperclip.copy(translated)

print('Full %sed text copied to clipboard.' % (myMode))

After running this program, adjusting, readjusting, and running again, nothing prints out to the console, it's like those print statements above aren't even there, I included the link to the chapter below where you can see the full source code if you think there may be a problem there, but I've made sure to have that exact code. There's another module I needed to create to complete the affine cipher called 'cryptomath' and I've double and triple checked that code as well to make sure it was correct, I did find an indentation error in that module but after fixing it, there is still NO printing/output at all.

What am I missing here?

http://inventwithpython.com/hacking/chapter15.html

-edit- the first 3 variables, the if/ elif, and the print statements are all indented on the same vertical behind the def, and the two translated variables are indented on the same vertical behind the if/elif statements. (since I guess my indents didn't show up)


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 • • May 13 '18

Cracking Codes With Python Corrections

4 Upvotes

u/AlSweigart , I felt bad spamming your e-mail, so I'll just post all corrections here and add if I find more.

Note: My PDF copy was created 12/1/2017 7:03:06PM and was last modified 12/4/2017 5:30:14PM

  • Chapter 1 Practice Questions:

The answer for Practice Question 1, part b: Encrypt “GUILLOTINE: A machine which makes a Frenchman shrug his shoulders with good reason.” with a key of 17 should be “XlZccfkZeV:NRN4rtyz5vN.yztyN4r2v0NrNW9v5ty4r5N0y9!xNyz0N0y6!3uv90N.z yNx66uN9vr065Q”, not “bpdggjodiZ:RVR8vx349zRD34x3R8v6z.RvRa?z9x38v9R.3?B2R34.R.30B7yz?.RD4A3R200yR?zv.09U” (that’s key of 21)

Scratch that, with SYMBOLS = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”, even the messages should be in all caps with totally different outputs, like the decryption in question 2.

Question 1 answers should be:

a. EQFMHIBXVSYW: EFPI XS TMGO AMXL IUYEP WOMPP E VMKLX-LERH TSGOIX SV E PIJX.

b. XLZCCFKZEV: R DRTYZEV NYZTY DRBVJ R WIVETYDRE JYILX YZJ JYFLCUVIJ NZKY XFFU IVRJFE.

c. DHKDZOT: TJPM DMMZQZMZIXZ OJRVMY HT YZDOT.

and Question 3 should be using all caps as well.

  • On page 57, the final paragraph reads:

“Just as in the reverse cipher in Chapter 5, …”

However, the reverse cipher was in chapter 4 because chapter 5 is the Caesar cipher!

  • On page 84, end of the third-to-last paragraph:

“(All the variables in the reverse cipher and Caesar cipher programs in Chapters 5 and 6, respectively, were global.)”

Chapter 6 was the Caesar cipher hacker program!

  • On page 166, the fourth paragraph:

Line 30 uses string interpolation to print the key currently being tested using string interpolation to provide feedback to the user.

  • On page 236, the code block​

>>> letterMapping1 = simpleSubHacker.addLettersToMapping(letterMapping1,
'OLQIHXIRCKGNZ', candidates[0])
>>> letterMapping1

Should be

>>> simpleSubHacker.addLettersToMapping(letterMapping1, 'OLQIHXIRCKGNZ', candidates[0])
>>> letterMapping1
  • On page 237, the code blocks:

>>> letterMapping1 = simpleSubHacker.addLettersToMapping(letterMapping1,
'OLQIHXIRCKGNZ', candidates[1])
>>> letterMapping1

and

>>> letterMapping2 = simpleSubHacker.getBlankCipherletterMapping()
>>> wordPat = makeWordPatterns.getWordPattern('PLQRZKBZB')
>>> candidates = wordPatterns.allPatterns[wordPat]
>>> candidates
['CONVERSES', 'INCREASES', 'PORTENDED', 'UNIVERSES']
>>> for candidate in candidates:
...     letterMapping2 = simpleSubHacker.addLettersToMapping(letterMapping2, 'PLQRZKBZB', candidate)
...
>>> letterMapping2

should be

>>> simpleSubHacker.addLettersToMapping(letterMapping1, 'OLQIHXIRCKGNZ', candidates[1])
>>> letterMapping1

and

>>> letterMapping2 = simpleSubHacker.getBlankCipherletterMapping()
>>> wordPat = makeWordPatterns.getWordPattern('PLQRZKBZB')
>>> candidates = wordPatterns.allPatterns[wordPat]
>>> candidates
['CONVERSES', 'INCREASES', 'PORTENDED', 'UNIVERSES']
>>> for candidate in candidates:
...     simpleSubHacker.addLettersToMapping(letterMapping2, 'PLQRZKBZB', candidate)
...
>>> letterMapping2
  • On page 238, the code block:​

>>> letterMapping3 = simpleSubHacker.getBlankCipherletterMapping()
>>> wordPat = makeWordPatterns.getWordPattern('MPBKSSIPLC')
>>> candidates = wordPatterns.allPatterns[wordPat]
>>> for i in range(len(candidates)):
...     letterMapping3 = simpleSubHacker.addLettersToMapping(letterMapping3, 'MPBKSSIPLC', candidates[i])
...
>>> letterMapping3

should be

>>> letterMapping3 = simpleSubHacker.getBlankCipherletterMapping()
>>> wordPat = makeWordPatterns.getWordPattern('MPBKSSIPLC')
>>> candidates = wordPatterns.allPatterns[wordPat]
>>> for i in range(len(candidates)):
...     simpleSubHacker.addLettersToMapping(letterMapping3, 'MPBKSSIPLC', candidates[i])
...
>>> letterMapping3

May 14, 2018 Update:

  • On page 253, the code block:​

>>> building = ''
>>> for c in 'Hello world!':
>>>     building += c
>>> print(building)

should be

>>> building = ''
>>> for c in 'Hello world!':
...    building += c
...
>>> print(building)
  • On page 254, the code block:​

>>> building = []
>>> for c in 'Hello world!':
>>>     building.append(c)
>>> building = ''.join(building)
>>> print(building)

should be

>>> building = []
>>> for c in 'Hello world!':
...    building.append(c)
...
>>> building = ''.join(building)
>>> print(building)

May 15, 2018 Update

  • On page 260, the last line:

Similarly, the letters that appear least often in the ciphertext are more likely to have been encrypted from to X, Q, and Z in plaintext.

May 18, 2018 Update

  • On page 298, the code:​

>>> set([1, 2, 3, 3, 4])
set([1, 2, 3, 4])

outputs

>>> set([1, 2, 3, 3, 4])
{1, 2, 3, 4}

for me, but that may be the interactive shell or OS I'm using (Ubuntu 16.04 with Python 3.5.2). TODO: Can anyone else confirm?

  • On page 306, the code:

>>> def printStuff():
        print('Hello', end='\n')
        print('Howdy', end='')
        print('Greetings', end='XYZ')
        print('Goodbye')
>>> printStuff()

should be

>>> def printStuff():
...     print('Hello', end='\n')
...     print('Howdy', end='')
...     print('Greetings', end='XYZ')
...     print('Goodbye')
...     
>>> printStuff()

May 19, 2018 Update

  • On page 318, the code block:

>>> import secrets
>>> otp = ''
>>> for i in range(55):
        otp += secrets.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
>>> otp

should be

>>> import secrets
>>> otp = ''
>>> for i in range(55):
...     otp += secrets.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
>>> otp

I think. Ubuntu 16.04 LTS doesn't have Python 3.6 or above. TODO: Can someone confirm?

  • On page 326, the code block:

>>> primeNum.isPrime(13)
True

should be

>>> primeNum.isPrime(13)
False

Here's the thing: isPrime() checks a number for divisibility by low prime numbers (which would make it not prime). Therefore, 13 is divisible by the low prime number 13 and is not prime by that definition.

You'd have to add something like:

if num in LOW_PRIMES:
    return True  # Low prime numbers are still prime numbers

to isPrime() to keep it from doing that.

May 20, 2018 Update:

  • On page 341 and 347, the code:

64. print('The private key is a %s and a %s digit number.' %
(len(str(publicKey[0])), len(str(publicKey[1]))))

should be

64. print('The private key is a %s and a %s digit number.' %
(len(str(privateKey[0])), len(str(privateKey[1]))))

r/inventwithpython • • May 11 '18

Ch 12 Working with openpyxl pg 270 correction? openpyxl.cell should be openpyxl.utils

4 Upvotes

In order to use "get_column_letter" and "column_index_from_string" to work I used .utils instead of .cell:

from openpyxl.utils import get_column_letter, column_index_from_string


r/inventwithpython • • Mar 06 '18

Problem creating a consolidated pdf

4 Upvotes

Hi

I am trying my hands at the PDF consolidating project of Chapter 13 of automating the boring stuff book. The input pdfs are password projected so I am giving the decrypt command. My intent is to pool up the pdfs while retaining only the first page ( page 0 ) of each pdf. The pdf is getting generated in the Finder of my mac but I am unable to open it as the system is saying the file is corrupt.

Since there is no error per se in Python ( v 3.6.4), I am unable to debug anything or google anything.

The code fragment is lying is

https://pastebin.com/5vZV70RM

I can share the input pdfs well though I was open to same in the shell with decrypt command.


r/inventwithpython • • Feb 17 '18

Please help i have little problem with the for loop check my code

Thumbnail
pastebin.com
4 Upvotes

r/inventwithpython • • Jan 25 '18

[automate] (Chapter 8) trouble with the open() function

4 Upvotes

[Now solved]

I cannot seem to work the open() function.

I created a file in my home directory called 'hello2.txt' (I made several, but they keep not working so the name has evolved). The file just has the text "Hello world!" in it as recommended in the book.

When I run the suggested text (with my attempt to adapt it for linux) in idle:

              .>>> helloFile = open('/home/chris/hello2.txt')

I get:

Traceback (most recent call last):

File "<pyshell#7>", line 1, in <module>

helloFile=open('/home/chris/hello2.txt')

FileNotFoundError: [Errno 2] No such file or directory: '/home/chris/hello2.txt'

So I tried:

.>>> helloFile=open('~/home/chris/hello2.txt')

with the thought that maybe for linux one needs the leading ~, but that gave the same result.

When I run the terminal and look at the directory with the 'ls' command, I see the file.

I can open the file with a text editor no problem. I can open it from the shell using the same path as attempted above... for example, if I run

$pico ~/home/chris/hello2.txt

from the terminal's Linux command line I can edit the program in that editor.

I thought that maybe it was a typo in the book to not have the "os." in front of open, so I tried

helloFile=os.open('/home/chris/hello2.txt')

and I get this error:

Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> helloFile=os.open('/home/chris/hello2.txt') TypeError: Required argument 'flags' (pos 2) not found

So I thought maybe I needed the 'r' after the file (as a flag) and ran:

.>>>helloFile=os.open('/home/chris/hello2.txt', 'r')

...but this gives me an error about an expected integer.

I have tried finding someone else who has the same problem, but I cannot seem to ask the question well enough to find anything on stack overflow or reddit.

I tried many things including restarting (in case the python shell did not update it's index of my directory) -- and I did import os at the beginning of each python shell session. (Restarting made no noticeable impact on this problem.)

I have also tried making other .txt files and putting them in other directories and that also does not work. I don't need sudo to open the file from the Linux command line, so I don't think that is creating a problem for me.

Clearly I am making some mistake but I cannot out what it is and I would love some help.

(I am running python 3.5.2 on a linux mint machine if any of that matters.)


r/inventwithpython • • Jan 09 '18

Automate the boring stuff: chapter 4 problem

4 Upvotes

The question can be found here, at the bottom of the page: http://automatetheboringstuff.com/chapter4/

I reached the following result, which works fine (numbers added to identify lines of code):

1. for y in range(len(grid[0])):	
2.     for x in range(len(grid)):
3.         if x < len(grid)-1:				
4.             print(grid[x][y], end="")
5.         else:
6.             print(grid[x][y], end="\n")

However, this is more elegant:

7. for x in range(len(grid[0])):
8.     for y in range(len(grid)):
9.         print(grid[y][x],end='')
10.    print()

To be honest, I'm having trouble visualizing what the code is doing in the second, shorter example. I don't see how it's able to rotate the grid correctly. If someone could maybe walk me through what exactly is happening on a step by step basis, it might help it click for me.


Okay, as I was writing this, I started thinking about my code, and it I think it clicked for me. Below is my understanding of the discrete sequence of operations that is happening with this code:

x and y start at 0. For x=0, we must run the for-loop at line 8. That loops will run 9 times (because len(grid) is 9) before we run the for-loop at line 7 again. The result is that we print the 0th element of sublist 0, then the 0th element of sublist 1, and so forth. Working from printing [0][0] to printing [9][0].

At [9][0], we complete the line 8 for-loop and drop down to line 10, where print() gives us our linebreak.

Then we repeat the process, only instead of x=0, x=1. So we do the for-loop at 8 again, which requires us to print grid[0][1] though [9][1] before print() runs and the line 7 for loop repeats .

This continues until we have completed all 6 iterations of the x for-loop.


Is this a correct understanding of the more elegant code, or have I missed something?