Python || Helpful One-Liners
1. Create Local HTTP Server
Python can help us when we need a simple HTTP Server to serve files from directory.
- Open Terminal and navigate to desired folder.
- Type below command (For Python3)
python -m http.server 8080
It will start local http server on port 8080
You can access it via http://127.0.0.1:8080
What if you want to bind your IP ?
python -m http.server --bind 192.168.1.5 8081
Open Web Browser and type: http://192.168.1.5:8081
Fun Time
In your mobile open web browser and type “http:192.168.1.5:8081” and you will able to access the files that are present on your laptop.
(Make sure your mobile and laptop are connected to same network)
2. Palindrome
It is a Number/String that remains the same when it is reversed.
To Remember “[::-1]”
Check = 'ABBA'
Result = Check == Check[::-1]
print(Result)
Let’s TRY FOR STRING
Let’s TRY FOR Integer ( Number: 1221)
Let’s TRY FOR Integer ( Number: 12211)
3. Delete All Even Elements From List.
To delete elements from the list we can utilize del.
l = [2,1,4,3,6,5,8,7]
del l[1::2]
print(l)
[1::2] Start with First Element Present at Index ‘1’ and then Jump by ‘2’.
4. Sum of Even Numbers From the List
l = [1,2,3,4,5,6,7,8]
result = sum[i for i in l if i%2 == 0 ]
print(result)
sum[ i for i in l if i%2 == 0]
It will take one element from the list and then it will check if it’s odd number of even, if number is even then it will include it in a list. Once it will iterate through all numbers present in a list, it will create new list and by utilizing SUM function we do Addition of all elements present in List.
5. Swap 2 variables without utilizing 3rd Variable
a = 10
b = 20a,b = b,aprint(a)
print(b)
a,b = b,a
6. Create List which Contains All Odd Number From 0 to 100
l = [ i for i in range(0,101) if i%2 != 0 ]
print(l)
range(0,101)
Loop Through Start Number till N-1 Number. So it will start from 0 and terminate at 100
7. Print Unique value from the list
l = [ 1,2,3,4,5,4,2,1,7,8]
print(l)
l = set(l)
print(l)
set() : It’s collection of items that will contain only unique values.
8. Factor of Number
import math
number = 5
factor_of_number = math.factorial(number)
print(factor_of_number)
import math
It allow us to perform mathematical tasks on numbers.
9. Find Out Maximum & Minimum Number From the List
l = [ 1,2,3,4,5,6,7,8,99,7,5,3,22,34,54]max_number = max(l)
min_number = min(l)print(max_number)
print(min_number)