Table of Contents
Loops
Python Interpreters
a) Google Colab
Google Colab (short for Colaboratory) is a free, cloud-based Jupyter notebook environment
provided by Google. It allows you to:
Step 1: Access Google Colab
Sign in to Google Account: Ensure you are logged into your Google account
Open Google Drive.
Click on “New” > “More” > “Google Colaboratory” to create a new notebook.
Step 2: Understand the Notebook Interface
The Google Colab interface is similar to Jupyter Notebook. Key components include:
1. Cells:
Step 3: Create a New Notebook
1. Start a New Notebook:
2. Rename the Notebook:
Step 4: Write and Run Code
1. Add a Code Cell:
2. Write Python Code:
3. Run the Code:
b) Jupyter Notebooks:
Step 1: Download Anaconda
1. Visit the official Anaconda website.
2. Download the appropriate version for your operating system (Windows, macOS, or Linux).
Step 2: Install Anaconda
Step 3: Launch Jupyter Notebook via Anaconda Navigator
1. Open the Anaconda Navigator (search for it in your start menu or applications folder).
2. In Anaconda Navigator, you’ll see an option for Jupyter Notebook.
3. Click the Launch button next to Jupyter Notebook. It will open in your default web browser.
Python Data Types
Python has no command for declaring a variable for any datatype. A variable is created the
moment you first assign a value to it. Variable names are case-sensitive. Just like in other
languages, Python allows you to assign values to multiple variables in one line.
Sr# | Categories | Data Type | Example |
1 | Numeric Types | int | -2, -1, 0, 1, 2, 3, 4, 5, int(20) |
float | -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25,float(20.5) | ||
complex | 1j, complex(1j) | ||
2 | Text Sequence Type | str | ‘a’, ‘Hello!’, str(“Hello World”) |
3 | Boolean Type | bool | True, False, bool(5) |
4 | Sequence Types | list | [“apple”, “banana”, “cherry”], list((“apple”,”banana”, “cherry”)) |
tuple | (“apple”, “banana”, “cherry”), tuple((“apple”,”banana”, “cherry”)) | ||
range | range(6) | ||
5 | Mapping Type | dict | {“name” : “John”, “age” : 36},dict(name=”John”, age=36) |
6 | Set Types | set | {“apple”, “banana”, “cherry”}, set((“apple”,”banana”, “cherry”)) |
frozenset | frozenset({“apple”, “banana”, “cherry”}) | ||
7 | Binary Sequence Types | byte | b”Hello”, bytes(5) |
bytearray | bytearray(5) | ||
memoryview | memoryview(bytes(5)) |
The process of explicitly converting the value of one data type (int, str, float, etc.) to another data type
is called type casting. In Typecasting, loss of data may occur as we enforce the object to a specific data
type.
Typecasting Example:
Area is type cased here.
Operators
This section contains the details of different Python operators i.e., Math operators, comparison
operators and Boolean operators.
Arithmetic Operator
Arithmetic operator are used with numerical values to perform common mathematical operations. From Highest to Lowest precedence:
Operators | Operation | Example |
** | Exponent | 2 ** 3 = 8 |
% | Modulus/Remainder | 22 % 8 = 6 |
// | Integer Division | 22 // 8 = 2 |
/ | Division | 22 / 8 = 2.75 |
* | Multiplication | 3 * 3 = 9 |
– | Subtration | 5 – 2 = 3 |
+ | Addition | 2 + 2 = 4 |
Comparison Operator
Operator | Meaning |
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater Than |
<= | Less than or Equal to |
>= | Greater than or Equal to |
Boolean Operators
There are three Boolean operators: and, or, and not.
The AND Operator’s Truth Table:
Expression | Evaluates to |
True and True | True |
True and False | False |
False and True | False |
False and False | False |
The OR operator’s Truth Table:
Expression | Evaluates to |
True or True | True |
True or False | True |
False or True | True |
False or False | False |
The NOT Operator’s Truth Table:
Expression | Evaluates to |
not True False | False |
not False True | True |
If-else Conditions
Python supports conditional statements i.e.if,elif,else. Comparison operators and Boolean operators written in the previous section can be used in if-elif-else statements.
An “if statement” is written by using the if keyword.
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.
The elif keyword is Python’s way of saying “if the previous conditions were not true, then try this condition”.
The else keyword catches anything which isn’t caught by the preceding conditions.
if Statement Example:
name = Rabia
if name == ‘Rabia’:
print(‘Hi, Rabia.’)
if-else Statement Example
name = ‘Sajal’
if name == ‘Rabia’:
print(‘Hi, Rabia.’)
else:
print(‘Hello, stranger.’)
if-elif-else Statement Example:
name = ‘Sajal’
age = 22
if name == ‘Rabia’:
print(‘Hi, Rabia.’)
elif age < 12:
print(‘You are not Rabia, kiddo.’)
else:
print(‘You are neither Rabia nor a little kid.’)
Functions
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. In Python a function is defined using the def keyword. To call a function, use the function name followed by parenthesis:
Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument (input_string). When the function is called, we pass along a example string, which is used inside the function to print the resultant string:
Python has a set of built-in functions. Below is the list of built-in functions.
Function | Description |
abs() | Returns the absolute value of a number |
all() | Returns True if all items in an iterable object are true |
any() | Returns True if any item in an iterable object is true |
ascii() | Returns a readable version of an object. Replaces none-ASCII characters with escape character |
bin() | Returns the binary version of a number |
bool() | Returns the boolean value of the specified object |
bytearray() | Returns an array of bytes |
bytes() | Returns a bytes object |
callable() | Returns True if the specified object is callable, otherwise False |
chr() | Returns a character from the specified Unicode code. |
classmethod() | Converts a method into a class method |
compile() | Returns the specified source as an object, ready to be executed |
complex() | Returns a complex number |
delattr() | Deletes the specified attribute (property or method) from the specified object |
dict() | Returns a dictionary (Array) |
dir() | Returns a list of the specified object’s properties and methods |
divmod() | Returns the quotient and the remainder when argument1 is divided by argument2 |
enumerate() | Takes a collection (e.g. a tuple) and returns it as an enumerate object |
eval() | Evaluates and executes an expression |
exec() | Executes the specified code (or object) |
filter() | Use a filter function to exclude items in an iterable object |
float() | Returns a floating point number |
format() | Formats a specified value |
frozenset() | Returns a frozenset object |
getattr() | Returns the value of the specified attribute (property or method) |
globals() | Returns the current global symbol table as a dictionary |
hasattr() | Returns True if the specified object has the specified attribute (property/method) |
hash() | Returns the hash value of a specified object |
help() | Executes the built-in help system |
hex() | Converts a number into a hexadecimal value |
id() | Returns the id of an object |
input() | Allowing user input |
int() | Returns an integer number |
isinstance() | Returns True if a specified object is an instance of a specified object |
issubclass() | Returns True if a specified class is a subclass of a specified object |
iter() | Returns an iterator object |
len() | Returns the length of an object |
list() | Returns a list |
locals() | Returns an updated dictionary of the current local symbol table |
map() | Returns the specified iterator with the specified function applied to each item |
max() | Returns the largest item in an iterable |
memoryview() | Returns a memory view object |
min() | Returns the smallest item in an iterable |
next() | Returns the next item in an iterable |
object() | Returns a new object |
oct() | Converts a number into an octal |
open() | Opens a file and returns a file object |
ord() | Convert an integer representing the Unicode of the specified character |
pow() | Returns the value of x to the power of y |
print() | Prints to the standard output device |
property() | Gets, sets, deletes a property |
range() | Returns a sequence of numbers, starting from 0 and increments by 1 (by default) |
repr() | Returns a readable version of an object |
reversed() | Returns a reversed iterator |
round() | Rounds a numbers |
set() | Returns a new set object |
setattr() | Sets an attribute (property/method) of an object |
slice() | Returns a slice object |
sorted() | Returns a sorted list |
staticmethod() | Converts a method into a static method |
str() | Returns a string object |
sum() | Sums the items of an iterator |
super() | Returns an object that represents the parent class |
tuple() | Returns a tuple |
type() | Returns the type of an object |
vars() | Returns the __dict__ property of an object |
zip() | Returns an iterator, from two or more iterators |