python by ravi rajput hcon groups
TRANSCRIPT
Python Basics
By:- Ravi.Rajput
Python Basics by Ravi Rajput is licensed under aCreative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Acknowledgement
• This presentation dedicated to my mom , dad and whole family who always supported and loved me the way I am.
• I would like to thank Ashish Mistry who give me platform for sharing my knowledge
• Very much thankful to Lord Swami-Narayan
About Me• I am security researcher.• I have interest in Software
Reversing and Python Programming.• I am a noob and I learn all the
things because a noob can teach well .
Why Python?• Python is derived from many other languages,
including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.
• Easy to Learn.
• A broad standard library
• Interactive Mode
• provides interfaces to all major commercial databases.
Basic Syntax
>>>Print “Hello World..!!!”
• input
>>>raw_input(“Which scripting language is this ??”)
• comments
#This is the comment.
• Type
>>>type(port)
Variable Types
• Standard Data types• Numbers• String• List• Tuple• Dictionary
For Example:• Port = 21 # An integer
• percentage = 99.60 # A floating point
• PortName = “FTP“ # A string print counter print miles print name
Decision Making
• if>>>var=100>>If(var == 100):
Print “Inside If”
• Colon after if and indentation is compulsory.
• In if .. Else statement , If the condition is false then else part is executed.
• Nested if
• You can use if..else another if.
Loops Contd.
>>count = 0 >>while (count < 9):
print 'The count is:', count count = count + 1
• While Loop
• Else Used with While loop
>>>count = 0>>>while count < 5:
print count, " is less than 5" count = count + 1
else: print count, " is not less than 5"
• For Loop
• Output:0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5 5 is not less than 5
>>>for letter in 'Python': # First Example print 'Current Letter :', letter
>>>fruits = ['banana', 'apple', 'mango'] >>>for fruit in fruits: # Second Example
print 'Current fruit :', fruit
Loops Contd.
Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Current fruit : banana Current fruit : apple Current fruit : mango
• Output
Loops Contd.
• The break/Continue statement in Python terminates/continue the current loop and resumes execution at the next statement,
just like the traditional break found in C.
Strings>>>var1 = 'Hello World!' >>>var2 = "Python Programming“>>> print "var1[0]: ", var1[0] >>>print "var2[1:5]: ", var2[1:5]
• Output
var1[0]: H var2[1:5]: ytho
>>>var1 = 'Hello World!' >>>print "Updated String :- ", var1[:6] + 'Python'
• Output
Updated String :- Hello Python
Lists
>>>portlist=[]>>>portlist.append(21) #Appending>>>portlist.append(443)>>>portlist.append(25)>>>portlist.append(80)>>>portlist.sort() #sorting>>>print portlist #printing[21,25,80,443]>>>portlist.remove(25)#removing>>>count=len(portlist) #counting length>>>print count2>>>pos=portlist.index(21) #Indexing0
• The list in python is like an array of any data type.• There are several methods like inserting,
removing, popping, indexing, counting, sorting and reversing and it is mutable.
Tuples
• A tuple is a sequence of immutable Python objects.• The only difference between tuple and list is that can't be
changed• i.e., tuples are immutable and tuples use parentheses and
lists use square brackets.
>>>tup1 = ('phython', ‘reversing', 2013, 2014); >>>tup2 = (1, 2, 3, 4, 5 ); >>>tup3 = "a", "b", "c", "d";
• Even if tuple have single value still comma ,must be included
>>>tup=(21,)
>>>print "tup1[0]: ", tup1[0] Tup1[0]:python
>>>print "tup2[1:3]: ", tup2[1:3]Tup2[1:3]:[2,3,4]
Dictionary
• The python dictionary data structure provides a hash table
that can store any number of python objects and it is mutable .• The dictionary consists of pairs of items that contain a
key and value.• Each key is separated by colon and items by comma.
>>>services={‘ftp’:21,’ssh’:22,’smtp’:25,’http’:80}>>>services.keys()[‘ftp’,’smtp’,’ssh’,’http’]>>>>services.items()[(‘ftp’.21), (’http’.80), (’smtp’.25), (’ssh’.22)]>>>services.has_key(‘ftp’)True>>>services[‘ftp’]21
FunctionsYou can define functions to provide the required functionality. Here are simple rules to define a function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Functions• Syntax:def function_name( parameters ):
"function_docstring" function_suite return [expression]
>>>def printinfo( arg1, *vartuple ): "This prints a variable passed arguments"
print “[+]Open_port is: “print arg1 for var in vartuple:
print var return; # Now you can call printinfo function
>>>printinfo( 21); >>>printinfo( 25,80,443);
• For example
Files>>>file=open(‘portscanner.py’,’r’)>>>file.read()>>>list=file.readlines()>>>for i in list:
if ‘port’ in i:print i
>>>file.close()>>>file.open(‘sample.txt’,’w’)>>>file.write(‘overwritten’)>>>file.close()>>>file.open(‘sample.txt’,’a’)>>>file.write(‘appended’)>>>file.close()
Exception>>>print 1337/0Traceback (most recent call last):
file “<stdin>”, line 1, in <module>ZeroDivisionError: Integer division or modulo by zero
try: You do your operations here;
except ExceptionE: If there is ExceptionE, then execute this block.
finally: this block is executed whether exception occur or
not.
try: file = open("testfile", "w") file.write("This is my test file for exception handling!!")
except: print "Error: can\'t find file or read data“
Finally:print ”Thank you for using this script”
Exception
Reference
1.Tutorial Points:http://www.tutorialspoint.com/python/index.htm2.Violent Python3.Learn Python: http://www.learnpython.org/