3rd Week Python Experience

3rd Week Python Experience

Now at week 3 , increase in complexity ,, have a great time reading the article ....

While Loop

A "while loop" is a control flow statement used in programming to repeatedly execute a block of code as long as a specified condition is true. If the condition is true, the code block inside the loop is executed. When the condition becomes false, the loop terminates, and the program continues with the next line of code after the loop.

Use Cases :

  • Used when you don't know the number of iterations in advance, but you know the condition under which you want to continue iterating.

  • Useful when the number of iterations is not predetermined, or you want to repeatedly execute a block of code until a certain condition is met.

example:

Guessing my birthday :

print('year of birth of Anish ?')
year=int(input(  ))

while(year!=2004):  
  print('you are wrong, guess again?')
  year=int(input(  ))

print("hurray! you got it correct")

Finding factorial of an integer :

a=1 #answer
i=1  #iterator 
n=int(input("Enter a positive interger for finding factorial : "))
while(i<=n):
  a=a*i
  i=i+1
print(a)

OR

n=int(input())      #input
a=1                 #ans (factorial)

if(n<0):            # if n  is negative
  print("Not defined")
else:
 while(n>0):        #if n is positive
    a=a*n
    n=n-1
 print(a)

For Loop

In Python, the for loop is used to iterate over a sequence (such as a list, tuple, string, etc.) or any iterable object.

Use Cases :

  • Used when you know the number of iterations or the sequence to iterate over in advance.

  • Suitable for iterating over sequences like lists, tuples, strings, and iterating a fixed number of times using functions like range().

for item in iterable:
    # Code block to be executed for each iteration
    # You can use 'item' to access the current element in the iteration

Here's the breakdown:

  • item: This is a variable that takes the value of the next element in the iterable for each iteration. You can use any valid variable name here.

  • iterable: This is the sequence or iterable object over which the loop iterates. It could be a list, tuple, string, dictionary, range object, etc.

  • Indentation: As with other control structures in Python, the code block to be executed within the loop is indented.

1.Here's a simple example of a for loop iterating over a list:

my_list = [1, 2, 3, 4, 5]

for num in my_list:
    print(num)         


                           #o/p: 
                             1
                             2
                             3
                             4 
                             5

This loop will iterate over each element in my_list, and in each iteration, num will take the value of the current element, which will then be printed.

2.The range() function is commonly used with for loops to generate a sequence of numbers:

for i in range(5):  # This will iterate from 0 to 4
    print(i)

3.You can also use for loops with dictionaries to iterate over keys, values, or key-value pairs:

my_dict = {'a': 1, 'b': 2, 'c': 3}

for key in my_dict:
    print(key, my_dict[key])  # Accessing both key and value

# Or you can use items() method to get key-value pairs directly
for key, value in my_dict.items():
    print(key, value)

Remember that the indentation is crucial in Python to denote the scope of the loop.

another example:

** i iterates over (0 to19) <<->> which is range(20)

for example : here also i stars from 1 and ends at 11-1 =10

More on range and 'for' loop

without range

1. Therange()function can take one, two, or three arguments:

  1. range(stop): Generates a sequence from 0 up to (but not including) the stop value.

  2. range(start, stop): Generates a sequence from start up to (but not including) the stop value.

  3. range(start, stop, step): Generates a sequence from start up to (but not including) the stop value, incrementing each time by the step value.

The step parameter specifies the amount by which the sequence increases from one element to the next. If the step parameter is omitted, it defaults to 1. If the step parameter is negative, the sequence decreases by that amount instead.

#print even numbers till 10
for i in range(2,11,2):       # 2 for increment 
  print(i)  #o/p : 2 4 6 8 10

2. for reverse order in range :

for example : print even numbers till 10 in reverse order


for i in range(10,0,-2):  #-2 for decrementing
  print(i)

3. for loop for collections :

If you want to iterate over each element in a collection (such as a list, tuple, string, etc.) without explicitly using the range() function, you can use the for loop with the in keyword. This allows you to iterate directly over the elements of the collection.

Here's the syntax:

for element in collection:
    # Code block to execute for each element

In this loop:

  • element represents each individual element in the collection.

  • collection is the iterable object (e.g., list, tuple, string) you want to iterate over.

Here's an example:

my_list = [1, 2, 3, 4, 5]
for num in my_list:
    print(num)

This loop will print each element of the list my_list on a separate line:

1
2
3
4
5

Similarly, you can iterate over the characters in a string:

my_string = "hello"
for char in my_string:
    print(char)

This loop will print each character of the string my_string on a separate line:

h
e
l
l
o

You can use this approach to iterate over the elements of any iterable object without explicitly using range().

Formatted Printing

  1. end parameter - in Python, the end parameter is used with the print() function to specify what should be printed at the end of the output. By default, print() ends with a newline character (\n), which moves the cursor to the next line after printing.

  2. separator parameter - sep parameter is used with the print() function to specify the separator between multiple items that are being printed. By default, the sep parameter is set to a single space character.

for the problem "/" between is and 10 we use this method :

3. f-string : (f"") syntax in Python with the print() function.

The f"" string formatting, also known as f-strings, is a feature introduced in Python 3.6. It allows for easy string interpolation, where expressions inside curly braces {} are evaluated at runtime and replaced with their values.

4.format() :-

5. Format specifier:-

Format specifiers in Python are used to control the formatting of variables when they are inserted into strings using the str.format() method or f-strings. They allow you to specify how variables should be displayed, such as their width, precision, alignment, and type.

Nested Loops

A loop inside another loop is called a nested loop. The inner loop will repeat its iterations for each iteration of the outer loop.This means that there is a loop contained inside another loop. In programming, this structure allows you to iterate over elements in multiple dimensions or perform repetitive tasks in a hierarchical manner.

For example, consider the following Python code that prints a multiplication table:

s='vibgyor'
combinations=0
for i in range(7):
  for j in range(7):
   print(s[i],s[j])
   combinations=combinations+1 
#talkig about the number of permutations
print(combinations)

In this code:

  • The outer loop iterates over each character of the string 'vibgyor'.

  • The inner loop also iterates over each character of the string 'vibgyor'.

  • Inside the nested loops, each combination of characters is printed.

  • The variable combinations is incremented by 1 for each combination printed, effectively counting the total number of combinations.

  • Finally, the total number of combinations is printed outside the nested loops.

example 2 : for nested for

# Find all the prime numbers Less than the entered number.
n=int(input())
if(num>2):
  print(2,end=' ')

for i in range(3,n):
  flag=False
  for j in range(2,i):
    if(i%j==0):
      flag=False
      break
    else:
      flag=True
  if(flag):
    print(i,end=' ')

example 3 : while nested while

Break , Continuous and Pass statement

  1. A break statement is used in programming to immediately exit a loop when certain conditions are met. When the break statement is encountered within a loop, the loop is terminated, and the program continues with the next statement after the loop.

  1. The continue statement is used in programming to immediately skip the rest of the current iteration of a loop (for example, a for loop or a while loop), and continue with the next iteration. When the continue statement is encountered within a loop, the remaining code inside the loop for the current iteration is skipped, and the loop proceeds with the next iteration.

  2. In Python, the pass statement is a null operation. It doesn't do anything when it's executed. It's typically used as a placeholder where syntactically some code is required but you don't want to perform any action.

    {here , in this code we don't want to do anything with the numbers which are not divisible by 3 }

!!!! This are the learnings that I gathered in week-3 . !!!!