An Informal Introduction to Python

Comments in Python start with the hash character, #, and extend to the end of the physical line.

1
2
3
>>> a = 1 #I am a comment
>>> a
1

3.1. Using Python as a Calculator

3.1.1. Numbers

  • Division / always returns a float.

    1
    2
    3
    4
    5
    >>> 20 / 5
    4.0
    >>> res = 20 / 5
    >>> type(res)
    <class 'float'>
  • floor division // return an int and discard any fractional result

    1
    2
    3
    4
    5
    >>> 20 // 5
    4
    >>> res = 20 // 5
    >>> type(res)
    <class 'int'>
  • ** can be used for calculating powers. Note that the type of the result depends.

    • Since ** has higher precedence than -, -3**2 will be interpreted as -(3**2) and thus result in -9. To avoid this and get 9, you can use (-3)**2.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    >>> 2 ** 10
    1024
    >>> res = 16 ** 0.5
    >>> res
    4.0
    >>> type(res)
    <class 'float'>
    >>> res = 2 ** 10
    >>> type(res)
    <class 'int'>
  • There is full support for floating point. Operators with mixed type operands convert the integer operand to floating point(works like C)

    1
    2
    3
    4
    5
    >>> res = 3 * 1.0
    >>> res
    3.0
    >>> type(res)
    <class 'float'>
  • In interactive mode, the last printed expression is assigned to the variable _

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    >>> 1+1
    2
    >>> _
    2
    >>> 1+3
    4
    >>> _
    4
    >>> type(_)
    <class 'int'>

    This variable should be read-only, using it as a variable name will create a new independent variable without this magic behavior(the original one is masked)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    >>> 200
    200
    >>> _
    200
    >>> _ = 0
    >>> _
    0
    >>> 3+4
    7
    >>> _
    0
  • Other avaiable type of numbers : Decimal,Fraction,complex numbers……

3.1.2. Strings

  • express strings : enclosed in ' or ",\ can be used to escape

    1
    2
    3
    4
    >>> 'Hello World'
    'Hello World'
    >>> _ == "Hello World"
    True
    1
    2
    3
    4
    5
    >>> s = "\"Isn't it\"?"
    >>> s
    '"Isn\'t it"?'
    >>> print(s)
    "Isn't it"?
  • If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:

    1
    2
    3
    4
    5
    >>> print('C:\some\name')  # here \n means newline!
    C:\some
    ame
    >>> print(r'C:\some\name') # note the r before the quote
    C:\some\name
    1
    2
    3
    4
    >>> s1 = 'C:\some\name'
    >>> s2 = r'C:\some\name'
    >>> s1 == s2
    False
  • two or more literal string next to each other are automatically concatenated

    1
    2
    3
    4
    5
    6
    >>> 'P' 'y' 't' 'h' 'o' 'n'
    'Python'
    >>> print('Hello''World')
    HelloWorld
    >>> s = 's' 's'
    >>> s

    This feature is particularly useful when you want to break long strings:

    1
    2
    3
    4
    >>> text = ('Put several strings within parentheses '
    ... 'to have them joined together.')
    >>> text
    'Put several strings within parentheses to have them joined together.'
  • String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    >>> print('''\
    ... Usage: thingy [OPTIONS]
    ... -h Display this usage message
    ... -H hostname Hostname to connect to
    ... '''
    ... )
    Usage: thingy [OPTIONS]
    -h Display this usage message
    -H hostname Hostname to connect to

    >>>
  • Strings can be concatenated by + and repeated by *

    1
    2
    3
    4
    5
    >>> 'em' + 'm' * 20
    'emmmmmmmmmmmmmmmmmmmmm'
    >>> payload = 'a' * 30 + '\xac\xeb' #this technique can be used to quickly produce a pwn payload
    >>> payload
    'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa‘'
  • String can be indexed. There is no separate character type; a character is simply a string of size one

    1
    2
    3
    4
    5
    >>> s = "I am a string"
    >>> s[0]
    'I'
    >>> type(s[0])
    <class 'str'>

    Indices can be negative numbers, since -0 = 0, so negative indices start with -1

    1
    2
    3
    4
    5
    >>> s[-1]
    'g'
    >>> s = "I am a string\n"
    >>> s[-1]
    '\n'
  • string can be sliced. While indexing is used to obtain individual characters, slicing allows you to obtain substring. Note that the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s

    • an omitted first index defaults to 0, an omitted second index defaults to the size of the string being sliced.

    • For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.

      remember

  • Attempting to use an index that is too large will result in an error, while slicing error can be handled gracefully

    1
    2
    3
    4
    5
    6
    7
    8
    >>> word[42]  # the word only has 6 characters
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    IndexError: string index out of range
    >>> word[4:42]
    'on'
    >>> word[42:]
    ''
  • Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed position in the string results in an error:

    1
    2
    3
    4
    5
    6
    7
    8
    >>> word[0] = 'J'
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'str' object does not support item assignment
    >>> word[2:] = 'py'
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'str' object does not support item assignment

    If you need a different string, you should create a new one:

    1
    2
    3
    4
    >>> 'J' + word[1:]
    'Jython'
    >>> word[:2] + 'py'
    'Pypy'

    While in C, string array can of course be changed.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    $ cat test.c
    #include <stdio.h>
    int main(){
    char s [] = "Hello World\n";
    printf("%s" ,s);
    s[5] = ',';
    printf("%s" ,s);
    return 0;
    }
    $ ./test
    Hello World
    Hello,World
  • see more about :Text Sequence Type — str,String Methods,Formatted string literals,Format String Syntaxprintf-style String Formatting…..

3.1.3. Lists

  • Lists might contain items of different types, but usually the items all have the same type.

    1
    2
    3
    >>> ls = [123 , 'Hello' , 3.4]
    >>> ls
    [123, 'Hello', 3.4]
  • list can be indexed, just like string

    1
    2
    3
    4
    5
    6
    >>> ls[100:101]
    []
    >>> ls[100]
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    IndexError: list index out of range
  • However, list slicing return a new list with selected items, differ with string slicing behavior

    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> s = 'Python'
    >>> id(s)
    4316265008
    >>> id(s[:])
    4316265008
    >>> id(ls)
    4317802688
    >>> id(ls[:])
    4317798080
  • Lists also support operations like concatenation

    1
    2
    >>> squares + [36, 49, 64, 81, 100]
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  • Assignment to slices is also possible

    1
    2
    3
    4
    5
    >>> ls
    ['p', 'y', 't', 'h', 'o', 'n']
    >>> ls[2:5] = [123]
    >>> ls
    ['p', 'y', 123, 'n']

    3.2. First Steps Towards Programming

  • multiple assignment:

    the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    >>> a , b = 0 ,1 # the variables a and b simultaneously get the new values 0 and 1
    >>> a
    0
    >>> b
    1
    >>> a , c = a+b , b
    >>> a
    1
    >>> c
    1
    >>> b
    1
  • an initial sub-sequence of the Fibonacci series

1
2
3
4
a , b = 0 , 1
while a < 10:
print(a)
a , b = b , a+b