for loop:
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
Syntax:
for variable in Sequence
example:
txt = '1234'
for num in txt:
print(num,end=' ')
output:
1 2 3 4
If condition:
The If statement works by checking the expression to see whether a condition is met and returns a value based on the output obtained.
syntax:
if condition:
if condition is True
else:
if condition is False
example
x=20
if x>=20:
print(x is within 20)
else :
print(x is above the limit)
output:
x is within 20
txt = '12a4'
for num in txt:
if num>='0' and num<='9':
print(num,end=' ')
else:
print('Not Decimal',end=' ')
Output:
1 2 Not Decimal 4
above code is the example of combines if and for.
name = input("Your Name please: ")
print(name)
for alphabet in name:
print(alphabet, end='*')
output:
R*A*J*A
The code checks each and every index and prints the output.
name1 = input("Enter the first name: ")
name2 = input("Enter the second name: ")
name3 = input("Enter the third name: ")
name4 = input("Enter the fourth name: ")
name = [name1, name2, name3, name4]
for letter in name:
if letter[0]=='G':
print(letter)
else:
continue
for alphabet in name:
if alphabet[-1]=='a':
print(alphabet)
else:
continue
for alpha in name:
for i in alpha:
if i==' ':
print(alpha)
else:
continue
for character in name:
if len(character)>9:
print(character)
else:
continue
output:
Enter the first name: Guhanraja
Enter the second name: Lakshmi Pritha
Enter the third name: Guru Prasanna
Enter the fourth name: Varatharajan
Guhanraja
Guru Prasanna
Guhanraja
Lakshmi Pritha
Guru Prasanna
Lakshmi Pritha
Guru Prasanna
Lakshmi Pritha
Guru Prasanna
Varatharajan
Top comments (0)