❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

PYTHON-FUNDAMENTALS: CONSTANTS, VARIABLES AND DATA TYPES

26 July 2024 at 13:22

hi,everyody
I am kavin. I am going to write which I learnt I my class.

Variables

A variable in Python is a symbolic name that references or points to an object. Once a variable is assigned a value, it can be used to refer to that value throughout the program. Variables act as containers for storing data values.

How to name a variables

1.Start with a letter or an underscore.
2.Followed by letters, digits, or underscores.
3.Case-sensitive
4.Don't use Python Keywords

Examples of Valid Variable Names:
my_variable
variable1
_hidden_variable
userName

Assigning Values to Variables

In Python, the assignment operator = is used to assign values to variables. The syntax is straightforward: variable_name = value.
eg:

>>>name="kavin"
>>>print(name)

>>>kavin

Multiple Assignments

Python allows you to assign values to multiple variables in a single line. This can make your code more concise and readable.
eg:

>>>a,b,c=1,2,3
>>>print(a,b,c)

Variable Types

Python is a dynamically typed language, which means you don’t need to declare the type of a variable when assigning a value to it. The type is inferred at runtime based on the assigned value.
eg:

>>>my_variable="10"

>>>my_variable is an integer

You can check the type of a variable using the type() function.
eg:

>>>type("hello")

>>><class'str'>

Constants

In Python, constants are variables whose values are not meant to change. By convention, constants are typically written in all uppercase letters with underscores separating words.
eg:

>>>PI=22/7

Data Types

Data types are the different kinds of values that you can store and work with.

1.Numeric Types
*Integer (int): Whole numbers.

>>>value=23

*Float (float): Decimal numbers.

>>>value=23.5

*Complex (complex): Complex numbers.

>>>value=2+3j

2. Text Type

String (str): Sequence of characters.
eg:

>>>message="hello mac"

3. Boolean Type

Boolean (bool): Represents True or False.
eg:

>>>my_project=True

4. None Type

NoneType: Represents the absence of a value
eg:

>>>result=none

5. Sequence Types

*List (list): Ordered, mutable collection
eg:

>>>fruits=[apple,cherry,mango]

*Tuple (tuple): Ordered, immutable collection.
eg:

>>>coordinates(3,4)

*Range (range): Sequence of numbers.
eg:

>>>number=range(1,10)

6. Mapping Type

Dictionary (dict): Unordered, mutable collection of key-value pairs.
eg:

>>>person={"name":"kavin","url":"https://www.kavin.com"}

7.Set Type

Set (set): Unordered collection of unique elements.
Eg:

>>>unique_number={2,3,4}

Frozenset (frozenset): Immutable set.
eg:

>>>frozen_set=frozena([2,3,4])

Checking Data Type

Syntax: type(variable_name)
eg:

>>>name="kavin"
>>>print(type(name))

>>> <class'int'>

this is the things which i learnt in the class of Variables, Constants and Data Types.
Thank You

Python Variable – Is a Container or a Reference ?

11 July 2024 at 09:13

Unlike other programming languages, in Python, variable is not a container but just a reference or a name/label to the object.

Caution: This post deals with memory management, which might confuse you if you are a beginner. Read at your own risk.

Let’s dive deep into it,

To understand how python handles variable storage and references involves several key concepts,

Objects & References:

In python, everything is an object and variables are references to these objects. To check if an item is an object, we can use the isinstance() function.

This will give,

Now we can see that everything in python is an object.

Let’s try to prove,

When you create a variable (label), it holds a reference (a pointer) to the memory location where the actual object is stored.

To validate this we need to check the size of the objects and the address of the objects. We can use

  • id() function to check the address of the object
  • getsizeof() method from sys module to find the size of the object.

Let us take an example,


age = 26 

26 is the Numeric object which is stored in some memory address.

import sys

age = 26
print("Address of 26 (Numeric Object)", id(26))
print("Address of age", id(age))
print("Size of reference:", sys.getsizeof(x))  # Size of the reference

Here we can see the address of both the age and 26 are same. Its because the numeric object 26 is stored in the memory address (140593168368656) and its been referenced to age.

Okay, So where does the variable gets stored,

Python maintains namespaces, which are dictionaries that map variable names to objects. The process of associating a variable name with an object is called binding. When you assign a value to a variable, you are binding the variable name to an object in the namespace.

Variable names are stored in namespaces (which are dictionaries).

For example,

  • local variables are stored in a dictionary specific to the function
  • global variables are stored in the module’s dictionary, and so on.

import sys

x = 10
print("Size of reference:", sys.getsizeof(x))  # Size of the reference
local_namespace = locals()
print("Namespace:", local_namespace)  # Shows the local namespace
for key, value in local_namespace.items():
  print(key, value)

In the above code, we can see the variable x is stored in the namespace, which is a reference to the object 10. Both x and 10 will have the same address.

So, now we can say that variables in python is not a container but a label to the object.

So now what is the size of an variable ?

In Python, you can get the size of the reference (pointer) itself using the sys.getsizeof() function. However, sys.getsizeof() typically returns the size of the object that the reference points to, not the size of the reference itself.

Python does not provide a direct way to get the size of just the reference (pointer). This is because Python abstracts away the details of memory management and does not expose low-level details like the size of pointers directly to the user.

The size of a reference (pointer) is typically determined by the architecture of the system (e.g., 4 bytes on a 32-bit system, 8 bytes on a 64-bit system).

But we can try to get a rough estimate of the size,

import sys

def get_reference_size():
    # Create an object and get its size
    obj = 123
    
    # Create a list to hold references to the object
    reference_list = [obj] * 1000
    
    # Get the size of the list with references
    size_of_reference_list = sys.getsizeof(reference_list)
    print("size_of_reference_list", size_of_reference_list)
    
    # Calculate the size of one reference
    size_of_empty_list = sys.getsizeof([])
    size_of_one_reference = (size_of_reference_list - size_of_empty_list) / 1000
    
    return size_of_one_reference

print("Estimated size of one reference (pointer):", get_reference_size(), "bytes")

In the above code, we created a list of 1000 values (i.e 1000 times 123).

As per documentation,

Some objects contain references to other objects; these are calledΒ containers. Examples of containers are tuples, lists and dictionaries. https://docs.python.org/3/reference/datamodel.html

So the list object contains the reference to the other objects. So here it contains 1000 references to the value 123.

And then we are trying to calculate the size of the list of references and then dividing by the total number to get the size of the singe reference (or pointer or label).

Now, the size of a single variable it 8 bytes (Note: It depends on the system architecture.)

Inference:

  • Variables are not the containers.
  • Variables are just the labels to the objects. Variables and the variable name are same.
  • There is no type for the variables. If we use type(variable) it gives the type of the object which it refers to.
  • Variables are stored in the namespace.
  • Variables are having the size which varies based on the architecture. It might be 4 bytes or 8 bytes.

Docker Directives – Env Directive

9 July 2024 at 01:45

The ENV directive in a Dockerfile can be used to set environment variables.

Environment variables are key-value pairs that provide information to applications and processes running inside the container.

They can influence the behavior of programs and scripts by making dynamic values available during runtime.

Environment variables are defined as key-value pairs as per the following format:


ENV <key> <value>

For example, we can set a path using the ENV directive as below,


ENV PATH $PATH:/usr/local/app/bin/

We can set multiple environment variables in the same line separated by spaces. However, in this form, the key and value should be separated by the equal to (=) symbol:


ENV <key>=<value> <key=value> ...

Below, we set two environment variables configured.

The PATH environment variable is configured with the value of $PATH:/usr/local/app/bin, and

the VERSION environment variable is configured with the value of 1.0.0.


ENV PATH=$PATH:/usr/local/app/bin/ VERSION=1.0.0

Once an environment variable is set with the ENV directive in the Dockerfile, this variable is available in all subsequent Docker image layers.

This variable is even available in the Docker containers launched from this Docker image.

Below are some of the examples of using ENV file,

Example 1: Setting a single environment variable

# Use an official Node.js runtime as a parent image
FROM node:14

# Set the environment variable NODE_ENV to "production"
ENV NODE_ENV=production

# Copy package.json and package-lock.json files to the working directory
COPY package*.json ./

# Install app dependencies using the NODE_ENV variable
RUN if [ "$NODE_ENV" = "production" ]; then npm install --only=production; else npm install; fi

# Copy app source code to the container
COPY . .

# Expose the port the app runs on
EXPOSE 8080

# Define the command to run the app
CMD ["node", "app.js"]
##

Example 2: Using Environment Variables in Application Configuration


# Use an official Python runtime as a parent image
FROM python:3.8-slim

# Set environment variables
ENV APP_HOME=/usr/src/app
ENV APP_CONFIG=config.ProductionConfig

# Create application directory and set it as the working directory
RUN mkdir -p $APP_HOME
WORKDIR $APP_HOME

# Copy the current directory contents into the container at /usr/src/app
COPY . .

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Use the environment variable in the command to run the application
CMD ["python", "app.py", "--config", "$APP_CONFIG"]

Example 3: Passing Environment Variables to the Application


# Use an official nginx image as a parent image
FROM nginx:alpine

# Set environment variables
ENV NGINX_HOST=localhost
ENV NGINX_PORT=8080

# Copy custom configuration file from the current directory
COPY nginx.conf /etc/nginx/nginx.conf

# Replace placeholders in the nginx.conf file with actual environment variable values
RUN sed -i "s/NGINX_HOST/$NGINX_HOST/g" /etc/nginx/nginx.conf && \
    sed -i "s/NGINX_PORT/$NGINX_PORT/g" /etc/nginx/nginx.conf

# Expose ports
EXPOSE 8080

# Start nginx
CMD ["nginx", "-g", "daemon off;"]

TASK 2 – Constants and Variables

7 July 2024 at 07:44
  1. Create a variable named name and assign your name to it. Then print the value of the variable.
  2. Create a variable age and assign your age to it. Later, reassign the variable with a new value and print the new value.
  3. Assign the values 5, 10, and 15 to three variables a, b, and c in a single line. Print their values.
  4. Swap the values of two variables x and y without using a third variable. Print their values before and after swapping.
  5. Define constants PI with appropriate values and print them.
  6. Write a program that calculates the area of a circle using the constant PI and a variable radius. Print the area.
  7. Define constants for the length and width of a rectangle. Calculate and print the area.
  8. Define a constant for Ο€ (pi) and a variable for the radius. Calculate and print the circumference of the circle.

Solutions

PYTHON-FUNDAMENTALS: Constants Variables aNd Data Types

7 July 2024 at 03:52

Variables

A variable in Python is a symbolic name that references or points to an object.

Once a variable is assigned a value, it can be used to refer to that value throughout the program.

Variables act as containers (eg: box) for storing data values. But ideally they are reference to a memory where the value is stored.

How to name a variable ?

When naming variables in Python, there are a few rules and best practices to follow:

  1. Start with a letter or an underscore: Variable names must begin with a letter (a-z, A-Z) or an underscore (_).
  2. Followed by letters, digits, or underscores: After the first character, you can use letters, digits (0-9), or underscores.
  3. Case-sensitive: Variable names are case-sensitive. For example, myVariable and myvariable are different variables.
  4. Avoid Python keywords: Do not use Python reserved words or keywords as variable names (e.g., class, def, for, while).

Examples of Valid Variable Names:

  • my_variable
  • variable1
  • _hidden_variable
  • userName

Examples of Invalid Variable Names:

  • 1variable (starts with a digit)
  • my-variable (contains a hyphen)
  • for (a reserved keyword)

Assigning Values to Variables

In Python, the assignment operator = is used to assign values to variables. The syntax is straightforward: variable_name = value.

Examples:

# Assigning integer value
age = 25

# Assigning string value
name = "John Doe"

# Assigning float value
height = 5.9

# Assigning boolean value
is_student = True

Multiple Assignments

Python allows you to assign values to multiple variables in a single line. This can make your code more concise and readable.

Example:

# Assigning multiple variables in a single line
a, b, c = 5, 10, 15

# Swapping values of two variables
x, y = y, x

Unpacking Sequences

Python also supports unpacking sequences, such as lists or tuples, into variables. This feature is handy when working with collections of data.

Example:

# Unpacking a tuple
person = ("Alice", 30, "Engineer")
name, age, profession = person

# Unpacking a list
numbers = [1, 2, 3]
one, two, three = numbers

Variable Types

Python is a dynamically typed language, which means you don’t need to declare the type of a variable when assigning a value to it. The type is inferred at runtime based on the assigned value.

Example:

# Dynamic typing
my_variable = 10        # my_variable is an integer
my_variable = "Hello"   # my_variable is now a string

You can check the type of a variable using the type() function.

Example:

my_var = 42
print(type(my_var))  # Output: <class 'int'>

my_var = "Python"
print(type(my_var))  # Output: <class 'str'>

Constants

In Python, constants are variables whose values are not meant to change. By convention, constants are typically written in all uppercase letters with underscores separating words.

Note: However, Python does not enforce this, so constants are not truly immutable.

# Defining a constant
PI = 3.14159
MAX_USERS = 100

Data Types

Data types are the different kinds of values that you can store and work with.

Just like in your home, you have different categories of items like clothes, books, and utensils, in Python, you have different categories of data.

1. Numeric Types

  • Integer (int): Whole numbers.
  • Float (float): Decimal numbers.
  • Complex (complex): Complex numbers.

2. Text Type

  • String (str): Sequence of characters.

3. Boolean Type

  • Boolean (bool): Represents True or False.

4. None Type

  • NoneType: Represents the absence of a value

5. Sequence Types

  • List (list): Ordered, mutable collection
  • Tuple (tuple): Ordered, immutable collection.
  • Range (range): Sequence of numbers.

6. Mapping Type

  • Dictionary (dict): Unordered, mutable collection of key-value pairs.

7, Set Type

  • Set (set): Unordered collection of unique elements.
  • Frozenset (frozenset): Immutable set.

Checking Data Type

  • Syntax: type(variable_name)

Why Do Data Types Matter?

Data types are important because they tell Python what kind of operations you can perform with the data. For example:

  • You can add, subtract, multiply, and divide numbers.
  • You can join (concatenate) strings together.
  • You can access, add, remove, and change items in lists.
  • You can look up values by their keys in dictionaries.

Using the right data type helps your program run smoothly and prevents errors.

Exercises

Infographics

https://parottasalna.com/wp-content/uploads/2024/07/variables-constants-and-data-types-in-python.pdf

Quiz:

https://docs.google.com/forms/d/e/1FAIpQLSezKyjHkKlg4Qo8juWqviZkasyWOcAcEcBzK_NsBwGYG3WAvg/viewform?usp=sf_link

Migrating from .env to dotenvx

30 June 2024 at 17:43

Official Link: https://github.com/motdotla/dotenv

As a developer, we used .env file where we used to store environmental variables.

As stated from founder,

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.

During software development, we use environment variables to access the secret values, segregation based on env and other details required for development.

Dotenv is a small software library that helps manage environment variables in applications. Environment variables are like little pieces of information your application needs to run, such as database passwords, API keys, and other configuration details.

Why is Dotenv Useful?

Imagine you have an app that needs to connect to a database. You don’t want to hard-code your database password directly into your app’s code because:

  1. Security: If someone gets access to your code, they’ll also get your password.
  2. Flexibility: If you ever need to change the password, you’d have to go through your code and update it everywhere.

Dotenv allows you to store these important pieces of information in a separate file, usually named .env. This file is kept out of the main codebase, making it easier to manage and more secure.

How Does Dotenv Work?

Here’s a step-by-step on how you might use dotenv:

  1. Create a .env File: In the root directory of your project, create a file named .env.
  2. Add Variables: Inside this file, you add your environment variables. It might look something like this:
DATABASE_URL=your-database-url
API_KEY=your-api-key

3. Load Variables in Your Code: In your application code, use dotenv to load these variables. Here’s a quick example in JavaScript using Node.js:

require('dotenv').config();

const dbUrl = process.env.DATABASE_URL;
const apiKey = process.env.API_KEY;

Benefits of Using Dotenv

  • Security: Sensitive information is not directly embedded in your code.
  • Ease of Use: It’s straightforward to update configuration settings without digging through the code.
  • Portability: You can easily share your project with others. They can create their own .env file with their settings without changing the code.

So no problems right ?

Not really, there are some problems within itself,

  1. If not handled properly, the .env file can be accidentally committed to version control systems like Git. This exposes sensitive information to anyone with access to the repository.
  2. The contents of a .env file are stored in plain text. If unauthorized users gain access to the server or development environment, they can easily read sensitive information.
  3. Managing multiple .env files for different environments (development, testing, staging, production) can become cumbersome and error-prone.
  4. Each time the application starts, dotenv has to read and parse the .env file. While this overhead is generally minimal, it can become noticeable in very large applications or performance-critical environments.
  5. Using dotenv adds an additional dependency to your project. While it’s a relatively small and stable library, it’s still something that needs to be maintained and kept up-to-date. ( <- This is my main concern )

What to do ?

The dotenv founder itself brought a upgraded version of dotenv; dotenvx.

dotenvx works the same across every language, framework, and platform – inject your env at runtime with dotenvx run -- your-cmd.

Installing dotenvx

https://dotenvx.com/docs#getting-started

# download it directly as a standalone binary
curl -sfS https://dotenvx.sh/install.sh | sh
dotenvx help

Run Anywhere

This is one of my main concern, that i need to install one extra package to my codebase and i need to do some code changes while deploying to different deployment environments.

With dotenvx, I can simply run my application without installing additional packages.

$ echo "HELLO=World" > .env 
$ echo 'import os;print("Hello " + os.getenv("HELLO", ""))' > index.py

$ dotenvx run -- python3 index.py
Hello World

Even for different environments,

$ echo "HELLO=production" > .env.production
$ echo 'import os;print("Hello " + os.getenv("HELLO", ""))' > index.py

$ dotenvx run -f .env.production -- python3 index.py
Hello production

So for me, now it more handy to use .env

❌
❌