First Program in Python
You can Start using String within Quotes like below :-
PHP Code:
krokite@worldofhacker~$ python>>> print("Hello World of Hacker")Hello World of Hacker
- Open Editor of your Choice like (VIM [Linux], Notepad, Notepad++[Windows], etc.,)
- Start Writing below code and save them as "hello_world.py"
PHP Code:
#!/usr/bin/pythondef main():
print("Hello World of Hackers");
if __name__ == "__main__":
main()
After Saving the File and When you will run them like Below, Your Output will be same as mine here - Don't bother about mine "krokite@worldofhacker:~$" part, if you are using windows machine you will see something like "C:\>" etc.,
PHP Code:
krokite@worldofhacker:~$ cd python/First_Tutorial/krokite@worldofhacker:~/python/First_Tutorial$ ls
hello_world.py
krokite@worldofhacker:~/python/First_Tutorial$ python hello_world.py
Hello World of Hackers
krokite@worldofhacker:~/python/First_Tutorial$
Well, Congratulation, you made your first program, even though you could not have understood anything above.
See, "def main():" is way of defining function, we are defining main() function and calling it below from __name__, just like main() in C and C++.
and we used print function to print the value in command prompt.
Understanding String in Python
In Python Valid String can be anything like :-
PHP Code:
string_1 = 'abce'
PHP Code:
string_2 = "xyz"
PHP Code:
string_3 = """A
multi-line
string.
"""
So, All above Codes are categorised as python, See how can you make them in your program :-
PHP Code:
#!/usr/bin/pythondef main():
print('Hi');
print("I am KroKite");
print("""
This is Introduction to Python Tutorial for Hackers Part 2
We are not covering anything more than String, Comments and
Operators.
""")
if __name__ == "__main__":
main()
Save them as "strings.py" and run them like below :-
PHP Code:
krokite@worldofhacker:~/python/First_Tutorial$ python strings.py
Hi
I am KroKite
This is Introduction to Python Tutorial for Hackers Part 2
We are not covering anything more than String, Comments and
Operators.
krokite@worldofhacker:~/python/First_Tutorial$
Going inside More in the Intepreter Version of Python
PHP Code:
krokite@worldofhacker:~$ python
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> krokite= "world " + "of" + " hacker ">>> krokite'world of hacker'>>>
Strings can be concatenated (glued together) with the + operator, and repeated with *:
PHP Code:
>>> krokite *5'world of hackerworld of hackerworld of hackerworld of hackerworld of hacker'>>> krokite = "World " +"of"+" hacker ">>> krokite'World of hacker '>>> krokite*5'World of hacker World of hacker World of hacker World of hacker World of hacker '>>>
Two string literals next to each other are automatically concatenated;
PHP Code:
>>> 'str' 'ing' # <- br="" his="" is="" nbsp="" ok="">->'string'>>> 'str'.strip() + 'ing' # <- br="" his="" is="" nbsp="" ok="">->'string'>>> 'str'.strip() 'ing' # <- br="" his="" invalid="" is="" nbsp=""> ->File "" , line 1, in ?
'str'.strip() 'ing'
^SyntaxError: invalid syntax
Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon.
We will Learn Below code better when we will learn about Dictionary, tuples and list of python.
PHP Code:
>>> krokite[4]'d'>>>
PHP Code:
>>> krokite[0:4]'Worl'>>>
PHP Code:
>>> krokite[3:13]'ld of hack'>>>
Note: Index Starts with 0
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
PHP Code:
>>> krokite[ :2]'Wo' # This is First Two Characters.>>> krokite [5: ]' of hacker ' # This is Everything Except 5 Characters.
Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error:
PHP Code:
>>> krokite[0] = 'x'Traceback (most recent call last):
File "" , line 1, in <module>TypeError: 'str' object does not support item assignment>>> krokite[ :1] = "Boom"Traceback (most recent call last):
File "" , line 1, in <module>TypeError: 'str' object does not support item assignment
However, creating a new string with the combined content is easy and efficient:
PHP Code:
>>> krokite = 'world of hacker '>>> 'KroKite@' + krokite'KroKite@World of hacker '>>>
PHP Code:
>>> krokite[:3] + krokite[3:]'World of hacker '>>> krokite[:3] + krokite[5:]'Wor of hacker '>>>
Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.
PHP Code:
>>> krokite[1:100]'orld of hacker '>>>
PHP Code:
>>> krokite[20:]''>>>
If you ask more or less the values are always blank and represented as '.
PHP Code:
>>> krokite[5:3]''>>> krokite[5:5]''>>> krokite[2:5]'rld'>>>
Indices may be negative numbers, to start counting from the right. For example:
PHP Code:
>>> krokite[-3]'e' # The last but only 3rd Character>>> krokite[-3:]'er ' # The last 3 characters>>> krokite[:-3]'World of hack' #Everything Except last 3 character>>>
The built-in function len() returns the length of a string:
PHP Code:
>>> s = 'supercalifragilisticexpialidocious'>>> len(s)34
Understanding Comment System in Python
Generally, We use Two Signs for Comment System in Python.
1. # [Hash] => Single line Comment.
2. ''' [Three Single Quote] and Ending with Same Three single line quote. => Multi-line comment.
[/php]
PHP Code:
#!/usr/bin/pythondef main():
print('Hi');
# I am KroKite, and this is single line comment.
'''
This is Introduction to Python Tutorial for Hackers Part 2
This is Multi-line comment, :)
And comment is basically a note or reminder for developers and is
not executed by programs :)
'''if __name__ == "__main__":
main()
Now save them with name "comment.py" and run them like below :-
PHP Code:
krokite@worldofhacker:~/python/First_Tutorial$ python comment.py
Hi
krokite@worldofhacker:~/python/First_Tutorial$
You see , Nothing was printed which was commented, So Basically, Comment is kind of reminder to developers about the code or anything he wish to add, and dont wants code to get executed by programs.
Understanding Numbers in Python
PHP Code:
>>> 2+2
4>>> # This is a comment... 2+2
4>>> 2+2 # and a comment on the same line as code4>>> (50-5*6)/4
5>>> # Integer division returns the floor:... 7/3
2>>> 7/-3-3
The equal sign ('=') is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
PHP Code:
>>> width = 20>>> height = 5*9>>> width * height
900
A value can be assigned to several variables simultaneously:
PHP Code:
>>> x = y = z = 0 # Zero x, y and z>>> x
0>>> y
0>>> z
0
Variables must be “defined” (assigned a value) before they can be used, or an error will occur:-
PHP Code:
>>> n # try to access an undefined variableTraceback (most recent call last):
File "" , line 1, in <module>NameError: name 'n' is not defined
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
PHP Code:
>>> 3 * 3.75 / 1.5
7.5>>> 7.0 / 2
3.5
Complex numbers are also supported; imaginary numbers are written with a suffix of j or J. Complex numbers with a nonzero real component are written as (real+imagj), or can be created with the complex(real, imag) function.
PHP Code:
>>> 1j * 1J(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3(3+3j)
>>> (3+1j)*3(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
Complex numbers are always represented as two floating point numbers, the real and imaginary part. To extract these parts from a complex number z, use z.real and z.imag.
PHP Code:
>>> a=1.5+0.5j>>> a.real
1.5>>> a.imag
0.5
The conversion functions to floating point and integer (float(), int() and long()) don’t work for complex numbers — there is no one correct way to convert a complex number to a real number. Use abs(z) to get its magnitude (as a float) or z.real to get its real part.
PHP Code:
>>> a=3.0+4.0j>>> float(a)Traceback (most recent call last):
File "" , line 1, in ?TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a) # sqrt(a.real**2 + a.imag**2)
5.0
In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
PHP Code:
>>> tax = 12.5 / 100>>> price = 100.50>>> price * tax
12.5625>>> price + _
113.0625>>> round(_, 2)113.06