Sunday 3 March 2019

Add two Matrix in Python

# Program to add two matrices using nested loop
X = [ [12,7,3],
[4 ,5,6],
[7 ,8,9] ]
Y = [ [5,8,1],
[6,7,3],
[4,5,9] ]
result = [ [0,0,0],
[0,0,0],
[0,0,0] ]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)


Output:
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

Fibonacci Sequence in Python

# Python program to display the Fibonacci sequence up to n-th term using recursive functions,
def recur_fibo(n):
"""Recursive function to print Fibonacci sequence""" if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# Change this value for a different result
nterms = 10
# uncomment to take input from the user
#nterms = int(input("How many terms? "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):

Output:
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

Display Calendar in Python

# Python program to display calendar of given month of the year
# import module
import calendar
yy = 2014
mm = 11
# To ask month and year from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))


Output:
November 2014
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

Shuffle Deck of Cards in Python

# Python program to shuffle a deck of card using the module random and draw 5 cards
# import modules
import itertools, random
# make a deck of cards
deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))
# shuffle the cards
random.shuffle(deck)
# draw five cards
print("You got:")
for i in range(5):
print(deck[i][0], "of", deck[i][1])


Output:
You got:
5 of Heart
1 of Heart
8 of Spade
12 of Spade
4 of Spade

Make a Simple Calculator in Python

''' Program make a simple calculator that can add, subtract, multiply and divide using functions '''
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
## This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

Output:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210

Find Factors of Numbers in Python

# Python Program to find the factors of a number
# define a function
def print_factors(x):
# This function takes a number and prints the factors
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
# change this value for a different result.
num = 320
# uncomment the following line to take input from the user
#num = int(input("Enter a number: "))
print_factors(num)


Output:
The factors of 320 are:
1
2
4
5
8
10
16
20
32
40
64
80
160
320

Find LCM in Python

# Python Program to find the L.C.M. of two input number # define a function def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
# choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
# change the values of num1 and num2 for a different result
num1 = 54
num2 = 24
# uncomment the following lines to take input from the user
#num1 = int(input("Enter first number: "))
#num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))


Output:
The L.C.M. of 54 and 24 is 216

Find HCF to GCD in Python

# Python program to find the H.C.F of two input number
# define a function
def computeHCF(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
num1 = 54
num2 = 24
# take input from the user
# num1 = int(input("Enter first number: "))
# num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))

Output:
The H.C.F. of 54 and 24 is 6

ASCII value of character in Python

#Program to find the ASCII value of the given character
# Change this value for a different result
c = 'p' # Uncomment to take character from user
#c = input("Enter a character: ")
print("The ASCII value of '" + c + "' is",ord(c))


Output:
The ASCII value of 'p' is 112

Decimal to Binary in Python

#Python program to convert decimal number into binary, octal and hexadecimal number system
# Change this line for a different result
dec = 344
print("The decimal value of",dec,"is:")
print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
print(hex(dec),"in hexadecimal.")
Output:
The decimal value of 344 is:
0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.

Saturday 2 March 2019

Number Divisible by Number in Python

#Python Program to find numbers divisible by thirteen from a list using anonymous function
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
Output:
Numbers divisible by 13 are[65,39,221]

Display Power of 2 in Python

# Python Program to display the powers of 2 using anonymous function
# Change this value for a different result
terms = 10
# Uncomment to take number of terms from user
#terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
# display the result
print("The total terms is:",terms)
for i in range(terms):
print("2 raised to power",i,"is",result[i])
Output:
The total terms is: 10
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512

Sum of Natural Number in Python

# Python program to find the sum of natural numbers up to n where n is provided by user
# change this value for a different result
num = 16
# uncomment to take input from the user
#num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
Output:
The sum is 136

Check Armstrong Number in Python

#Python program to check if the number provided by the user is an Armstrong number or not
# take input from the user
# num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:

digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

Output 1:

Enter a number:663
663 is not an Armstrong number

Output 2:

Enter a number:407
407 is an Armstrong number

Fibonacci Sequence in Python

#Program to display the Fibonacci sequence up to n-th term where n is provided by the user
# change this value for a different result
nterms = 10
# uncomment to take input from the user
#nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 0
# check if the number of terms is valid
if nterms <= 0:

print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Output:

Fibonacci sequence upto 10 :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Display Multiple Table in Python

'''Python program to find the
multiplication table (from 1 to 10)'''
num = 12
# To take input from the user
# num = int(input("Display multiplication table of? "))
# use for loop to iterate 10 times
for i in range(1, 11):

print(num,'x',i,'=',num*i)

Output:

12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120

Factorial of Number in Python

#Python program to find the factorial of a number provided by the user.
# change the value for a different result
num = 7
# uncomment to take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:

print("Sorry, factorial does not exist for negative numbers")
elif num == 0:

print("The factorial of 0 is 1")
else:

for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

Output:

The factorial of 7 is 5040

Print Prime Number in Python

#Python program to display all the prime numbers within an interval
# change the values of lower and upper for a different result
lower = 900
upper = 1000
# uncomment the following lines to take input from the user
#lower = int(input("Enter lower range: "))
#upper = int(input("Enter upper range: "))
print("Prime numbers between",lower,"and",upper,"are:")
for num in range(lower,upper + 1):

# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)

Output:

Prime numbers between 900 and 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997

Check Prime Number in Python


#Python program to check if the input number is prime or not
num = 407
# take input from the user
# num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:

# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:

print(num,"is not a prime number")

Output:

407 is not a prime number
11 times 37 is 407

Check Largest Among Three Numbers

# Python program to find the largest number among the three input numbers
# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12
# uncomment following lines to take three numbers from user #num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):

largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)

Output:

The largest number between 10, 14 and 12 is 14.0

Check Leap Year in Python

# Python program to check if the input year is a leap year or not
year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
if (year % 4) == 0:

if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))

Output:

2000 is a leap year

Check Number Odd or Even in Python

# Python program to check if the input number is odd or even.
# A number is even if division by 2 give a remainder of 0.
# If remainder is 1, it is odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

Output1:

Enter a number: 43
43 is Odd

Output2:

Enter a number: 18
18 is Even

Convert Celsius To Fahrenheit in Python

# Python Program to convert temperature in celsius to fahrenheit
# change this value for a different result
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))

Output:

37.5 degree Celsius is equal to 99.5 degree Fahrenheit

Convert Kilometres To Miles in Python

kilometers = 5.5
# To take kilometers from the user, uncomment the code below
kilometers = input("Enter value in kilometers")
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))

Output:

5.500 kilometers is equal to 3.418 miles

Swap Two Variables in Python

#Python program to swap two variables
# To take input from the user
# x = input('Enter value of x: ')
# y = input('Enter value of y: ')
x = 5
y = 10
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

Output:

The value of x after swapping: 10
The value of y after swapping: 5

Solve Quadratic Equation in Python


#Solve the quadratic equation ax**2 + bx + c = 0
# import complex math module
import cmath
a = 1
b = 5
c = 6
# To take coefficient input from the users
# a = float(input('Enter a: '))
# b = float(input('Enter b: '))
# c = float(input('Enter c: '))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

Output:

Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

Area of Triangle in Python


# Python Program to find the area of triangle
a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Output:

The area of the triangle is 14.70

Find Square Root in Python

# Python Program to calculate the square root
# Note: change this value for a different result
num = 8
# uncomment to take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

Output:

The square root of 8.000 is 2.828

Friday 1 March 2019

R packages

R packages are a collection of R functions, complied code and sample data. They are stored under a directory called "library" in the R environment. By default, R installs a set of packages during installation. More packages are added later, when they are needed for some specific purpose. When we start the R console, only the default packages are available by default. Other packages which are already installed have to be loaded explicitly to be used by the R program that is going to use them.
All the packages available in R language are listed at R Packages.
Below is a list of commands to be used to check, verify and use the R packages.

Check Available R Packages

Get library locations containing R packages
.libPaths()

When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc.
[2] "C:/Program Files/R/R-3.2.2/library"

Get the list of all the packages installed

library()
When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc.
Packages in library ‘C:/Program Files/R/R-3.2.2/library’:

base                    The R Base Package
boot                    Bootstrap Functions (Originally by Angelo Canty
                        for S)
class                   Functions for Classification
cluster                 "Finding Groups in Data": Cluster Analysis
                        Extended Rousseeuw et al.
codetools               Code Analysis Tools for R
compiler                The R Compiler Package
Get all packages currently loaded in the R environment
search()
When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc.
[1] ".GlobalEnv"        "package:stats"     "package:graphics" 
[4] "package:grDevices" "package:utils"     "package:datasets" 
[7] "package:methods"   "Autoloads"         "package:base" 

Install a New Package

There are two ways to add new R packages. One is installing directly from the CRAN directory and another is downloading the package to your local system and installing it manually.

INSTALL DIRECTLY FROM CRAN

The following command gets the packages directly from CRAN webpage and installs the package in the R environment. You may be prompted to choose a nearest mirror. Choose the one appropriate to your location.
 install.packages("Package Name")
 
# Install the package named "XML".
 install.packages("XML")

INSTALL PACKAGE MANUALLY

Go to the link R Packages to download the package needed. Save the package as a .zip file in a suitable location in the local system.
Now you can run the following command to install this package in the R environment.
install.packages(file_name_with_path, repos = NULL, type = "source")

# Install the package named "XML"
install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source")

Load Package to Library

Before a package can be used in the code, it must be loaded to the current R environment. You also need to load a package that is already installed previously but not available in the current environment.
A package is loaded using the following command −
library("package Name", lib.loc = "path to library")

# Load the package named "XML"
install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source")

Tuesday 19 February 2019

String Operation in Python

In Python String is a sequence of characters.

It is an object that represents a sequence of characters. You can create a string in python as shown below
Python Code:
x = "XMarksThe Spot"

String are constant. They cannot be changed once memory is allocated for them. Every time you perform operations on a String it rather creates a new string. Below example show you some common String operations in Python.
Python Code:
s = "XMarksTheSpot"
upper(s) # Prints XMARKSTHESPOT
lower(s) # Prints xmarksthespot
s.startswith("XMa") # Prints True
s.replace("X", "Y") # Prints YMarksTheSpot
len(s) # Prints 13
s[0] # Prints X
s[1] # Prints MarksTheSpot

We can slice parts of a string using slice operator :. The digit in front of the the : represents the start index. The digit after the : represents the end index. For example :
Python Code:
>>> s[1:3]
'Ma'

We can get list of characters for a given string using list function.
Python Code:
>>> list(s)
['X', 'M', 'a', 'r', 'k', 's', 'T', 'h', 'e', 'S', 'p', 'o', 't']

We can remove leading and trailing space from a string using strip function.
Python Code:
>>> x = " I have a lot of space before and after me...... do I?"
>>> x.strip( )
'I have a lot of space before and after me... do I?'

We can remove spaces from the left of a string using Istrip function.
Python Code:
>>>x.Istrip( )
' I have a lot of space before and after me ... do I? '

We can remove spaces from the right of a string using rstrip function.
Python Code:
>>> x.rstrip( )
' I have a lot of space before and after me ... do I? '

Join function on a string can join a list of strings using a specified delimiter. In the example below, we are joining a list of strings with comma as delimiter.
Python Code:
>>> ",".join (["Apple","a","day"])
'Apple,a,day'

We can check whether a given string starts with a substring using startswith method.
Python Code:
>>> y = "Superwoman"
>>> y.startswith("Duper")
False
>>> y.startswith("Super")
True

We can check whether a given string ends with a substring using endswith method.
Python Code:
>>> y.endswith("girl")
False
>>> y.endswith("woman")
True

We can use split method on a string to split a string into a list of substrings. To the split method, we need to pass a delimiter on which the split operation is to be performed.
Python Code:
>>> z="www.ntirawen.com"
>>>z.split(".")
['www','ntirawen','com']

zfill function is used to fill up the leading part of string with zeros until the specified with.
Python Code:
>> z.zfill(25)
'00000000www.ntirawen.com'

We can format a string using % operator. % is a format specifier used to specify how the data is to be formatted. In the below example, we are using %d format specifier which is an integer. 
Python Code:
>>> "There are %d letters in the alphabet" % 26
'There are 26 letters in the alphabet'

In the below example, we are using %s format specifier, which is a string, in addition to %d format specifier.
Python Code:
>>> "There are %d planets. The largest planet is %s" %(8,"Jupiter")
'There are 8 planets. The largest planet is Jupiter'

Sunday 17 February 2019

Loops in Python

Loops are used in cases where you need to repeat a set of instruction over and over again until a certain condition is met. There are two primary  types of looping in Python.
  • For Loop
  • While Loop

For Loop

Python Code:
for i in range(1,10):
  print(i, end=' ')

A for loop contains three operations. The first operation i is initializing the loop iterator with first value of range function. range function is supping values as iterator from (1,10).for loop catches the Stop Iterator error and breaks the looping.

Output:
1 2 3 4 5 6 7 8 9

While  Loop

Python Code:
i = 0
while i < 10:
  print(i, end= ' ')
   i+=1

Output:
1 2 3 4 5 6 7 8 9

A while loop variable is initialized before the statement. Here we initialized i to 0. In the while statement, we have kept until when the loop is valid.

So here we check up to i < 10. Inside the while loop we are printing i and then incrementing it by 1.
Imagine what would happen if we don't increment i by 1?
The loop will keep running a concept called infinite loop. Eventually the program will crash.

Break and Continue:

Break Statement:

A break statement will stop the current loop and it will continue to the next statement of the program after the loop.

Python Code:
i = 0
while i < 10:
   i+ = 1
   print(i, end=' ')
    if i == 5:
       break

Output:
1 2 3 4 5

In the above random example, we are incrementing i from an initial value of 0 by 1. When the value of i is 5, we are breaking the loop.

Continue Statement:

Continue will stop the current iteration of the loop and it will start the next iteration.It is very useful when we have some exception cases, but do not wish to stop the loop for such scenarios.

Python Code:
i = 0
while i < 10:
  i+ = 1
  if i%2 == 0:
     continue
  print(i, end= ' ')

Output:
1 3 5 7 9

In the above example, we are skipping all even numbers via the id conditional check i%2.So we end up printing only odd numbers. 

Saturday 16 February 2019

Conditional Statements in Python

Conditional statement in python can be used to take decisions based on certain conditions in your program.

In this blog we will describe you four most commonly used forms of conditionals.We will encounter more of these forms and variations in your professional programming life.
  • If Then
  • If Then Else
  • If Then Else If Else
  • Nested If Then
If Then :

As the name indicates it is quite simple.If a certain condition is satisfied, then perform some action.

Python Code:
accountBalance = 0
if accountBalance < 1000
  print("Close Account!")

Output:
Close Account!

In the example above, we are checking account balance in the if statement. If the account balance comes to less than 1000, we are printing a line to close the account.

In a real world scenario this can be the case to check an account has minimum balance.

If Then Else:

An extra else statement can be added to an if condition, to execute what should happen if the if condition is not satisfied.

Python Code:
accountBalance = 1001
if accountBalance < 1000:
  print("Close Account!")
else:
  print("We love having you with us!")

Output:
We love having you with us!

In the above example, if the account balance is >=1000, we are printing a warm message.

If Then Else If Else:

If a primary if condition is not satisfied, we can add an Else if statement in between to check another condition if required.

Python Code:
accountBalance = 1000002
if accountBalance < 1000:
    print("Close Account!")
elif accountBalance > 1000000:
   print("We really love having you with us. Please find a Europe tour cruise package in your mailbox!")
else:
   print("We love having you with us!")


Output:
We really love having you with us. Please find a Europe tour cruise package in your mailbox!

In the above example, we added an else if condition.
For high valued customers who have more than a large threshold of account balance with us, we printed a separate message.

Nested If Then:

We can nest multiple If Then statements. Be careful when using this as it can become a mess to read . You can use && or || operators to avoid it in some scenarios.

Python Code:
accountBalance = 600
if accountBalance < 1000:
    if accountBalance < 500:
        print("Close Account!")
      else:
        print("You better maintain a minimum balance Pal! You got 5 days time.")
elif accountBalance > 1000000:
 print("We really love having you with us.Please find a Europe tour cruise package in your mailbox!")
else:
 print("We love having with us!")

Output:
 You better maintain a minimum balance Pal! You got 5 days time.

In the above example, we added a nested if statement where we are further checking if account balance is less than 500. If it is not, then we are giving a friendly and warm warning message.

Data Types and Operators in Python

The Data types in Python are :
  • boolean
  • byte
  • list
  • tuple
  • dict
  • Complex Number
  • float
  • long
  • string
Primitive data types are stored in stack memory.

boolean:
Valid values: true, false
Default value: false
Size: 1 bit

Python Code:
isEnabled = True

Byte:

Python Code:
b'Python'

List:

Python Code:
listOfFruits = ["apples", "mango", "bananas"]

Tuple:

Python Code:
listOfVegetables = ("carrot", "brinjal", "cauliflower")

Dict:

Python Code:
numberDictionary = {"ONE" : 1, "TWO" :2}

Complex Number: 

Python Code:
z = 2+3j

float:
Python Code:
x = 2.3

long:
Python Code:
bigValue = 1094324242344L

string:
Python Code
x = "The Quick Brown Fox Jumps Over The Lazy Dog"


Python Operators: 

Listed below are various operators available in Python. A brief description is provide with the operators and an example of most commonly used operators is provided to end this blog.

Multiplication/division operators:

* : It multiples the left and right operand and returns the result.
% : Modulo operator. Divides the left operand with the right operand and returns the remainder.
/  : Division Operator. Divides the left operand and returns the result.

Additional / Subtraction :

+ : Addition Operator. Adds the left operand with the right operand and returns the result.
- : Subtraction Operator. Subtracts the left operand and right operand and returns the result.

Shift Operators :

<< : Left Shift Operator. Moves the left operand to the left by the number of bits specified by the right operand.
>> : Right Shift Operator. Moves the left operand to the left by the number of bits specified by the right operand.

Relational Operators :

< : Less than Operator. Check if the left operand is less than the right operand. Return True or False.
> : Greater than Operator. Check if the left operand is greater than the right operand. Return True or False.
>= : Greater than or equal to. Check if the left operand is greater than or equal to the right operand . Return True or False.
is : Instance of Operator. Check if the left operand is instance of right operand. Example: Is Dog Animal. True. Is Dog Plant. False.


Equality :

== : Check if left operand is equal to the right operand. Return True or False.
!= : Check if left operand is not equal to the right operand. Return True or False.

Bitwise AND :
& : Bitwise AND Operator. If bit exists in both left and right operand, copy the bit to the result.

Bitwise exclusive OR :
^ : Bitwise XOR Operator. If bit is set in either left or right operand but not in both, copy the bit to the result.

Bitwise inclusive OR :
| : Bitwise OR Operator. If bit exists in either left to right operand is true, the result will be true else false.

Logical AND :
and : Logical AND Operator. If both left and right operand is true, the result will be true else false.

Logical OR :
or : Logical OR Operator. If Either left or right operand is true, the resultwill be true or false.

Assignment Operator :

= : Assignment operator. Assign the right operand to the left operand.
+= : Add plus assignment operator. Adds the left and right operand AND assigns the result to the left operand
-= : Subtract plus assignment operator. Subtract the left and right operand AND assigns the result to the left operand.
*= : Multiples plus assignment operator. Multiplies the left and right operand AND assigns the result to the left operand.
/= : Divides plus assignment operator. Divides the left and right operand And assigns the result to the left operand.
%= : Modulo plus assignment operator. Divides the left and right operand AND assigns the remainder to the left operand.
&= : Bitwise AND plus assignment operator.
^= : Bitwise OR plus assignment operator.
>>= : Right shift plus assignment operator.

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (115) C (77) C# (12) C++ (82) Course (62) Coursera (178) coursewra (1) Cybersecurity (22) data management (11) Data Science (91) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (747) Python Coding Challenge (203) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses