SPACE
for next slideShift
+ SPACE
for previous slideSince Linux and Darwin are based on the Unix operating system, they are commonly regarded as *nix.
A standard that assigns a number to each character in English to enable information exchange between programs and across the network.
Examples:
Like ASCII but enables more characters and languages.
Just like a house address there is an address for each byte in RAM. For a 4 GB RAM the highest address would be (4 ⨉ 109 - 1) i.e. 399999999 as the lowest address starts at 0.
A program uses these addresses internally for referencing a specific memory location which may span across multiple bytes.
The CPU only understands basic instructions like:
Variables are human readable names of certain memory locations that contains the required value.
Another perspective: We can use latitude and longitude to represent a location but we mostly use human readable names instead like New Delhi, London, etc. The value is the infrastructure, the people and the things present at the location.
These are special variables in an operating system which influence a program’s behaviour.
The most common example is the PATH
variable which needs to change after
installing a program like Python.
JAVA_HOME
is also one of the requirements when doing something related to
Java.
A program that needs to be compiled before execution is categorized as a compiled program.
There are special programs called compilers which turn the program into a file called executable which is made of 0s and 1s.
These executables need to be compiled for different platforms separately and
may also depend on dll
/ so
files to run properly.
Examples: firefox
, anaconda
, vlc
, code
, steam
, emacs
, etc.
Program is interpreted line by line in real-time by a special program called an interpreter which needs to be present on host system.
C:\
or Z:\
on Windows/
on *nix systems/home/user/.bashrc
, C:\Users\user\.bashrc
/
or C:\
or Z:\
user/.bashrc
, .bashrc
, home/user/.bashrc
REPL - Read Evaluate Print Loop
You can install Python using one of the following ways:
Way | UI | Extension | Feedback | Minimal |
---|---|---|---|---|
Python REPL | ❌ | ❌ | ✅ | ✅ |
Ipython REPL | ✅ | ❌ | ✅ | ✅ |
Script | ❌ | ✅ .py |
❌ | ✅ |
Notebook | ✅ | ✅ .ipynb |
✅ | ❌ |
Launch a terminal and type:
python
OR
python3
Now you can type code one line at a time and Python will execute it. To quit
the REPL type exit()
and press enter
.
ipython
REPL
ipython
is the same Python under the hood but with lots of useful features
like auto indentation and syntax highlighting. To install it type the
following in a terminal:
python -m pip install ipython
Now run it by typing python -m ipython
.
A jupyter notebook is file having .ipynb
extension and requires a separate
environment to execute it. It also uses the the same Python under the hood to
execute code. The best part about it is that documentation is a first class
citizen with full markdown support and partial latex support.
You can find out how to enable jupyter notebook support from your text editor’s documentation or extension/plugin list.
Install it using the following command:
python -m pip install jupyter
To start the server type python -m jupyter notebook
in the terminal. This
will print an URL which you can open in a web browser and start using it.
pandas
?
Because pandas
feels like a different syntax and does lot of black magic
under the hood which is hard to explain when you are just starting with
Python.
For example, you can write something like df[['date', 'language', 'column3']]
in pandas
which is easy to use but hard to reason about because you wont find
any standard Python syntax that relates to this type of code. This sure is
doable in normal Python but requires knowledge of classes and dunder methods.
Before moving to pandas
I would suggest you to build a strong foundation in
Python fundamentals to prevent confusion, lack of control and helplessness.
Values are of different types which defines the rules of what you can do with it. Some examples are:
2
an integer"asd"
a stringb"xyz"
a sequence of bytesprint
a function that refers to a block of code"2" + 3
gives error"2" * 3
gives "222"
"a,b".split(",")
gives ["a", "b"]
"a+b".split(+)
gives errorIn some cases you need to check and see what works while in other cases you need to read the documentation to understand the behaviour and compatibility with other datatypes.
Variable is a human readable name that refers to a value
To set a value to a variable write the name on the LHS and the value or expression on RHS
Example:
var_name01 = 2 name = "Ram" * var_name01
Lets write a program to convert 37℃ to farenheit
\[\frac{C}{5} = \frac{F - 32}{9}\]
celsius = 37
To convert celsius to farenheit we need to transform the formula in such a
way that F
is on LHS and the rest is on RHS.
\[F = \frac{9C}{5} + 32\]
F = (9 * C) / 5 + 32
It follows the BODMAS rule.
celsius = 37 farenheit = (9 * celsius) / 5 + 32
But this wont show anything on the screen. To show the result we need to use
the print
function.
celsius = 37 farenheit = (9 * celsius) / 5 + 32 print("Celsius:", celsius) print("Farenheit:", farenheit)
Output:
Celsius: 37 Farenheit: 98.6
A line of code that can be executed in Python is called a statement.
Python will ignore anything written after hash (#
) symbol. These are called
comments and used mainly to document the code in a human readable language.
Example:
# This is a comment x = 1 # I am invisible to Python
A statement that returns / gives a result after running / execution is called an expression.
2
is an integer which returns 2
"Hi there"
is a string of characters which returns "Hi there"
3 + 2
is an arithmetic expression which returns 5
3 + 2 < 5
is a logical expression which returns False
{"a": 1}.get("a")
is a function call applied to a dictionary which returns 1
print
?
print
is a function that prints (shows) output on the console / terminal /
screen and returns None
i.e. if you were to capture it in a variable then the
value stored in the variable would be None
.
For example,
x = print("Hi there") print(x)
Outputs
Hi there None
Indentation is very important in Python. If indentation is incorrect your code wont run. It follows the following format:
special statement: code block
Make sure you give a colon (:
) at the end of a special statement and each
statement in the code block should be prefixed by one or more spaces.
Statements starting with the following keywords can be considered special statements:
if elif else
for
and while
with
def
and class
try except finally
match case
Note: Special statement is not a standard term. It is just used to explain the concept of indentation.
A code block consists of one or more normal/special statements.
Example 1:
x = 1
Example 2:
print("Hello world")
Example 3:
2 if True else "Hi"
x = 1 print(x) x -= 1
x = "yes" if "y" in x: b = "y" * len(x) if "e" in x: b += "es" else: b = "n" + "o" * len(x) print(b)
Output:
yyyes
if elif else
- Invalid example 1else: print("hi")
else
and elif
cannot be used in isolation and gives a syntax error when
executed.
if elif else
- Invalid example 2else: print("Hi") if 2 > 1: print("Hello")
else
should be the last one in a group of if elif else
.
if elif else
- Invalid example 3if: print("Hi")
A condition is required when writing an if
statement.
if elif else
- Example 1if 2 < 3: print("Hello")
if
in isolation can be used. If the condition is false then the block wont be
executed / run.
if elif else
- Example 2if 3 < 3: print("Hi") elif 2 < 3: print("Hello")
Here elif
condition is checked when the if
condition is false. When the elif
condition is true then the corresponding block is executed. If both
conditions are false none of them are executed.
if elif else
- Example 3if 3 < 3: print("Hi") elif 2 == 3: print("Hello") else: print("There")
Here the else
block is executed only when all the conditions in if
and elif
are false. If any of the above conditions are true then the else
block is not
run.
if elif else
- Example 4x = 1 if x % 2 == 0: print("Even") elif x < 0: print("Negative") elif x - int(x) == 0: print("Integer") else: print("Odd, Positive, Fraction")
We can write multiple elif
but only one if
and one else
.
if elif else
- Example 5if 2 == 2: print("Hi") if 3 < 2: print("Hello") else: print("yo")
Here we have two set of independent if elif else
blocks.
if elif else
- Rulesif
and elif
blocks are executed only when the condition is true.elif
and else
cannot be used without if
.else
block is executed when all the conditions of if
and elif
are false.if elif else
are executed whichever comes first.if elif else
- Example 6if 1 == 1: print("Hi") elif 2 == 2: print("Hello")
Output:
Hi
if elif else
- Example 7if 1 == 1: print("Hi") if 2 == 2: print("Hello")
Output:
Hi Hello
while
x = 1 while x < 5: print(x) x = x + 1
for
Used for iterating over a list of elements.
Example 1:
for i in [2, 1, 11]: print(i)
Example 2:
for i in range(2, 11, 2): print(i)
with
Used for automatic resource allocation and deallocation such as connecting to network, opening a file, etc.
with open("/path/to/some/file.txt") as f: print(f.read())
try except finally
try: print(some_unknown_var) except NameError as error: print("An error occured") finally: print("I will always be run")
Just like we have different file types for different purposes, we have different datatypes for different purposes.
Datatype | Python name | Example(s) | Comment |
---|---|---|---|
Boolean | bool |
True, False | |
Integer | int |
-3002, 0, 101 | |
Floating point | float |
-30.2, 0, 0.39 | Real numbers |
Complex | complex |
3 + 2j | j is √-1 |
String | str |
’abc’, “नमस्ते” |
bool
)
Boolean values contain either 0 (False
) or 1 (True
)
bool
- The or
operator
The or
operator returns False
only when both values are False
. For all other
cases it returns True
.
False or False = False False or True = True True or False = True True or True = True
bool
- The and
operator
The and
operator returns True
only when both values are True
. For all other
cases it returns False
.
False and False = False False and True = False True and False = False True and True = True
bool
- Writing conditions (part 1)2 == 2 and 3 < 2
True and False
False
bool
- Writing conditions (part 2)a, b = 2, 3
a < b - 2 or a > 5
2 < 3 - 2 or 2 > 5
2 < 1 or False
False or False
False
bool
- Writing if
elif
else
statementstemp = 40 if temp > 45: print("Too hot to touch") elif temp < 20: print("Too cold to touch")
The above elif
could have been just if
because the conditions are mutually
exclusive i.e. temp
can’t have a value that is both greater than 45 and
lesser than 20. But it is better to use elif
if you want to be extra careful
to prevent printing both the messages.
str
)
Any data which contains text is considered a string. The text should be
written between either one of '
, "
, '''
, """
.
str
- Different ways'Single line string'
"Single line string"
'''Multi line string'''
"""Multi line string"""
str
- Example usage"ab" + "2" = 'ab2' "ab" * 2 = 'abab' "ab".isupper() = False "ABhI".lower() = 'abhi' "bc" in "a bcd" = True
str
- Converting other datatypes to stringx = str(1 + 2) + "rd" print(x)
3rd
str
- Injecting values in a string:a, b = 5, 4 x = "%s + %s = %s" % (a, b, a + b) y = f"{a} + {b} = {a + b}" print(x) print(y)
5 + 4 = 9 5 + 4 = 9
Simple datatypes in isolation can’t solve all types of problems. Because of
this we have datatypes like list
, set
and dict
which are used to store a
collection of values instead of single values.
To store data of arbitrary datatypes sequentially you can use the list
datatype.
Example: ["abc", 1, [-0.3, 'a'], 52]
To store data of arbitrary hashable datatypes you can use the set
datatype.
Example: {"abc", 1, (2,3)}
To store d
str
)'abcd'
"I'm"
"""multi line string"""
''' another multi line string '''
Text Type | str |
Sequence Types | list , tuple , range |
Numeric Types | int , float , complex |
Mapping Type | dict |
Set Types | set , frozenset |
Boolean Type | bool |
Binary Types | bytes , bytearray , memoryview |
None Type | NoneType |
A function is a subprogram that is used to perform a predefined operation and return a value. It is mainly used to reduce development time by reducing lines of code and modularizing the code.
Basically, it is like a mathematical function but with much more features.
A function definition is a subprogram (block of code) that is registered to a function name.
def
return
statementsdef function_name(parameter1, parameter2 ...): first line second line ... last line
After a function is defined, it can be called to perform the action it was defined for and return (give) a value.
Note: Returning value from a function is different from printing the value on the screen.
Just like 3 + 2
returns 5
, a function after execution reduces to a single
value.
For example, sin(90°)
is a function call that returns 1
.
Functions that return nothing still return the value None
in Python.
sin(90°)
sin
90°
1
Python equivalent:
import math # Importing a module / library math.sin(math.pi / 2) # Function call # 90° = 𝛑/2
It was a pre-defined function. We just used it.
This is a user-defined function to calculate celsius to farenheit:
def to_farenheit(celsius): farenheit = (9 * celsius) / 5 + 32 return farenheit
Then we can use it:
to_farenheit(25) # Convert 25℃ to ℉
\[a = \frac {v - u} {t}\]
a
(acceleration)v
, u
, t
Python equivalent:
def acceleration(v, u, t):# Function definition return (v - u) / t acceleration(10, 5, 2) # Function call
\[\sum_{i=1}^{10} i\]
i = 0
, 10
, i
55
Python equivalent:
def summation(s, e, f): return sum(f(i) for i in range(s, e+1)) summation(1, 10, lambda i: i)
input
- Take text input from the keyboard
The input
function captures input typed from a keyboard into a string.
\[ Keyboard \xrightarrow{input} \fbox{input()} \xrightarrow{return} String \]
Since it returns a string we can store it in a variable and use it in further computations.
\[Keyboard \xrightarrow[3]{input} \fbox{Program} \xrightarrow[3rd]{output} Screen\]
Lets assume you want to do '2' + 3
which looks pretty straigtforward and
should return 5
.
But computers are dumb, they do nothing more and nothing less. It sees them
as incompatible datatypes and thus fails to add them using the +
operator.
Basically its based on the assumption that strings can contain characters
other than numbers so it doesn’t make sense to add them directly. For
example, someone could have written 'ab' + 3
which is not at all possible.
So, here Python doesn’t want to spend computing power to check if the string is a number and automatically adding itself.
import math
- Import a modulemath.pi
, math.cos(0)
, etc.math.sin(math.pi / 2)
- Calling functionsimport math
first