More about Language
Watch on YouTube
There are two modes of running Python code: Interactive and Batch.
Interactive mode
Code is typed inside an interpreter session which gets evaluated immediately. This mode is suitable for small edits.
To start the interpreter, type python3
or python
on your terminal or command prompt.
python3 vs python
You have to figure out what to use while invoking the interpreter (python3 or python) based on the following:
Type python --version
on your command prompt.
The Interpreter looks like this when it starts:
If you see >>>
, this means that the interpreter has started and is waiting for your input. Type print("Hello Python!")
.
The interpreter evaluates each line which you type. The print
function is used to print content on the terminal. This is why you saw "Hello Python!" printed immediately on the next line.
Using the Interpreter
Start a new interpreter session and type 1 + 1
and hit enter. You will see the below output.
Here, 1 + 1
is called an expression and 2
is the output.
+
will calculate the sum of two numbers (1 and 1) and return the result.
-
will calculate the subtraction of 1 and 1 and return the result.
*
multiplies 10 with 10 and return the result.
**
is called the power operator, it returns 10 to the power of 2.
Operator Types
In the above expressions, +
, -
, *
are called operators, they operate on numbers (which are called operands).
In general, there are three types of operators:
Unary operators: Require one operand to operate on.
Binary operators: Require two operands to operate on. Most of the operators are binary (
-, +, *, **
etc)Ternary operators: Require three operators to operate on.
We won't be looking at unary and ternary operators now, we need to understand the language before jumping to ternary operators.
Batch Mode
The interpreter makes it difficult to write big programs. The best you can do in an interpreter is type lines of code. But, when you want to write programs and build applications, it is better to use the batch mode. In this, you create a text file who's name ends with .py
like file.py
and save it to your machine on some folder. We then run the file as python3 file.py
.
To execute the program, you'd need to use the cd
program to change folders.
For this book, create a folder. Open the terminal and type this.
Mac/Linux (Applications -> Terminal)
mkdir ~/antitextbookpy
You will save all the code files in this folder. You have to do this only once.cd ~/antitextbookpy
This will change the current working directory to~/antitextbookpy
, you have to do this every time you open a new terminal window or tab.
Windows: (open the Command Prompt)
mkdir antitextbookpy
cd antitextbookpy
You would need to create a file in this folder, save it by giving it a .py
extension then run it like python file.py
from the command line. If it says file not found, then you might have to check if you followed the above steps (of changing directories).
Links
Last updated