DEV Community

Kuhanraja A R
Kuhanraja A R

Posted on

python session day-6 at payilagam for loop and if condition

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

example


x=20
if x>=20:
   print(x is within 20)
else :
   print(x is above the limit)

output:
x is within 20
Enter fullscreen mode Exit fullscreen mode
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.


Enter fullscreen mode Exit fullscreen mode

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



Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)