๐—–๐—ผ๐—ฑ๐—ฒ๐—ฟ๐—ฎ๐˜๐—ผ๐—ฟ
67 subscribers
6 links
A Free Channel for Sharing and Learning PHP, Nodejs, Python, HTML, CSS Codes to make your own scripts

Feel Free to ask
Download Telegram
#Python #Py #py #python

๐Ÿ”ด What is Python?

Python is a popular and versatile programming language. It's known for its simplicity, readability, and ease of use, which makes it a great choice for beginners and experienced programmers alike. Python can be used for a wide variety of tasks, such as web development, data analysis, scientific computing, automation, artificial intelligence, and more.

๐Ÿ”ด How to install Python?

To use python programming language, you need to install the Python interpreter on your operating system.

For windows: You can download Python from the official website https://www.python.org/downloads/
For VPS: You can install by command: apt install python3 && apt install python3-pip
For Termux: You can install by command: pkg install python3

๐Ÿ”ด How to make python code?

Open a text editor on your computer. You can use Notepad (Windows), TextEdit (macOS), or any code editor you prefer (e.g., Visual Studio Code, Sublime Text). Write the following code:

print("Hello, World!")

Save the file with a .py extension, for example, hello.py.

๐Ÿ”ด How to run the code?

Open a terminal or command prompt. Go to the folder where you saved your hello.py file. Run the program by typing:

python hello.py

You should see the output: Hello, World!
โค1
๐Ÿ”ด PYTHON BASICS KNOWLEDGE

Python has a simple and readable syntax. Here are some basic concepts you should start learning:

Variables: Used to store data. Example: name = "John"

Data Types: Python has various data types, including integers, floats, strings, lists, dictionaries, and more.

Control Structures: Learn about if statements for conditional execution and loops like for and while for repetition.

Functions: Functions allow you to group code into reusable blocks. You can define your own functions and use built-in functions.

Lists and Dictionaries: These are data structures used to store collections of values.

Classes: These are updated form of functions. There would be 2 or more functions defined in a class for use the individual functions in future through the class
๐Ÿ”ด Variables and Data Types

name = "Alice" #Data Type: String
age = 25 #Data Type: Integer
height = 5.7 #Data Type: Float
is_student = True #Data Type: Boolean

print(name)
print(age)
print(height)
print(is_student)


All Default Data Types used in Pythonโ€”

Numeric Types:
int: Integer type, e.g., 5, -10
float: Floating type, e.g., 3.14, -0.25
complex: Complex number type, e.g., 2 + 3j

Sequence Types:
str: String type, e.g., "Hello, World!"
list: List type, e.g., [1, 2, 3]
tuple: Tuple type, e.g., (1, 2, 3)

Mapping Type:
dict: Dictionary type, e.g., {'key': 'value'}

Set Types:
set: Unordered set type, e.g., {1, 2, 3}
frozenset: Immutable set type, e.g., frozenset([1, 2, 3])

Boolean Type:
bool: Boolean type, either True or False

NoneType:
None: Represents the absence of a value or a null value

Binary Types:
bytes: Immutable sequence of bytes, e.g., b'hello'
bytearray: Mutable sequence of bytes, e.g., bytearray([65, 66, 67])
memoryview: Provides a view on memory buffers
๐Ÿ”ด Conditional Statements (if, else, and elif)

Conditional statements allow you to control the flow of your program based on certain conditions. They help you make decisions and execute different blocks of code depending on whether conditions are met.

If Statement:
The if statement allows you to execute a block of code if a certain condition is true. Example:

age = 18

if age >= 18:
print("You are an adult.")

If-else Statement:
The if-else statement lets you execute one block of code if a condition is true and another block if the condition is false.

age = 15

if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")

If-elif-else Statement:
The if-elif-else statement allows you to check multiple conditions in sequence.

score = 85

if score >= 90:
print("You got an A.")
elif score >= 80:
print("You got a B.")
elif score >= 70:
print("You got a C.")
else:
print("You need to improve.")

In this example, only one block of code will be executed. Once a condition is met, the rest of the elif and else blocks are skipped.


๐Ÿ”ด Operators

Equal (==):
Checks if two values are equal.

x = 5
y = 5

if x == y:
print("x and y are equal.")

Not Equal (!=):
Checks if two values are not equal.

x = 5
y = 10

if x != y:
print("x and y are not equal.")

Greater Than (>):
Checks if the left value is greater than the right value.

x = 10
y = 5

if x > y:
print("x is greater than y.")

Less Than (<):
Checks if the left value is less than the right value.

x = 5
y = 10

if x < y:
print("x is less than y.")

Greater Than or Equal To (>=):
Checks if the left value is greater than or equal to the right value.

x = 10
y = 10

if x >= y:
print("x is greater than or equal to y.")

Less Than or Equal To (<=):
Checks if the left value is less than or equal to the right value.

x = 5
y = 10

if x <= y:
print("x is less than or equal to y.")

๐Ÿ”ด Operators with combination Usage Examples:

These operators can be used in various combinations within conditional statements to create complex conditions:

x = 7
y = 12

if x > 5 and y < 15:
print("Both conditions are satisfied.")

if x > 10 or y > 20:
print("At least one condition is satisfied.")

if not (x > 10):
print("The condition is not satisfied.")

Additionally, these operators can also be used in conjunction with elif clauses within an if-elif-else statement:

age = 25

if age < 18:
print("You are a minor.")
elif age >= 18 and age < 60:
print("You are an adult.")
else:
print("You are a senior citizen.")
๐Ÿ”ด Lists and Dictionaries

Lists and dictionaries are powerful data structures in Python. Example:

#Lists
fruits = ["apple", "banana", "orange"]

print(fruits[0]) # Accessing elements by index

fruits.append("grape") # Adding an element

print(len(fruits)) # Finding the length of the list



#Dictionaries
person = {"name": "Alice", "age": 30, "city": "New York"}

print(person["name"]) # Accessing values by key

person["job"] = "engineer" # Adding a key-value pair


๐Ÿ”ด Index In Python

In Python, indexing refers to the process of accessing individual elements within a data structure, such as a list, tuple, or string, using their position or index. The index is a numerical value that represents the position of the element within the data structure. Python uses zero-based indexing, which means that the index of the first element is 0, the index of the second element is 1, and so on.

Lists:
Lists are ordered collections of elements, and you can access elements using their index positions.

my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Output: 10
print(my_list[2]) # Output: 30


Tuples:
Tuples are similar to lists, but they are immutable (cannot be changed after creation).

my_tuple = (5, 15, 25, 35)
print(my_tuple[1]) # Output: 15


Strings:
Strings are sequences of characters, and you can access individual characters using their indices.

my_string = "Hello, world!"
print(my_string[7]) # Output: "w"


Negative Index:
Negative indexing can also be used to count positions from the end of the sequence. For example, -1 refers to the last element, -2 refers to the second-to-last element, and so on.

my_list = [10, 20, 30, 40, 50]
print(my_list[-1]) # Output: 50 (last element)
print(my_list[-2]) # Output: 40 (second-to-last element)
๐Ÿ”ด Methods in Python

append() Method:
The append() method is used to add a single element to the end of a list.

my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

extend() Method:
The extend() method is used to append elements from another iterable (like a list or tuple) to the end of the list.

my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]

insert() Method:
The insert() method is used to add an element at a specific index in the list. The syntax is list.insert(index, element).

my_list = [1, 2, 3]
my_list.insert(1, 5) # Insert 5 at index 1
print(my_list) # Output: [1, 5, 2, 3]

remove() Method:
The remove() method is used to remove the first occurrence of a specified element from the list.

my_list = [1, 2, 3, 2]
my_list.remove(2) # Removes the first occurrence of 2
print(my_list) # Output: [1, 3, 2]

pop() Method:
The pop() method is used to remove and return an element from a specific index. If no index is provided, it removes and returns the last element.

my_list = [10, 20, 30, 40]
popped_element = my_list.pop(1) # Removes and returns element at index 1 (20)
print(my_list) # Output: [10, 30, 40]
print(popped_element) # Output: 20

index() Method:
The index() method is used to find the index of the first occurrence of a specified element.

my_list = [10, 20, 30, 20, 40]
index_of_20 = my_list.index(20) # Finds the index of the first occurrence of 20
print(index_of_20) # Output: 1
๐Ÿ”ด Loops

Loops are a fundamental programming concept used to execute a block of code repeatedly. They allow you to automate repetitive tasks, iterate over collections of data, and perform various computations efficiently. Python provides two main types of loops: for loops and while loops.

For Loops:
A for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence.

for item in sequence:
print("Hi")

Here's an example using a for loop to print numbers from 1 to 5:

for num in range(1, 6):
print(num)

In this example, the range(1, 6) generates a sequence of numbers from 1 to 5 (inclusive). The loop iterates over each number in the sequence and prints it.


While Loops:
A while loop is used to repeatedly execute a block of code as long as a certain condition is true.

while condition:
print("Hi")

Here's an example using a while loop to print numbers from 1 to 5:

num = 1
while num <= 5:
print(num)
num += 1

In this example, the loop runs as long as the condition num <= 5 is true. The variable num starts at 1 and increments by 1 in each iteration until it reaches 6, at which point the loop terminates.


Loop Control Statements:
Python provides loop control statements to modify the behavior of loops:

break: Terminates the loop prematurely.
continue: Skips the rest of the current iteration and moves to the next one.
else clause: Used with for and while loops. The code in the else block executes when the loop completes normally (i.e., without encountering a break statement).

Here's an example of using the break statement to exit a loop:

for num in range(1, 11):
if num == 5:
break # Exit the loop when num is 5
print(num)


Nested Loops:
You can also nest loops within each other to perform more complex tasks. Just be careful with the indentation to maintain clarity.

for i in range(3):
for j in range(2):
print(i, j)

This nested loop will print combinations of i and j for each value of i from 0 to 2 and each value of j from 0 to 1.
โค1
๐Ÿ”ด All Types of Operators in Python

Python supports a variety of operators for performing different types of operations on values and variables. Here's an overview of the main types of operators in Python:

1. Arithmetic Operators:
These operators are used for mathematical calculations.

+: Addition
-: Subtraction
*: Multiplication
/: Division
//: Floor Division (division that rounds down to the nearest whole number)
%: Modulus (remainder after division)
**: Exponentiation (raising a number to a power)


2. Assignment Operators:
These operators are used to assign values to variables.

=: Assigns a value to a variable
+=: Adds the right operand to the left operand and assigns the result to the left operand
-=: Subtracts the right operand from the left operand and assigns the result to the left operand
*=: Multiplies the left operand by the right operand and assigns the result to the left operand
/=: Divides the left operand by the right operand and assigns the result to the left operand
//=: Performs floor division and assigns the result to the left operand
%=: Computes the modulus and assigns the result to the left operand
**=: Raises the left operand to the power of the right operand and assigns the result to the left operand


3. Comparison Operators:
These operators are used to compare values.

==: Equal to
!=: Not equal to
<: Less than
>: Greater than
<=: Less than or equal to
>=: Greater than or equal to


4. Logical Operators:
These operators are used to perform logical operations.

and: Logical AND (returns True if both operands are True)
or: Logical OR (returns True if at least one operand is True)
not: Logical NOT (returns the opposite of the operand's truth value)


5. Membership Operators:
These operators are used to test whether a value is a member of a sequence.

in: Returns True if a value is found in the sequence
not in: Returns True if a value is not found in the sequence


6. Identity Operators:
These operators are used to compare the memory locations of two objects.

is: Returns True if both operands refer to the same object
is not: Returns True if both operands do not refer to the same object


7. Bitwise Operators:
These operators are used to perform bitwise operations on integers.

&: Bitwise AND
|: Bitwise OR
^: Bitwise XOR (exclusive OR)
~: Bitwise NOT
<<: Left shift
>>: Right shift
LXML INSTALLATION PROCESS IN TERMUX:

First clear data your termux.

Then open termux and command these sequently:


apt update && apt upgrade

pkg install python libxml2 libxslt pkg-config

pip install cython wheel

CFLAGS="-Wno-error=incompatible-function-pointer-types -O0" pip install lxml

It will be installed ๐Ÿฅฐ๐Ÿ‘
Rust Compiler For Termux:

pkg install rust
How to host PHP Scripts in VPS โ“

Solution:

First install the necessary packages from below commands :

sudo apt update
sudo apt install apache2
sudo apt install php libapache2-mod-php php-mysql

Then find out which version of PHP you are using by this command :

php -v

After getting the PHP version, use the below commands to allow permission :

sudo a2enmod php7.x
sudo a2enmod rewrite

Here 7.x means 'x' is the version of your PHP. Just replace the actual version you are using. Then restart the apache using this command :

sudo systemctl restart apache2


We are done setting up our VPS to a Web Hosting Server. Now what we need is to upload our PHP files to the public_html folder as usual we upload in our web hostings and then restart apache and our PHP site will be hosted.

To go to the public_html folder, use this command :

cd var/www/html

Then upload your full PHP project on that folder and restart apache by this command again :

sudo systemctl restart apache2


And Boom ๐Ÿ”ฅ

Your PHP Website is running on Your VPS IP Address. To open your site, go to :

http://x.x.x.x

Here 'x' is Your IP Address
How to connect domain to my PHP hosted website โ“

Solution:

First open your domain configuration where you purchased the domain. I mean open DNS Management

Then set up 'A Record' by below instructions :

Type: A Record
Host/Name: @
Point/IP: x.x.x.x
TTL: Leave Empty or 3600

If you want to use a sub-domain then,

Type: A Record
Host/Name: Your_Subdomain_Name
Point/IP: x.x.x.x
TTL: Leave Empty or 3600


Domain Management System done โœ… Now wait for 5 minutes to confirm the dns actually setted up


After that, open your VPS and you have to create a new configuration file on your VPS sites configuration folder.

To open sites configuration folder of your VPS use this command :

cd /etc/apache2/sites-available

Then create a new file named [your_domain.conf] like this example using nano editor :

Suppose my domain is : xoiox.com. So i name the file:

nano xoiox.com.conf

After that a editor page will appear in your VPS and simply write this below code on that file :


<VirtualHost *:80>
ServerAdmin your_mail@mail.com
ServerName your_domain_or_subdomain
ServerAlias www.your_domain_or_subdomain
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>



Now allow permission to your domain site using the below command :

sudo a2ensite your_domain.conf

[Note: Here will be is exact same as you created the configuration file name before]

Allow 443 ans 80 port traffics to receive by this command :

sudo ufw allow 'Apache'

And then restart your apache again using this command :

sudo systemctl restart apache2

After that, wait for 5 minutes again and boom ๐Ÿ”ฅ๐Ÿ”ฅ

Your site is now running at your domain ๐Ÿ”ฅ

If you want to check your access logs and error logs, just command these :

sudo tail -f /var/log/apache2/access.log
sudo tail -f /var/log/apache2/error.log

Boom ๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅ
A Few Things PHP Website Related โ•โ—

1. If you want to use the hosted files without (.php) extensions, then all you need to create a file, write something and save and then restart apache.

Below instructions is for (.php) extension remove :

First create a new file if not exists in your public_html folder (e.g. /var/www/html) :

cd /var/www/html
sudo nano .htaccess

Then save this below script on that file :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]


After that command this :

sudo a2enmod rewrite

And finally restart your apache using this command again :

sudo systemctl restart apache2

And now finally boom ๐Ÿ”ฅ๐Ÿ”ฅ You can now use any files without php extension on your website


2. If you need to install any PHP Extensions for your site, then use apt-get package install manager to install extensions for your website.

Suppose, I need to install Curl Extension for my PHP website, so the command for php-curl installation is :

sudo apt-get update
sudo apt-get install php-curl

And Your extension will be installed...๐Ÿ”ฅ๐Ÿ”ฅ

And for use the extension, just do restart your apache again ๐Ÿ˜๐Ÿ˜ :

sudo systemctl restart apache2

And your website is running super fast ๐Ÿ”ฅโ—๐Ÿ”ฅ
#Part1 Heroku Deploying

How to host any php/python projects/files in heroku using Heroku-Cli โ“

So So So Simple ๐Ÿคญ๐Ÿ”ฅ

Solution:

First you need to install heroku-cli on your system. For instance let me using Termux

So command these one by one :-

pkg install wget tar gzip -y

wget http://cli-assets.heroku.com/heroku-linux-arm.tar.gz -O heroku.tar.gz

tar -xvzf heroku.tar.gz

mkdir -p /data/data/com.termux/files/usr/lib/heroku

mv heroku/* /data/data/com.termux/files/usr/lib/heroku

rm -rf heroku heroku.tar.gz

ln -s /data/data/com.termux/files/usr/lib/heroku/bin/heroku /data/data/com.termux/files/usr/bin/heroku

cd /data/data/com.termux/files/usr/lib/heroku/bin/

sed -i 's/#!/#!\/data\/data\/com.termux\/files/g' heroku

pkg install nodejs -y

mv node node.old

ln -s ../../../bin/node node

echo 'export PATH="/data/data/com.termux/files/usr/lib/heroku/bin:$PATH"' >> ~/.bashrc

source ~/.bashrc

After doing all these commands successfully, you will check heroku cli version using this command :

heroku --version

And boom ๐Ÿ”ฅ๐Ÿ”ฅ Heroku cli is all set. Now lets host python projects on heroku. See my next post โค๏ธ๐Ÿซถ
#Part2 Heroku Deploying

The previous process was about how to install heroku cli on termux. If you have windows or linux (ubuntu, debian etc.) then proceed the below instructions :

In windows, install Heroku-cli application by downloading and installing this:

32-Bit
64-Bit

In VPS, use this command to install heroku-cli:

sudo curl https://cli-assets.heroku.com/install.sh | sh

In termux, already posted in previous post

So finally our heroku cli installation has successfully completed.

Now we need to install GIT on our system. To install git use this below instructions:

For Linux/Termux Users, use this below command:

apt install git

For Windows, download and install the below application:

32-Bit
64-Bit

After installing GIT, your system is finnally ready to be able to host any php/python projects on heroku. So, go to the next post to see how to host on heroku ๐Ÿ”ฅ๐Ÿ‘
๐Ÿ‘1
#Part3 Heroku Deploying

So, we have now git and heroku-cli installed on our system and we are now ready to deoloy.

First, create or navigate to the directory/folder where your python/php project files located.

Then use these below instructions:

If you want to deploy a php project, then you need two files in your project named "composer.json" & "composer.lock", so use the below instructions to get those:

First, install php in your system.

For linux/termux, use the below command:

apt install php

For windows, go this post

After installing php, then you need to install composer in your system. Use the below commands to install composer:

For windows, download and install:

Composer

For termux, use these commands:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php composer-setup.php --install-dir=/data/data/com.termux/files/usr/bin --filename=composer

For vps, use these commands:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php -r "if (hash_file('sha384', 'composer-setup.php') === 'e21205b207c3ff031906575712edab6f13eb0b361f2085f1f1237b7126d785e826a450292b6cfd1d64d92e6563bbde02') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

php composer-setup.php --install-dir=/usr/local/bin --filename=composer

After successfully installed composer, lets proceed further to deploy a php project on heroku:

So, initialize a composer file by command this first:

composer init

[Inside this initialization:

Package Name will be the default inside the brackets

Description will be your choice, no matter what

Author will be your name and email

Minimum Stability will be "stable"

Package Type will be "project"

License will be "MIT"

Then it will ask to define dependencies for your php project. Simply write "yes" and enter. Then first write "php" and enter after that if ask latest version just leave it blank and enter

Then it will again ask another dependencies, so proceed with your dependencies for example if you need php-curl, then search it and choose "php-curl-class/php-curl-class" this if has, you can choose another provider also.

After that enter and if asks dev-dependencies then skip and enter and proceed to finalization. Then it will crete two files in your directory named "composer.json" and "composer.lock"
]

If you want to deploy a python project then you need one file named "Procfile", so create a " Procfile" without any extension and write inside the file :

worker: python your_project.py

If you want to run a folder, then use:

worker: python -m folder

Then save the file. And you are set all.

Now initialize a git repository for your project inside your directory by this command:

git init

Then, set up configuration file for your git repository following this command:

git config --global user.email YOUR_EMAIL@gmail.com

git config --global user.name YOUR_NAME

After setting up config file, now add all files to the repository following this command:

git add .

After that, you need to commite that you update files on the repository by this command:

git commit -m "Initialize Project Repository"

If you think some files are mistakely add to git repository then you can remove files using below command:

git rm [files/folders]

If you want to check how many files and which which are there in the repository, then command the below:

git ls-files

If you think to delete all the files inside the repository, then use the below command:

git rm -r .

To reset git repository, use this commamd:

git reset --hard

After changes in git repository you must need to commit that you change something using below command:

git commit -m "Your Changes"

So, our git repository is ready to deploy. Now what we need is to push this git repository to our heroku. See you in the next post ๐Ÿ”ฅ๐Ÿซถ
#Part4 Heroku Deploying

So, first of all, we need to login to our heroku account for deployment. So, command below:

heroku login

After this command, it will asks to enter for continue process. So, enter and it will prompt auto to open a browser. So, login your account on the browser. If the browser does not auto opened, then you will see a url so just open the url on your local browser and login. After login successfully, come back to your system.

After login, you need to create a heroku app for your project, so command:

heroku create YOUR_APP_NAME

After create, connect your git repository with this heroku app using the below command:

heroku git:remote -a YOUR_APP_NAME

After connect, push your git repository to heroku using this below command:

git push heroku master

After successfully pushing, if you had a php project it will directly hosted in heroku and you dont need to do any more things. Just copy the url shown in terminal and open it. And boom ๐Ÿ”ฅ Your website is ready to host

But if you had a python project, then after pushing, you need to scale your project with dynos using a worker for this app using the below command:

heroku ps:scale worker=1

And boom ๐Ÿ”ฅ๐Ÿ”ฅ

Your python project is also hosted in heroku. โค๏ธ๐Ÿ”ฅ

Now enjoy ๐Ÿซถ
Git Repository Connect to Shell:

git init

git add README.md

git commit -m "first commit"

git branch -M main

git remote add origin [REPO_LINK]

git push -u origin main

Existing Git Repository Connect to Existing Local Git Repository:

git remote add origin [REPO_LINK]

git branch -M main

git push -u origin main
โค2
In python 3.7>= older versions:

response = await call()

# Assume 'response' is 50

if response:
sum = 10 + response
print(sum)
else:
print("Sorry, no response found")


In python3.8=< later versions:

if response := await call():
print(10 + response)
else:
print("Sorry, no response found")


#Keypoint

Note: In python 3.8 or later versions, there is a new ":=" walrus operator, which can do conditional statements with assignation, so you can make your script more shorter and more improver
๐Ÿฅฐ1
FIREBASE ADMIN MODULE INSTALLATION IN TERMUX

pip install -U setuptools cython -y

GRPC_PYTHON_DISABLE_LIBC_COMPATIBILITY=1 GRPC_PYTHON_BUILD_SYSTEM_OPENSSL=1 GRPC_PYTHON_BUILD_SYSTEM_ZLIB=1 GRPC_PYTHON_BUILD_SYSTEM_CARES=1 CFLAGS+=" -U__ANDROID_API__ -D__ANDROID_API__=30 -include unistd.h" LDFLAGS+=" -llog" pip install grpcio -y

pip install firebase_admin -y

This will take at least 1.5 to 2 hour to properly install it on your android machine, even if the machine is a VPS or Windows or Android or IOS or MacOS, doesnโ€™t matter ๐Ÿ˜ž