Control
Structures
a. Conditional Statements
- Used for decision-making.
age = 10
age > 18: print("Adult")elif
age == 18: print("Just turned adult")else
: print("Minor") b. Loops
- For Loop: Iterates over a sequence.
- Using range() with For Loop
With range(start, stop, step):
for i in range(1,10,3): #iterates from 1 to 9 , stepping by 2
print(i)
for i in range(5):
print(i)for i in range(1,11): print(i*2)Iterating through a string
s = "Gods"
for i in s:
print(i)
fruits = ["apple","banana","cherry","Jackfruit"]
for fruit in fruits:
print (fruit)
for char in "python":
print(char)
- Break and Continue with For Loop
for i in
range(5):
if i == 3:
break #exit the loop when i is 3
elif i==1:
continue #skips the iteration when i is
1
print(i)
Nested for
loop
for i in
range(3):
for j in range(2):
print(f"i={i},j={j}")
Pass Statement with For Loop
# An empty loop
for i in 'geeksforgeeks':
pass
print(i)
Else Statement with For Loops
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break\n")
Using Enumerate with for loop
In Python, enumerate() function is used with the for loop to iterate over an iterable while also keeping track of index of each item.
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().
li = ["eat", "sleep", "repeat"]
for i, j in enumerate(li):
print (i, j)
- While Loop: Repeats as long as a condition is true.
count = 0while count < 5: print(count) count += 1
The break Statement with while loop
With the break statement we can stop the loop even if the while condition is true:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement with while loop
With the continue statement we can stop the current iteration, and continue with the next:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
while loop with pass statement
# An empty loop
a = 'geeksforgeeks'
i = 0
while i < len(a):
i += 1
pass
print('Value of i :', i)4. Functions
- Functions encapsulate reusable blocks of code.
- A function is a block of code which only runs when it is called.
- You can pass data, known as parameters, into a function.
- A function can return data as a result.
def greet(name): return f"Hello, {name}!"
print(greet("Alice"))
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
No comments:
Post a Comment