Programming Examples

Imported library in Python

from time import *
print(eval('dir()', {'sleeptime': sleep, 'Localtime': localtime}))

Local and global variables in the eval method in Python

from time import *
print(eval('dir()', {}))

Python eval

# expression to be evaluated 
user_expr = raw_input("Enter an expression in terms of variable a):") 
#nter the value of variable
a = int(raw_input("Enter the value of a:")) 
# evaluate the expression 
result = eval(user_expr) 
# printing evaluated result 
print("Result = {}".format(result))

Split a string in Python

str = "Apple Banana  Grapes Apple";
print(str.split(' ', 2))

String is a valid keyword in Python

import keyword


for word in list:
    if keyword.iskeyword(word):
        print ( word + " is a python keyword")
    else :  print ( word + " is not a python keyword")

Help function in Python


Filter in Python

# list of Months
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug']

# function that filters some Months
def filterMonths(months):
    MonthsWith31 = ['Apr', 'Jun','Aug','Oct']

    if(months in MonthsWith31):
        return True
        return False

non30months = filter(filterMonths, months)

print('The filtered Months :')
for month in non30months:

Using math factorial in Python

import math

num = input("Enter a number: ")
print("The factorial of ", num, " is : ")

Using Recurssion in Python

num = input("Enter a number: ")
def recur_factorial(n):
   if n == 1:
       return n
   elif n < 1:
       return ("NA")
       return n*recur_factorial(n-1)

print (recur_factorial(int(num)))

Factorial in Python

n = input("Enter a number: ")
factorial = 1
if int(n) >= 1:
    for i in range (1,int(n)+1):
        factorial = factorial * i
print("Factorail of ",n , " is : ",factorial)


We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.