GoGoAllen
GoGoAllen

Reputation: 117

How do I use one 'for loop' for 2 different lists

I want to print out a sentence inside of a for loop where a different iteration of the sentence prints out for each different situation i.e. I have two different lists: student_result_reading and student_name

student_result_reading = []
student_name = []

while True:

   student_name_enter = input("Please enter student name: ")
   student_name.append(student_name_enter)

   student_enter = int(input("Please enter student result between 0 - 100%: "))
   student_result_reading.append(student_enter)

   continueask = input("Would you like to enter someone else? ")
   if continueask == "yes":
          continue
   else:
          break

for studread, studentname in student_result_reading, student_name:
   print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread))     

Here are my two issues:

  1. When I enter 2 or more names, they are not formatted correctly.

  2. When I enter 1 name, I get an error.

Any help as to any solutions is appreciated.

Upvotes: 5

Views: 399

Answers (7)

radzak
radzak

Reputation: 3118

Let me explain it by a much simpler example:

pets = ['cat', 'dog']
ages = [5, 7]

for pet, age in pets, ages:
    print(pet, age)

What gets printed here is:

cat dog
5 7

The crucial question is what actually happens here. It turns out that pets, ages is actually a tuple. Expressions separated by commas are called expression-lists.

It is a tuple that contains 2 lists, it looks exactly like that: (['cat', 'dog'], [5, 7]). So when you iterate over it, next interesting thing happens :) Iterable unpacking!

Basically what happens now is:

pet, age = ['cat', 'dog']

And in the next iteration:

pet, age = [5, 7]

That's how you got originally surprising output.

The reason for the second issue you encountered is if you supply only one name, in the first iteration this happened (let's still use the example with pets):

pet, age = ['python']

ValueError: need more than 1 value to unpack

To fix both issues, you can use built-in zip function.

for studentname, studread in zip(student_name, student_result_reading):
   print('Student Name: {} | Test Name: Reading Test | Percentage Score: {}'.format(studentname, studread))

To format output you can also use so-called f-strings, they're available since Python 3.6

for studentname, studread in zip(student_name, student_result_reading):
   print(f'Student Name: {studentname} | Test Name: Reading Test | Percentage Score: {studread}')

Upvotes: 0

Grigoriy Mikhalkin
Grigoriy Mikhalkin

Reputation: 5573

You can use built-in function zip for that:

for studread, studentname in zip(student_result_reading, student_name):
   print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread))

Also, if you are using Python 2, you, probably, encountering problem, with this two lines:

student_name_enter = input("Please enter student name: ")

and

continueask = input("Would you like to enter someone else? ")

I.e., if you enter something like student name as input for student name, you will get SyntaxError or NameError. Reason is, in Python 2, input function expects valid Python expression, in you case, string, like "student name", not simply student name. For later expression to be valid input, you can use function raw_input.

Upvotes: 3

Simeon Ikudabo
Simeon Ikudabo

Reputation: 2190

student_result_reading = {}
#Create a dictionary to store the students name, and their score 


while True:
       student_name_enter = input('Please enter a student name: ')
       #Ask the user for a student name 

       student_enter = int(input('Please enter a student result between 0 - 100%: '))
       #Have the user enter an integer for the student score

       student_result_reading[str(student_name_enter)] = student_enter
       #Make the key of the dict element the students name, value the students score

       continue_ask = input('Please enter yes to continue, or enter (q) to quit: ')
       #Prompt user to enter q to quit

       #If prompt == q, break out of the loop
       if continue_ask == 'q':
             break

for student, score in student_result_reading.items():
           #Use the .items() method of the dict to get the key, and corresponding value for each element in list 
           print('Student name: {0} | Test Name: Reading Test | Percentage Score: {1}'.format(student, score))

To simplify this, you can add the student name in a dictionary, instead of utilizing two lists. We still run the while loop and ask for the user input for the student name and the student score. Then I Alter the dictionary by adding a key that will be the students name, and set the value equal to the students score. We can then prompt the user to continue, or exit the loop by entering q. We can use the .items() method of a dictionary to iterate over each key and its corresponding value. Then we get the output that you are looking for in the same dictionary, instead of two separate lists, with the student names being the keys, and the student scores being the values. Here is the output:

 Please enter a student name: Random Student
 Please enter a student result between 0 - 100%: 90
 Please enter another student name and score, or enter (q) to quit: yes
 Please enter a student name: Random Student2
 Please enter a student result between 0 - 100%: 75
 Please enter another student name and score, or enter (q) to quit: q
 Student name: Random Student | Test Name: Reading Test | Percentage Score: 90
 Student name: Random Student2 | Test Name: Reading Test | Percentage Score: 75

Upvotes: 0

blacker
blacker

Reputation: 798

The error is generated by use this: "input"

i reeplaced by "raw_input".

you can paste and run this code.

student_result_reading = []
student_name = []

while True:

   # student_name_enter = input("Please enter student name: ")
   student_name_enter = raw_input("Please enter student name: ")
   student_name.append(student_name_enter)

   # student_enter = int(input("Please enter student result between 0 - 100%: "))
   student_enter = int(raw_input("Please enter student result between 0 - 100%: "))
   student_result_reading.append(student_enter)

   # continueask = input("Would you like to enter someone else? ")
   continueask = raw_input("Would you like to enter someone else? ")

   if continueask == "yes":
          continue
   else:
          break

# for studread, studentname in student_result_reading, student_name:
#    print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread))
for studread, studentname in zip(student_result_reading, student_name):
   print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread))

Upvotes: 0

Vishaal
Vishaal

Reputation: 825

The code will only fluke out and work if you enter in exactly two students. The main issue is a misunderstanding of the for loop at the end.

for x, y in [1,2],[4,3]:
    print(x,y)

Will print

1,2
4,3

It will not print

1,4
2,3

as you would like. This answers why you see incorrect formatting when you enter exactly two students. You'll want to use zip to join the two lists as pointed out in another answer.

zip([1,2],[4,3]) will equal [(1,4),(2,3)] 

so your for loop will work as intended.

Upvotes: 0

rahul dhir
rahul dhir

Reputation: 29

I'm not experienced in python much but what you could do i keep a counter for the number of students ,say count_students

For students in range(0,count_students):
        print(student_name[student] + " ")
        print(student_result[student] + "\n")

Upvotes: 0

Initial Commit
Initial Commit

Reputation: 517

I prefer to access array elements by index, like this:

for x in range(len(student_name)):
    print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(student_name[x], student_result_reading[x]))

Upvotes: 0

Related Questions