Social Media

Image Slider

12/31/2018

Ternary Operator in Python

In Python language ternary operator is not present. But we can use if else in place of ternary operator here. The syntax is as:
value1 if condition else value2

The simple script to show the usage is as given below:

x=int(input("enter the number"))
y=int(input("enter second number"))
z= x if x>0   else y
print(z)

Problem1: Write a simple script to print the greatest number among two numbers entered  by the user.

x=int(input("Enter first number "))

y=int(input("Enter second number "))
print("The greatest number is",x if x>y else y)

12/29/2018

Flow Control: Iterative Control

for and while loops are used for iteration purpose.
They have a termination condition always.
range() function: 
The different types of usage of range() method is as follows:
range(100) will work from 0 to 99
range(2,100) will work from 2 to 99
range(1,100,2) will work from 1 to 99 and increment every time by 2 (1,3,5,....99)
range(100,2,-1) will work from 100 to 3

The usage of for and while are explained below using the problems given below:
Problem1: Calculate the factorial of a number using for loop

n=int(input())
ans=1
if n==0 or n==1:
    print("Factorial of {} is {}".format(n,ans))
else:
    for i in range(2,n+1):
        ans*=i
    print("Factorial of {} is {}".format(n,ans))

Problem2: Print natural numbers in reverse number where last number is supplied by the user using while loop.

n=int(input())
while n!=0:
    print(n)
    n-=1


Problem3: Write a script in Python to check whether the number entered by user is prime or  not.

n=int(input())
if n==1 or n==2:
    print("{} is Prime".format(n))
else:
    for i in range(2,n//2+1):
        if n%i==0:
            print("{} not Prime".format(n))
            break
    else:
        print("{} is Prime".format(n))

Problem4: Write a script to print the number between 1 to 100 except those which are divisible by 7.

for i in range(2,100):
    if i%7==0:
        continue
    else:
        print(i)

Problem5: Write an script which shows the use of pass statement.


pass keyword is use when we have to leave empty block. The example is as:

x=int(input())
if x<=0:
    pass
else:
    print("Number greater than 0")


Flow Control : Decision Control

There are two types of flow control.
1. Decision Control (if, if-else, if elif else)
2. Iterative control (while,for)
do while and switch are not available in Python.

Transfer Statements: Three transfer statements are available in Python namely break, continue and pass.
So without wasting much more time on theory we will learn all of these using simple scripts.

Decision Control:
if block is executed when condition given in that is True.
Here indentation is  most important.
Indentation defines the scope of the block.

Problem1: Write a script which check whether the number entered by user is even or odd.

n=int(input("Enter the number: "))
if n%2==0:
    print("Even")
else:
    print("Odd")

Problem2: Write a program which takes a number from user, if it is greater than 0 print positive, if less than 0 print negative if 0 print neutral.

n=int(input("Enter the number: "))
if n>0:
    print("Positive")
elif n<0:
    print("Negative")
else:
    print("Neutral")

input() function features

We can use input() method in many forms. For converting the input entered by user into float we can use float() method as shown below:
x=float(input("Enter any number"))
print(type(x))  # float

We can also take multiple string input in a single line as follows:
Here we are taking two string inputs from the user in a single line using two input() function.




If we want to take space separated inputs using a single input() method then we can do like this.

split() function by default separates the input() if a space is comes between strings. Then first string before space character will go into the x and second into the y.
We can also separate inputs entered by user using another character also. For example:
x,y=input("Enter two strings :").split("/")

Note: We cannot directly convert string inputs in case when we are taking multiple inputs using a single input function means this will gives us error message:
x,y=int("Enter two values").split()
For such kind of inputs we have to do in this way:









12/24/2018

Input from user

In python for taking input from the user we  have input() method.
Input method by default treat all inputs as string.
input() function  can take a single string type argument.

x=input()
print(type(x)) #str

Write a script to find out the sum of two numbers:
x=int(input("Enter first number"))
y=int(input("Enter second number"))
sum=x+y
print("The sum is ",sum)

The complex number input format in python is 3+6j etc
Here is  simple script which can take a complex number as input.
x=input()
y=complex(x)
print(type(x),type(y))  #<class 'str'> <class 'complex'>

12/23/2018

Identity and Membership Operators

 Identity operators:
Two operators comes under the category of identity operator.
1. is
2. is not


  • is operator: is operator is used to compare the memory locations. It tells whether both the reference variables pointing to same memory locations or not. It returns True if they are referring to same memory locations otherwise return False.

example
x=4
y=4
print(x is y)  # True

x=4

y=4.0
print(x is y) #False


  • is not operator: is  not operator gives the reverse result of is operator. You can apply is operator first and then you can reverse the result for is not operator.


Membership Operator:
Membership operator can only be applied on sequential data types eg. string, list, tuples etc.
There are two types of membership operators present in the python language.
1. in operator
2. not in operator


  • in operator: If specified value is present in the sequence it will return True otherwise it will return False.  See the examples given below


x="mayank"
"a" in x # True
"A" in x  # False

x=2,4,5,6 (tuple)

4 in x # True

x="mayank"

"may" in x # True

x=345

4 in x # error because x is not iterable here


  • not in operator: It gives the reverse result of in operator. You can perform in operation first and then reverse the result to get output of not in operator.


Bitwise and Assignment Operator

Bitwise Operator:
The table for explanation of bitwise operator is given below.
OperatorExpressionResult
&9&31
|3|47
~~8-9 (one's complement)
^3^56(exor same 0 different 1)
>>78>>219 (right shift)
<<9<<372 (left shift)

Bitwise operator are those operators which works on bits. First you have to convert the operands into binary and then apply the operation to get the result.

Assignment Operator:
The table for assignment operator is as follows:
OperatorExpresion/ example
=x=9
+=, -=,  *=, /=, %=x+=8
&=, |=,^=6^=2
>>=, <<=4>>=2


12/22/2018

Logical Operators

There are 3 logical operators available in Python.
and, or , not.

Operator
Expression
Explanation
anda>b and a<cBoth true then true
ora>b and a<cAny one true then true
notnot a>bInvert the result


3>4 and 5>6  #False
3 or 4 #3
3 and 4 #4
Empty string is treated as False.
Non empty strings are treated as true.
The important points to be noted are as follows:
  •  x and y: If x and y are not boolean then  result is not boolean. If x is False then result is x otherwise result is y.
  •  x or y: If x and y are not boolean here,then result is also not boolean. If x is False result is y otherwise result is x. eg 0 or 5 result is 5

Relational Operators

Relational operators always gives result in True or False.
The relational operators are as follows:
<, >, <=, >=, ==, !=
Relational operators can be used to compare strings also.
Every non zero integer is treated as True and only 0 is treated as False.
x=9
print(bool(x))  # True

"AB" >"CD" #False
<, >,<=,>= will not work on complex numbers. They will give error if applied.
True+5=6 # No conversion is required here
In python 5>4>3 gives True
5==5.0 gives True int and float can be compared.
5=="5" False

ord() method :
This method is used to calculate the unicode.
eg. print(ord('a')) #97 

Arithmetic operators

The table for common arithmetic operators is given below:
Operator
Expression
Keyword
**4**2=16exponent
/4/3=1.3333float
//4/3=1floor value division
*4*2=8Multiplication
%4%3=1Remainder(Modulus)

There are some points to be noted here
  • Modulus operator also works on negative numbers. The sign of the denominator is always the sign of the result
  • -4%-3=-1 result sign is same as denominator sign, and perform normal modulus operation
  • 4%-3=-2  result always negative and go to one upper multiple of 3 means 6 here subtract 6-4
  • -4%3=2   result always positive and go to one upper multiple of 3 means 6 here subtract 6-4
  • 2.5%2=0.5
  • 2%3.0=2.0
  • "ab"*3=ababab
  • The precedence order is as:
           **
          / // * %
          +  -

Operators Introduction

Operators are special symbol in python language that can be used to carry out arithmetic and logical computation. Operators always required one more operands to perform their operation.
In python language post and pre increment or decrement  operators are not present.
No conditional operator here exist (?:) but we can do similar jobs using if else block also.

The operators that are present in python are as follows:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operator
  • Identity Operator
  • Membership Operator

Handling Number Systems in Python3

Decimal: Decimal is that number system in which base is 10.  (0 to 9)
Binary: In binary system the base is 2. (0 and  1 only)
Octal: The base for octal system is 8. (0 to 7)
Hexadecimal: Hexadecimal is that format in which base is 16. (0 to 9, A to F)

By default in Python decimal number is supported.
for binary we can write:
x=0b101 or
x=0B101
for octal
x=0O341
for hexadecimal
x=0x4A
Can you guess the output of the following script??
x=45
print(x) #45
x=0b101
print(x)  #5
Both print statement will print the decimal value first one is 45 and another one is 5, then how can we able to print binary values.
The script can be as
x=0b101
print(bin(x)) #0b101
0b can be removed by using slicing which we study further.
Similarly for hexadecimal and octal we can write respectively as:
hex(x)
oct(x)

Slicing:
x=8
print(bin(x)[2::])
Slicing operator works on  those data types where indexing is supported.
example:
x="mayank"
print(x[0:2:]) #ma
Here last index is not included.




12/20/2018

Data Types in Python

Data types define the kind or type of the data.
No declaration is required for data type in python because it is dynamic typed language.
Python has 14 built in data types. These are given below:
int, float, complex, bool, str, bytes, bytearray, range, list, tuple, set, frozenset, dict, Nonetype

Numbers: There are 3 built in data types for numbers
1. Integers (int)
2. Floating Point Numbers (float)
3. Complex Numbers (complex)

Strings(str):
Strings are denoted using quotes (single, double or even triple)
a='Mayank'
x="MAYANK"
y="""Mayank"""

These all are treated as string in python language.

Boolean:
The boolean variable can have either True or False.
x=True
y=False
print(type(x)) #bool


The datatypes which falls under the category of sequential data types are as:
str, bytes, bytearray, range, list, tuple



12/18/2018

Variables,Keywords in Python

Variables:
Variables are reserved memory locations to store data or values. When we create a variable, we are actually reserving space in the memory.
As suggested by the name, the values in the variables can be changed at any time by the programmer.

Variables Declaration:
In Python you can directly use variables without declaration. No datatype is needed here, means
x=8 (here x is of int type)
x=9.7 (here x is of float type)
x="hacking" (here x is of string type)
That's why Python is called dynamically typed language.
This can be demonstrated using a simple python script as show below:
x=5
print(type(x)) #int
x=5.0
print(type(x))  #float

Note: In Python language, we actually create reference variable. This can be understood as, suppose we write
x=5
print(id(x))

then we are creating reference variable x which is pointing to the address in which value is 5.

Variable Naming Rules:
A name of a variable can be a combination of alphabets, digits, and  underscores.
A name cannot be start with a digit.
Variable names are case sensitive.
Keywords cannot be used as variable name.
Variable names can be start with underscore also.

Object: 
Object is something which is capable of storing set of values. Every variable in python is object. Object can be defined as an instance of class.

Keywords in Python3: 
Predefined words or reserved words are called keywords. As their function is already defined they cannot be used as variable names.
Python has 33 keywords.
Script: How to see all keywords in Python?
import keyword  #module
print(keyword.kwlist)  

Note: There are only three keywords in python which starts from capital letters. These are as:
True, False, None


 


Comments and First program in Python

So we have done with installing python IDE. Now we are going to discuss about comments.
Comments are that code in our python program that is ignored by the python interpreter. Comments are very useful in understanding the program very easily. In python we have several ways in which we can comment the code.

1.Single line comment: Single line comment can be made by putting # symbol. For example
#This script is written by me

2.Multi line Comments: Multi line comment can be given in two ways
''' this is multi
line comment'''

"""this is also

multi 
line comment"""


First Program in Python
We want to print only "hello world" in our first Python program. The script is very simple you need not to include anything in your program.
print("hello world")
Output: hello world  

It is just a single line code. Now you can imagine how easy is to learn Python language and believe me if python is your first language you will love it and grab it very easily without the prior knowledge of any programming language.


 

12/16/2018

Difference of Python2 and Python3

Python2
Python3
1. Division operator works like C language.1. Division Operator works like floating division.
2. Here range() and xrange() function both are available.2. Here only range() function is available which is similar to xrange() function.
3. raw.input() and input() both functions are available.3. Only input() function is available which is equivalent to raw.input() method in Python2
4. Implicit type is ASCII4. Implicit type is UNICODE.
5. We can print hello world in Python2 as print "hello world" 5. We can print hello world as print("hello world")
Note** You don't have to remember these points at all, this is just for basic difference between Python2 and Python3. As now, the support for Python2 has been discontinued, so we can say that Python3 is now the future.
12/15/2018

Introduction to Python

Python introduction:
Father of Python was Guido van Rossum.
Python is a high level, interpreted, scripting language. It can be used in most of the fields of computer science and technology. The demand of python is increasing day by day due to its simplicity and its interesting features. The common features of python language are given below.
  • It is very simple and easy to learn.
  • Python is platform independent language.
  • Python is case sensitive language.
  • It is dynamically typed language.
  • It is object oriented language.
  • Python has rich library for IOT(Internet of Things), Networking, Scientific Computing, Web scrapping, hacking etc.
  • It is scripting, interpreted language.
  • Python is favourite language for hackers and penetration testers as writing script in it is very simple and straight forward.  
  • Python has great libraries for handling database, graphical user interface, text processing, image processing etc.
Why name is Python??
Most people think that the name of python is taken from a breed of snake, but it is not true. Actually creator of Python language(Guido van Rossum) was great fan of a circus show named "Monty Python's Flying Circus". So he named it Python.


Versions of Python:
The version history of python is given below.
First version: 0.9.0 (1991)
Current version: 3.8.2 (2020)


Applications of Python:
Most of the popular applications like Youtube, Quora, Bit torrent, Google, Firefox are developed in Python.
More than 1 Million projects on github are created using python.
If we learn python then we can continue our career in the following fields
  • GUI applications
  • Web applications
  • Data Science
  • Big Data analysis
  • Artificial intelligence or Machine learning
  • Internet of Things
  • Ethical hacking
  • Penetration testing 
Installation of Python:
For running python scripts or programs we need to download python interpreter. You can download python interpreter from official website and installation process is very simple and easy.
https://www.python.org/downloads/