Friday, January 31, 2020

Python for loop

Python for loop


The "for" is an iteration loop in Python like other programming languages. The for loop is generally programmer's first choice when they want to iterate in their code, especially when the limit of the iteration is known and predefined. We can iterate elements in collection or sequence(iterable objects) in Python using for loop. For example, we can iterate over a list, tuple, set, or dictionary.

for loop python

Iterating a List,
for item in [14,17,20,11,25]:
  print(item)

Output:
14
17
20
11
25


Iterating in a range,
We can iterate over a provided range.

for item in range(1,5):
  print(item)

Output:
1
2
3
4


or,

for item in range(4):
  print(item)

Output:
0
1
2
3

for loop is iterated over any iterable object, which is an object defines a __getitem__ or a __iter__  function. The __ iter__ method returns an iterator, which is an object with a next function that is used to access the next element of the given iterable.

for item in ["Python","is","easy","yet","powerful","programming","language"]:
    print(item)

Output:
Python
is
easy
yet
powerful
programming
language  

If we want to iterate a list with an index of the item then we can use enumerate function. For example

for index, element in enumerate(["Python","is","easy","yet","powerful","programming","language"]):
    print(index,"->",element)

Output:
0 -> Python
1 -> is
2 -> easy
3 -> yet
4 -> powerful
5 -> programming
6 -> language  

The 'break' statement in a loop

The "break" statement forces control to come out the innermost loop, in an iteration.break are generally applied inside if statement nested inside an iteration statement like for, while and do-while.

for example,(linear search with for-loop)

def linearSearch(num):
  count=0  
  l=[7,12,25,0,11,36,41]
  length=len(l)
  for x in l:
    count=count+1    
    if num==x:
      print('found')
      break  
    #control will come out from the loop  
  if count>=length:
    print('not found')
linearSearch(11)
linearSearch(75)

Output:
found
not found

The 'continue' statement in a loop

The "continue" statement will jump to the next iteration, skipping all remaining code inside the current loop block but continuing the loop. Like break, continue can appear inside loops only.

for x in range(1,20):
  if x%2==0 or x%3==0:
    continue 
  print('2 and 3 are not a divisor of ',x)
    
Output:
2 and 3 are not a divisor of  1
2 and 3 are not a divisor of  5
2 and 3 are not a divisor of  7
2 and 3 are not a divisor of  11
2 and 3 are not a divisor of  13
2 and 3 are not a divisor of  17
2 and 3 are not a divisor of  19

The 'else' clause with for-loop

The "for-loop" optionally can have else clause, for example

for i in range(3):
  print(i)
else:
  print('range finished')

Output:
0
1
2
range finished

Iterating String with for loop

Strings are iterable objects and can be iterated over for loop easily.


for i in 'Python':
  print(i)

Output:
P
y
t
h
o
n

True and False values

True and False values in Python


All the values in Python are True except (All Boolean expressions return either True or False)
  1. None
  2. False
  3. Number values equal to 0 like 0, 0,0, 0L and 0j 
  4. All empty sequences like ' ', "",(),[] and mappings like {}
  5. All user-defined types having __bool__ and __len__ method return values as 0 or False.
None is like undef or Null or Nill in other languages. To test all of the above we can use not operator in Python, which returns the reverse of any Boolean expression on which it is applied.

#Booleans in Python
if not(False):
 
print(True) #True
if not(None):
 
print(True#True
if not(0):  #False is 0 and True is 1
 
print(True#True
if not(0.0):
 
print(True#True
if not([]):   
 
print(True#True
if not(()):
 
print(True)   #True
if not([]):
 
print(True)   #True
if not({}):
 
print(True)   #True
if not(''):
 
print(True)   #True
if not(""):
 
print(True)   #True

Try yourself:


Thursday, January 30, 2020

Branching statements(if else elif)

Branching Statements(conditionals) in Python


Like other programming languages branching statements are also available in Python. In python, we have if, if-else, and if-elif-else statements. Your program can execute different branching actions based on Boolean conditions (True or False). Else-if is not used in Python, instead, elif is available.

if-statement

If else statement is used to execute a block of code only if a test condition is fulfilled, Otherwise this block of code will be bypassed untouched.

The Syntax for if-statement is,

if conditionExpression:           
   #  Code to execute if
   #  conditionExpression is true


For example,

i = 70
if (i > 50): 
   print ("70 is less than 50") 
print ("I am Not part of if-statement") 

if-else-statement


If else statement has two blocks of code as options to execute, one of which is executed if the test expression is fulfilled, and the other is executed if the test expression is failed. 

The syntax for the if-else statement is,

if (conditionExpression):
    # Executes this block of code if
    # if conditionExpression is true
else:
    # Executes this block of code if
    # if conditionExpression is false


For example,

i = 50; 
if (i < 20): 
    print ("i is smaller than 20") 
    print ("This is if Block") 
else: 
    print ("i is greater than 20") 
    print ("This else Block") 
print ("This is outside the if-else statement")

if-elif-else statement



An if-elif-else statement is something like if-else if-else ladder in other programming languages. When the user has multiple test expressions associated with multiple blocks of code to execute, then this statement can be applied.

The syntax for if-elif-else is,

if (Test Expression 1):
    statement
elif (Test Expression 2):
    statement
.
.
else:
    statement



For example, 

i = 2
if (i == 1): 
    print ("RED") 
elif (i == 2): 
    print ("BLUE") 
elif (i == 3): 
    print ("GREEN") 
else: 
    print ("YELLOW")


Example:



num=3
if num%2==1:    #if example
 print('odd')
 
if num%2==0:    #if-else example
  print('even')
else:
  print('odd')
  
if num==1:    #if-elif-else example
  print('good')
elif num==2:
  print('very good')
elif num==3:
  print('best')
else:
  print('best')


Tuesday, January 28, 2020

Recursion in Java

Recursion in Java

A method is known as a recursive method if it invokes itself directly or indirectly(by some other method). Recursive methods must eventually terminate at some point in time. A recursive method has at least one base-case or case upon which, the execution of methods generally halts. Each successive call to itself must be a "smaller version of itself" so that a base case is finally reached. The arguments of the method are made smaller each time of the invocation of the method so that eventually the base case is executed and finishes the recursion process. Actually, the recursive method can execute the simplest version of the problem only. For the larger or complex version, it will further divide the problem into smaller pieces.

factorial with Recursion
Factorial 

Example( calculating the factorial with Iteration)


//Calculating Factorial of a number using
public class Demo {
public static void main(String[] arg) {
    //Iteration
    Demo d=new Demo();
System.out.println(d.factorial(7));
}
int factorial(int num)
{
    int fact=num;//num>=1 only
    for(int counter=num-1;counter>=1;counter--)
    {
        fact=fact*counter;
    }
    return fact;
}
}

Calculating factorial with recursion


public class DemoRecursion {// Factorial by recursion

    public static void main(String[] args) {
    DemoRecursion dr=new DemoRecursion();
    System.out.println(dr.factorial(7));
    }
    int factorial(int num)// recursive method
    {
        if(num<=1)
        {
            return 1;//base case
        }
        else
        {
            return num*factorial(num-1);
        }
    }
}

Video Tutorial



Monday, January 27, 2020

Java Applets

Applets

Java applets are small programs or snippets those can be embedded into a web page, can be transported over internet, can run inside a browser(or some other application), can be downloaded by the users, provides a rich environment for web applications and usually pretend to run at their own. We generally provide some user interface to users to interact with Applets. We can run Applets either by a special program known as Applet Viewer or inside some browser. The browser must have Java plug-in to manage the life cycle of the Applet.

Java Applets can perform following events in its life cycle

  • Initialize itself (init() method)
  • Start itself (start() method)
  • Stop itself (stop() method)
  • Destroy itself (destroy() method)

Your Applet class must be the subclass of an Applet. The Applet class specifies a standard interface between applets and their environment. Java Applets are now becoming obsolete now, as the latest versions of Java are discontinuing support for Applets.

Example

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
//Applet class
public class MyApplet extends Applet{

    @Override
    public void destroy() {//clean the object from memory
       
        super.destroy();
        System.out.println("destroyed");
    }

    @Override
    public void init() {//Initialize the object
       
        super.init();
        System.out.println("initialized");
    }

    @Override
    public void start() {//Start executing
       
        super.start();
        System.out.println("started");
    }

    @Override
    public void stop() {//Stop executing
       
        super.stop();
        System.out.println("stopped");
    }

    @Override
    public void paint(Graphics g) {//Let's draw something over screen
        g.setColor(Color.BLUE);
        g.drawLine(10, 15, 300, 500);
        g.drawLine(500, 300, 15, 10);
        g.drawString("Welcome to Applet", 100, 100);
    }  
}

Video Tutorial: