1+ #The only form of nesting we've encountered so far was an if statement within a loop.
2+ languages = ["Python" , "C++" , "Java" , "Perl" , "C#" ]
3+
4+ for language in languages :
5+ if language == "C#" :
6+ print (language + " found" )
7+ break
8+
9+ #proper nesting is vital inside of python. Unlike many other languages,
10+ #python is whitespace sensitive. The position of the code is important
11+
12+ for language in languages :
13+ if language == "C#" :
14+ print (language + " found" )
15+ break
16+
17+ #^^ This loop does something completely different.
18+ #Syntactically, the only difference is the position of the break keyword.
19+ #It will break at the end of the first iteration no matter what
20+
21+ ########## NESTED IF ##########
22+
23+ logging = True
24+ logging_in = True
25+ name = "Caleb"
26+
27+ if logging_in == True :
28+ if logging == True :
29+ print (name + " is logging in." ) #log console, file, or db.
30+ print ("Welcome, " + name )
31+
32+ ########## CONVERTING COMPLEX CONDITIONAL TO NESTED IF ###########
33+
34+ #It is common in more complex code to see nested if statements
35+ #This can often replace complex expressions that use numerous logical operators
36+ #Either way is not better, just whatever is clearer to you
37+
38+ age = 20
39+ fun = False
40+ likes_to_dance = True
41+
42+ if (age < 30 or fun == True ) and likes_to_dance :
43+ print ("You're invited to the party!" )
44+ else :
45+ print ("get lost freakbag" ) #most general
46+
47+ #This could alternatively be represented with nested if statements
48+ #and can allow more specific responses
49+
50+ if (age < 30 or fun == true ):
51+ if likes_to_dance :
52+ print ("You're invited to the party!" )
53+ else :
54+ print ("How could you not like to dance?" ) #Specific to dancing
55+ else :
56+ print ("You're either too old or not fun enough to be in my party" )
57+ #Note how we can't easily say which. We say OR.
58+
59+
60+ ########## INTRO TO NESTED FOR ##########
61+
62+ #If you are fairly new, nested loops can be confusing. Pay attention!
63+ #Stop texting and looking at memes...CODE!
64+ #We can loop a loop using a nested loop.
65+ #The inner loop will run each iteration of the outer loop.
66+
67+ for i in range (4 ):
68+ for j in range (5 ):
69+ print (j , end = " " )
70+ print () #go to next line
71+
72+ #The result? The inner loop prints 0 - 4. We then do this 4 times
73+ #After each complete 0-4 print, we go to the next line with print()
74+ #This puts the next loop on the next line of output
0 commit comments