how to use Two For loop (not nested loop)

nested loop example
nested for loops python
how nested for loop works in c
how to loop a loop in java
nested loops practice problems java
how often is the inner loop of a nested loop run
when to use nested for loops
syntax of nested for loop in java

I wan to print Student data and Class data. So, I wrote a code to fetch Student_id and Class_id.

  • Firstly the Input Student_id must match with the Stud_id in Student_data.csv file and print the data according.[I found the answer for this]

  • Samely, the input class_id must match with the Class_id in Class_data.csv file and print the data according.

I need the Final output as below[marked in **]:

Option 8: Enrol a student to a class Enter student id: S001 Enter class id: C001

  • Student S001, Kitty Tan enrolled into class C001, CCW101, Computer and Information Processing *

Code:

if option == 8:

            Stud_id = str(input("Enter Student Id : ")).lower()
            Clas_id = str(input("Enter Class ID : ")).lower()

            Stud_File=open('Student_Data.csv', "r")                             ## Reading CSV file.
            Stud_Reader=list(csv.reader(Stud_File, delimiter=','))            ## Converting the csv file into List.
            Class_File=open('Class_Data.csv', "r")                             ## Reading CSV file.
            Class_Reader=list(csv.reader(Stud_File, delimiter=','))            ## Converting the csv file into List.

            for row in Stud_Reader:                                               ## Creating a for loop to search sub-string in a string in a CSV file data.
                    for field in row:                                
                            if Stud_id in field:                                        
                                    print("Student " +Stud_id), row[1],(" Enrolled into Class " +Clas_id)


            for row in Class_Reader:
                    for field in row:
                            if Clas_id in field:
                                    print(row[1], row[2]) 

Student S001, Kitty Tan enrolled into class C001, CCW101, Computer and Information Processing *

If you give the design of the .csv i guess you can use Pandas to make the access simpler. But i guess just store the string and print it later. and use break to end for when you found your student id.

Do multiple loops have same complexity as nested loops?, Yes. Nested loops means that the outer loop will execute the inner one completely for each iteration (of the outer). This means O(n^2) in your  Instead of multi-loop, If you can categorize all the threads into a loop, you can easily go with the less complexity with the in python, and for the nested loop, it is total standing with the loop in between the loop.

Your code looks like it almost does what you want.. but you can store the student text "Student S001, Kitty Tan enrolled into class C001" in a variable and just print it later.. you could also try using end="" in your first print statement, which would stop it from printing a newline.. but I don't think that's as good a way to do this and it's only do-able in python3.

        Stud_id = str(input("Enter Student Id : ")).lower()
        Clas_id = str(input("Enter Class ID : ")).lower()

        Stud_File=open('Student_Data.csv', "r")                             ## Reading CSV file.
        Stud_Reader=list(csv.reader(Stud_File, delimiter=','))            ## Converting the csv file into List.
        Class_File=open('Class_Data.csv', "r")                             ## Reading CSV file.
        Class_Reader=list(csv.reader(Class_File, delimiter=','))            ## Converting the csv file into List.

        for row in Stud_Reader:                                               ## Creating a for loop to search sub-string in a string in a CSV file data.
                for field in row:                                
                        if Stud_id in field:                                        
                                student_text = "Student " + Stud_id + row[1] + " Enrolled into Class " + Clas_id


        for row in Class_Reader:
                for field in row:
                        if Clas_id in field:
                                print(student_text, row[1], row[2]) 

Chapter 5: Nested loops, Which loop to use?, The use of break statements is not recommended. We expect the iteration of a loop to be controlled by the true/false statements in the while and do-while and the  When you “nest” two loops, the outer loop takes control of the number of complete repetitions of the inner loop. Thus inner loop is executed N- times for every execution of Outer loop. Example: Nested for loop in R # R nested for loop for(i in 1:5) { for(j in 1:2) { print(i*j); } } Output

if you give your sample csv, it will be faster to understand. Below will work for your problem.

def check_student_id(student_id):
    try:
        Stud_File = open('Student_Data.csv', "r")
        Stud_Reader = list(csv.reader(Stud_File, delimiter=','))
        for stud_id_row in Stud_Reader:
            for stud_id in stud_id_row:
                if str(stud_id).lower() == student_id:
                    return True
        return False
    except Exception as Err:
        print(str(Err))
        return False


def check_class_id(class_id):
    try:
        Class_File = open('Class_Data.csv', "r")
        Class_Reader = list(csv.reader(Class_File, delimiter=','))
        for class_id_row in Class_Reader:
            for cls_id in class_id_row:
                if str(cls_id).lower() == class_id:
                    return True
        return False
    except Exception as Err:
        print(str(Err))
        return False

Stud_id = str(input("Enter Student Id : ")).lower()
Clas_id = str(input("Enter Class ID : ")).lower()

is_student_id_exists = check_student_id(Stud_id)
if is_student_id_exists:
    is_class_id_exits = check_class_id(Clas_id)
    if is_class_id_exits:
        print("Student {}, Enrolled into Class {}".format(Stud_id, Clas_id))
    else:
        print("Class id doesnt exits.")
else:
    print("Student id doesnt exits.")

if you CSV have data of student ID and class registered then we need to retrieve that data to show. But what i assume for you question is "Need to validate student ID and class ID present before proceeding to enrolling"

Beginning Java - Unit 4 Looping - Nested For Loops, When you "nest" two loops, the outer loop takes control of the number of counters that resemble the one shown below ( well, OK, maybe not quite this spastic!!) Chapter 5: Nested Loops, Which loop to use? Nested loops. Since the code block of a loop can include any legal C++ statements, you can place a loop inside of a loop. The inner loop is nested inside the outer loop. Nested loops are useful when for each pass through the outer loop, you need to repeat some action on the data in the outer loop.

for loops for two variables (not nested loop), for loops for two variables (not nested loop). Learn more about for loop, file read. Copy to Clipboard. when I try to apply another for loop,. x = [];. y = rms (a1  when you want to form iteration on a 2D array, where you use 2 variables to track current element (variable of the outer loop for no. of row and the variable of the inner loop is for the columns) for ex: x = [ [ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]]

Why are nested loops considered bad practice?, This would be considered O(n^2) time which would be a graph similar to: enter image description here When you use a nested loop, it's not bad practice. In later examples, we’ll use for loops and if-else statements to create useful, complicated programs. Nested For Loops. We nested loop is basically a loop within a loop. We covered a simple nested loop in an example above. Let’s go into this useful Python feature with a few more examples. Suppose you have a list of items:

Why and when to use nested FOR loops in programming.? If we use , when you want to form iteration on a 2D array, where you use 2 variables to track current element (variable of the outer loop for no. of row and  MATLAB allows to use one loop inside another loop. Following section shows few examples to illustrate the concept. Syntax. The syntax for a nested for loop statement in MATLAB is as follows − for m = 1:j for n = 1:k <statements>; end end The syntax for a nested while loop statement in MATLAB is as follows −

Comments
  • Can you describe what your code is doing incorrectly?
  • Class_Reader=list(csv.reader(Stud_File, delimiter=',')) should probably be reading from the Class_File.
  • Its a Class management system project. After selecting the option 8 it will enroll the student to class. and it will print the output as below Student S001, Kitty Tan enrolled into class C001, CCW101, Computer and Information Processing *
  • Pandas seems to be very heavy topic for me as Im a newbie. Please help me with the code.
  • I guess your question is already answered in Zhenhirs Post below. save the information needed in first loop, like studInfo = 'Student ' + str(Stud_id) + str(row[1]) break and then use print in second loop like print(studInfo + ' Enrolled into Class ' + str(Clas_id) + str(row[1]) + ',' + str(row[2])) break
  • yes but still facing some issue with the second loop. rectifyin the same.
  • Sorry but it is quite difficult help you like this, maybe share the data you are loading or a sample. I guess you are running into an Exception, or the Class ID is not found
  • please rectify the code, as im a newbie in python. its is my college project.
  • He is just printing the string student_text in the last printing statement, so all wanted information gets out in one line. Besides that your solution and his is basically the same.
  • All the changes you should need are already in the code I posted above.. Did something not work?
  • Its not entering into second loop. it shows no output. returning back to main menu.