Comments in Python start with the hash character, #, and extend to the end of the physical line.
1
2
3 1 #I am a comment a =
a
1
3.1. Using Python as a Calculator
3.1.1. Numbers
Division
/
always returns afloat
.1
2
3
4
520 / 5
4.0
20 / 5 res =
type(res)
<class 'float'>floor division
//
return anint
and discard any fractional result1
2
3
4
520 // 5
4
20 // 5 res =
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 get9
, you can use(-3)**2
.
1
2
3
4
5
6
7
8
9
102 ** 10
1024
16 ** 0.5 res =
res
4.0
type(res)
<class 'float'>
>>> res = 2 ** 10
type(res)
<class 'int'>- Since
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
53 * 1.0 res =
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
101+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
11200
200
_
200
0 _ =
_
0
3+4
7
_
0Other avaiable type of numbers : Decimal,Fraction,complex numbers……
3.1.2. Strings
express strings : enclosed in
'
or"
,\
can be used to escape1
2
3
4'Hello World'
'Hello World'
"Hello World" _ ==
True1
2
3
4
5"\"Isn't it\"?" s =
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 anr
before the first quote:1
2
3
4
5'C:\some\name') # here \n means newline! print(
C:\some
ame
r'C:\some\name') # note the r before the quote print(
C:\some\name1
2
3
4'C:\some\name' s1 =
r'C:\some\name' s2 =
s1 == s2
Falsetwo or more literal string next to each other are automatically concatenated
1
2
3
4
5
6'P' 'y' 't' 'h' 'o' 'n'
'Python'
'Hello''World') print(
HelloWorld
's' 's' s =
sThis feature is particularly useful when you want to break long strings:
1
2
3
4'Put several strings within parentheses ' text = (
'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 line1
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'
'a' * 30 + '\xac\xeb' #this technique can be used to quickly produce a pwn payload 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"I am a string" s =
0] s[
'I'
type(s[0])
<class 'str'>Indices can be negative numbers, since
-0 = 0
, so negative indices start with -11
2
3
4
51] s[-
'g'
"I am a string\n" s =
1] s[-
'\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 tos
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.
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
842] # the word only has 6 characters word[
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
4:42] word[
'on'
42:] word[
''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
80] = 'J' word[
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
2:] = 'py' word[
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignmentIf you need a different string, you should create a new one:
1
2
3
4'J' + word[1:]
'Jython'
2] + 'py' word[:
'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,Worldsee 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
3123 , 'Hello' , 3.4] ls = [
ls
[123, 'Hello', 3.4]list can be indexed, just like string
1
2
3
4
5
6100:101] ls[
[]
100] ls[
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of rangeHowever, list slicing return a new list with selected items, differ with string slicing behavior
1
2
3
4
5
6
7
8
9'Python' s =
id(s)
4316265008
id(s[:])
4316265008
id(ls)
4317802688
id(ls[:])
4317798080Lists also support operations like concatenation
1
236, 49, 64, 81, 100] squares + [
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]Assignment to slices is also possible
1
2
3
4
5ls
['p', 'y', 't', 'h', 'o', 'n']
2:5] = [123] ls[
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
120 ,1 # the variables a and b simultaneously get the new values 0 and 1 a , b =
a
0
b
1
a , c = a+b , b
a
1
c
1
b
1an initial sub-sequence of the Fibonacci series
1 | a , b = 0 , 1 |