prev
next
Or press ESC to close.
To continue enjoying our content, please consider disabling your ad blocker. Your support helps us continue providing quality content. To continue enjoying our content, please consider disabling your ad blocker. Your support helps us continue providing quality content.

Python Programming Part 09

Rajjit Oct 09th, 2023 5 mins read
part-09

TOPIC: Python Basic Loop Structure - for loop

for loop
A "for loop" in Python is a control flow statement that allows you to iterate over a sequence or an iterable object (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence. Here's a definition and common uses of the for loop:

  • Iterating Over Lists and Sequences: We can use a for loop to iterate over the elements of a list, tuple, or other sequence types.
  • Looping Through Strings: Strings are sequences of characters, and we can use a for loop to iterate through each character in a string.
  • Iterating Over Ranges: Ranges are often used with for loops when you need to generate a sequence of numbers.
  • Working with Iterators and Generators: Python supports custom iterators and generators, which can be used with for loops to create custom sequences.
  • Processing Data Structures: for loops are commonly used for processing data structures, like dictionaries and sets.

The syntax and the flowchart of a for loop:

for-loop for-loop-flow

for loops are essential for iterating over various types of data, and they provide a convenient way to perform repetitive tasks and process collections of data in Python programs. They are a fundamental building block of many Python programs and are widely used in everyday coding tasks.

Code as discussed in the video:

# for loop

'''
syntax: 
    for loop_var in sequence:
        statement block
'''

# Example 1 - using range()
# for i in range(0, 11):
#     print(i, end=" ")

n = 100
# for i in range(1, n+1):
#     print(i, end=" ")

# for i in range(1, n+1):
#     print(i, end=" ")

# Example 2
# for i in range(n):
#     print(i, end=" ")

# Example 3 - sum and average
# sumN = 0
# user_input = int(input("Enter a number: "))
# avg = 0.0
# for i in range(1, user_input+1):
#     sumN = sumN + i
# avg = sumN / i
# print(f'The sum of fist {user_input} is', sumN)
# print(f'The average is', avg)

Q1. Write a program to print the multiplication table of n, where n is the user input
Q2. Write a program to check if a given number is prime or composite number

You can copy and run this code