FAQ: Loops - While Loops: Lists

I don’t know if you are looking for an explanation, but in case someone bumps into this and wants one, here it it:

I understand you have the folowing code:

python_topics = [“variables”, “control flow”, “loops”, “modules”, “classes”]
#Your code below:
length = len(python_topics)
index = 0
while length < index:
print("I am learning about " + python_topics[index])
index += 1

Syntactically it is correct, but the best practice is to select the condition as the variable that will update within the loop.

I understand this is the reason from CodeAcademy they preferred to not accept this option.

1 Like

Hi,

what purpose does [index] serve in the print statement?

print('I am learning about ’ + python_topics[index])

image

can this implementation of python do arithmetic on hexadecimal integers?

how do you make it print to the… terminal? in hex?
also, if it’s possible to print a list of items without the on one line, how?

>>> print (hex(65535))
0xffff
>>> print (f"{str(hex(65535))[:2]}{str(hex(65535))[2:].upper()}")
0xFFFF
>>> 

To print a list with the commas,

>>> print (f"{str(list('abcdefgh'))[1:-1]}")
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'
>>> 

Down the rabbit hole…

>>> from functools import reduce
>>> print (reduce(lambda a, b: a + f", {b}", 'abcdefgh'))
a, b, c, d, e, f, g, h
>>>

rabbit hole indeed.
print a list on one line/print statement without any symbols(the brackets and commas)

1 Like

I have the exact same question but I don’t see a response! Anyone??? Please?

Python lists are zero-indexed i.e. the first element is at index 0, the second element is at index 1 and so on. To access a specific element of a list, we can do so by writing the list’s name followed by square brackets with the index of the element we want to access.

myList = ["a", "b", "c", "d", "e"]

# Printing second element of list
print(myList[1])
# "b"

# Printing fourth element of list
print(myList[3])
# "d"

In the exercise, python_topics is a list whose elements are strings.

python_topics = ["variables", "control flow", "loops", "modules", "classes"]

A while loop is being used in the exercise to iterate over the index i.e. in the first iteration, index will be 0, in the second iteration, index will be 1 and so on.
But we don’t want to print the index. Instead we want to print the element at that particular index.
python_topics[index] will allow us to access the string element at that particular index.

print('I am learning about ' + python_topics[index])

In each iteration of the while loop, the + operator will concatenate/join the string 'I am learning about ' with one of the string elements so that we get outputs such as:

"I am learning about variables"
"I am learning about control flow"
...
1 Like

@thedispatcher I just played around and modified @mtf’s code:

from functools import reduce print (reduce(lambda a, b: a + f" {b}", 'abcdefgh'))

i have a separate problem, about the object oriented programming project.
can python work with lots of circular references?

#type "python3 script.py" in a BASH terminal
class guess_you:
  def __init__(self, max_bits):
    self.regA = []
    self.regB = []
    self.guesses = 0
    self.game_over = False
    for i in range(int(max_bits)):
      self.regA.append(0)
      self.regB.append(0)
    self.regA[-1] = 1
    self.regB[-1] = 1
  def guess(self):
    self.guesses += 1
    accu = 0
    output = 0
    for i in self.regA:
      output += i * (2 ** accu)
      accu += 1
    print(output)
  def calculate(self, user_input):
    score = int(user_input) > 1
    if score:
      print("it took " + str(self.guesses) + " guesses for me to find your number")
    else:
      score = int(user_input) > 0
    if score:
      for i in range(len(self.regA)):
        self.regA[i] = abs(self.regA[i] - self.regB[i])
    self.regB.append(self.regB.pop(-1))
game = guess_you(input("define maximum bit length>"))
acc = 0
outpu = 0
max_guess = []
for i in range(len(game.regA)):
  max_guess.append(1)
for i in max_guess:
  outpu += i * (2 ** acc)
  acc += 1
print("think of a number from 0 to {maximum}".format(maximum = outpu))
print("type 0 if too low, type 1 if too high, type 2 if correct")
game.calculate(input(game.guess()))

do i need to put more comments in this for anyone to understand it?
this is the output of the terminal
Capture
if i reload the page, the ‘connected to codecademy’ green thing on the top right turns red saying ‘lost connection to codecademy’ and stays red, exiting the tab then going back in doesn’t help either, did my code break codecademy?
do i just have to skip this project and move on?

Hi. The output of the code I wrote meets the requirements of the exercise and did not throw any errors, though was still marked as incorrect:

python_topics = ["variables", "control flow", "loops", "modules", "classes"]

#Your code below: 
length = len(python_topics)
index = 0
while length > index:
  print(
    "I am learning about "
  + python_topics[index]
  )
  index += 1

I eventually figured out that my code was comparing the variables length and python_topics in the inverse to how it was expected: “as long as length is greater than the index, do the following” rather than “as long as the index is less than the length, do the following”.

I’m curious - are these two constructions literally identical, or are there cases where there’s a logical difference that could matter and produce different outcomes? Put another way - is marking this as incorrect a feature or a bug?

Not literally, no, but semantically, and logically they follow,

if A > B
then B < A

It’s a ‘given that’ scenario. B is less than A because A is greater than B. It requires some agency to come in and change that.

I’m too long out of school to remember what this logic is called, beyond inferential. Really glad you brought it up.

As to the lesson, it comes down to the code that evaluated the submission. By your logic it would have been apt for the lesson checker to probe for both the direct comparison AND the inferred comparison. That would be the most intuitive way to grade this exercise. Hopefully someone picks up on your suggestion and pays it forward.

1 Like

I would have thought simply probing the output of the code would do the trick, though I guess it would be incorrect to assume the user understood the lesson well enough to implement the relevant concepts into their code just from what was printed. It would be an interesting thing to be a QA for codeacademy :smirk:

1 Like