Let's go to examples straight away to understand the syntax and logic behind the control flows.
Line 1 gets the user input as a String and since it should be an integer, it is converted in line 5 and assigned it to another variable.
Line 7 starts the conditional statement saying if the value is larger than 12, Line 8 says to display "Your router is upto date" and
Line 10 says if it is equal to 12, and Line 11 says to display "Your router is old and upgrade"
Line 12 and 13 says "Your router is very old"
This is the most basic form of control flow, we can put much elif statements as we want in between if and else. Else is the default action if none of the above statements work and elif and else statements are optional. Since code runs from top to bottom, if it hits a matching condition, it stops there ignoring all the elifs of else below it.
Thing to remember is the indentation, Line 8 starts after 4 spaces.. Anyhow if you are using and IDE like VS Code like I do, it will do it automatically.
For Loops
Loops are there to do repetitive tasks.
Line 3 defines a List of devices.
Line 5 and 6 says, for all items in devices, print "There is a router named < > ".
So the output will be like the following..
Variable type used in this example is a List, but it can be anything including a String also. In case where a String is used, it will run for all the characters in the String..
For Loops with Continue Operator
This is how you can skip some items if you don't want to print in above type of example.
Note that in Line 6, I have used an equal mark, but there are some functions which can be used to address some other requirements as well. As an example, if I wrote the Line 6 as;
if items.startswith("R")
It will skip all items starts with R.
Nested For Loops
A For Loop can be inserted into another For Loop to get a desired out put like the following.
This will run for all the items in List "description" per every item in List "interface_list" like the following..
For Loops with Range Function
Range function can be used in for sequential tasks easily with For Loop.
Note that it does not print 192.168.1.5; 1st number in range parentheses is inclusive and the last number is exclusive.
You can use a third number in the parentheses to add a step like in the following..
For Loops are used in cases do a repetitive action for items in a variable making it a finite type of loop mostly.
If need to run a loop until a condition is met, have to use While Loops, perhaps it can run infinitely if the condition is not met.
Line 5 and 6 says to print the text as "less than 10" if it is less than 10 starting from original value and Line 8 increments the value of numb with a 1.
Output will be like the following..
This is how you can exit from the While Loop before the condition is met.
Line 9 says to break (exit the loop) if numb is 7,
No comments:
Post a Comment