article

Monday, May 29, 2017

Python Function and Loop Example code

Python Function and Loop Example code
 
#!/usr/bin/python

#A function is created with the def keyword
def function():
    pass
#-------------------------------------------------------   
def printme( str ):
   "This prints a passed string into this function"
   print (str)
   return
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
#-------------------------------------------------------
# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   print ("Values inside the function before change: ", mylist)
   mylist[2]=50
   print ("Values inside the function after change: ", mylist)
   return

# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
#-------------------------------------------------------
# Function definition is here
def printinfo( name, age ):
   "This prints a passed info into this function"
   print ("Name: ", name)
   print ("Age ", age)
   return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
#-------------------------------------------------------

print "1 + 1 =", 1 + 1
print "2 * (2 + 3) =", 2 * (2+3)
print "1.2 / 0.3 =", 1.2 / 0.3
print "5 / 2 =", 5 / 2
# 1 + 1 = 2
# 2 * (2 + 3) = 10
# 1.2 / 0.3 = 4.0
# 5 / 2 = 2

#functions
def square(number):
 sqr_num = number **2
 return sqr_num
 
input_num = 5
output_num = square(input_num)
print "print output", output_num 

#function morethan one input
def returnDifference(n1, n2):
 """Return the difference between two numbers.
 Subtracts n2 from n1."""
 return n1 - n2
print "print output", returnDifference(1,1)
 
def add_two_numbers(num1, num2):
 sum = num1 + num2
 return sum
print "print output", add_two_numbers(1,1)
print "print output", add_two_numbers(1,2) 

#loop
n = 1
while (n < 5):
 print "n =", n
 n = n +1
 print "Loop finished "
 
for n in range(1, 5):
 print"n =", n
 print "Loop finished " 
 
for i in range(0, 4):
 if i == 2:
    break
 print i
print "Finished with i = ", str(i) 

phrase = "it marks the spot"
for letter in phrase:
  if letter == "ks":
    print "yes ks" 
  break
else:
  print "There was no 'X' in the phrase"

tries = 0
while tries < 3:
 password = raw_input("Password: ")
 if password == "ednalan":
     break
 else:
     tries = tries +1
else:
     print "Suspicious activity. The authorities have been alerted."

total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2; # Here total is local variable.
   print ("Inside the function local total : ", total)
   return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )  
#-------------------------------------------------------------------
def add_two_numbers(num1, num2):
    sum = num1 + num2
    return sum
    print(add_two_numbers(1,1)) #2
#---------------------------------------------------------------------
n = 1
while (n < 5):
  print("n =", n)
  n = n + 1
print("Loop finished")    
#---------------------------------------------------------------------
numbers = [22, 34, 12, 32, 4]
sum = 0
i = len(numbers)
while (i != 0):
   i -= 1
   sum = sum + numbers[i]
print "The sum is: ", sum
#---------------------------------------------------------------------
import random
while (True):
   val = random.randint(1, 30)
   print val, # 14 14 30 16 16 20 23 15 17 22
   if (val ==  22):
      break
#---------------------------------------------------------------------
import random
num = 0
while (num < 1000):
   num = num + 1
   if (num % 2) == 0:
      continue
   print num,   
#---------------------------------------------------------------------
import random as rnd
for i in range(10):
   print rnd.randint(1, 10),    # 1 2 5 10 10 8 2 9 7 2

def root(x):
   return x * x
#---------------------------------------------------------------------
def root(x):
   return x * x
a = root(2)
b = root(15)
print a, b  
#---------------------------------------------------------------------
x = 15
def function():
   global x
   x = 45
function()
print x # 45
#---------------------------------------------------------------------
print 4 in (2, 3, 5, 6)
for i in range(25):
   print i, # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#---------------------------------------------------------------------
def gen():
   x = 11
   yield x
it = gen()
print it.next() # 11
#---------------------------------------------------------------------
def showModuleName():
    print __doc__
def getModuleFile():
   return __file__
a = showModuleName()
b = getModuleFile()
print a, b
#---------------------------------------------------------------------
def f():
    """This function prints a message """
    print "Today it is a cloudy day"
print isinstance(f, object) # True
print id(f) # 3077407212
print f.func_doc # This function prints a message 
print f.func_name # f
#---------------------------------------------------------------------
from math import sqrt
def cube(x):
    return x * x * x     
print abs(-1)
print cube(9)
print sqrt(81)
#---------------------------------------------------------------------
def showMessage(msg):
    print msg
def cube(x):
    return x * x * x   
x = cube(3)    
print x # 27
showMessage("Computation finished.") # Computation finished.
print showMessage("Ready.") # Ready.
#---------------------------------------------------------------------
n = [1, 2, 3, 4, 5]
def stats(x):
    mx = max(x)
    mn = min(x)
    ln = len(x)
    sm = sum(x)
    return mx, mn, ln, sm    
mx, mn, ln, sm = stats(n)
print stats(n) # (5, 1, 5, 15)
print mx, mn, ln, sm # 5 1 5 15
#---------------------------------------------------------------------
def C2F(c):
    return c * 9/5 + 32
print C2F(100) # 212
print C2F(0) # 32
print C2F(30) # 86
#---------------------------------------------------------------------
def power(x, y=2):
    r = 1
    for i in range(y):
       r = r * x
    return r
print power(3) # 9
print power(3, 3) #27
print power(5, 5) # 3125
#---------------------------------------------------------------------
def display(name, age, sex):
   print "Name: ", name
   print "Age: ", age
   print "Sex: ", sex
display("Lary", 43, "M") # Name:  Lary Age:  43 Sex:  M
display("Joan", 24, "F") # Name:  Joan Age:  24 Sex:  F


Monday, May 1, 2017

Create Custom Shortcode in WordPress Post, Page and Plugin

Create Custom Shortcode in WordPress Post, Page and Plugin

Edit current theme's function.php add this code


function recent_posts_func( $atts, $content = NULL ){
    $content = $content?$content:'Latest Posts';
    $a = shortcode_atts(
        array(
            'posts'=>5
        ),
        $atts
    );
    $args = array('numberposts'=>$a['posts']);
    $recent_posts = wp_get_recent_posts( $args, ARRAY_A );
    echo '<div class="recent-posts">';
    echo '<h1>'.$content.'</h1>';
    foreach($recent_posts as $post){
    ?>
    <div class="updated"><p><?php echo $post['post_title']; ?>. <a href="<?php echo get_permalink($post["ID"]); ?>"><span>Show Details</span>.</a></p></div>
    <?php
    }
    echo '</div>';
}
add_shortcode( 'latestposts', 'recent_posts_func' );

Shortcode content view:

Insert the shortcode through the WordPress admin panel editor, use the below code.

[latestposts posts="2"]Recent Posts[/latestposts]

Related Post