In this tutorial, we will write our first python program. Open your terminal / command prompt and type python. You will get something like this:
- Python 3.4.0 (default, Mar 22 2014, 22:59:56)
- [GCC 4.8.2] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>>
You will get this sign before every new command. In this tutorial series whenever you get this sign '>>>', skip it because you will get it already printed in your terminal.
It is a python interpreter which execute code without passing it to the file. We will start from here and also learn how to run program by saving in file because interpreter does not save the code.
Print hello world:
Now write a script to print hello world. Type this command:
- >>> print("hello world")
you will get output:
- >>> print("hello world")
- hello world
NOTE: In python 2, you can also write just print "hello world" for printing.
Try these commands and see result:
- >>> print(2)
- 2
- >>> print(2.4)
- 2.4
- >>> print("2.4")
- 2.4
- >>> print("2.4)
- File "<stdin>", line 1
- print("2.4)
- ^
- SyntaxError: EOL while scanning string literal
You will notice that line 3 and 5 both are giving same result 2.4 but in face these are different results. These are of different data types. First one is a float and second is a string. A float can be used in mathematics calculation but not string. We will read more about data types in next tutorial. Line 7 is giving an error because of wrong syntax. We have to use " in pair. If we want to print " then we have to escape it ( means we have to tell that we want to print "). We escape characters by writing a back slash before them.
- >>> print("\"2.4")
- "2.4
Assigning Variables:
Variable are places to put data. Look at these examples:
- >>> name = "harish"
- >>> print(name)
- harish
- >>> number = 2
- >>> print(number)
- 2
- >>> a=b=c=2
- >>> print(a)
- 2
- >>> print(b)
- 2
- >>> print(d)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- NameError: name 'd' is not defined
- >>> print(name)
- harish
- >>> name = "another name"
- >>> print(name)
- another name
It is just a preview we will study in detail in future tutorials.
Writing in a file
For writing python code in a file install rich text editors like notpad++ or sublime text. These both are free. Then write your code in a file and save it with an extension .py. If you are using linux or mac then make file executable by changing permissions. Open this file in terminal / command prompt by writing this command.
- python 'path to file'