My Rough PYTHON Random Notes as advice by Mr. Harry (codewithharry.com) started From 15 Aug 23
-------------------------------
import re
---------------------------------------------
Which operators can be used instead of "SET" object methods?
==============================================
----------------------------------------------------------------------
pattern = re.compile(r"cookie") sequence = "Cake and cookie" pattern.search(sequence).group()
-------------------------------------------------------------
-------------------------------
split a string by multiple delimiters?
How do you flatten a nested list (a list of lists of numbers)?
How do you create a list of tuples in range (0,0)-(2,2)?
=============================================================
Summary of Differences:
*args:
- Accepts variable numbers of positional arguments.
- Passed as a tuple.
**kwargs:
- Accepts variable numbers of keyword arguments.
- Passed as a dictionary.
*args:- Accepts variable numbers of positional arguments.
- Passed as a tuple.
**kwargs:- Accepts variable numbers of keyword arguments.
- Passed as a dictionary.
Combining *args and **kwargs
You can use both in the same function definition:
pythondef display_info(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
display_info(1, 2, 3, name="Alice", age=30)
You can use both in the same function definition:
pythondef display_info(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
display_info(1, 2, 3, name="Alice", age=30)
Output:
Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'age': 30}
This way, you can handle both types of arguments flexibly in your functions!
---------------------------------------------------------Mixing them properly: If you want to mix positional and keyword arguments, always place positional arguments first:
python
my_func(2, a=1)
-------------------------------------from Chatgpt.comHere's a simple example to illustrate how *argv works:
pythondef print_numbers(*argv):
for number in argv:
print(number)
# Calling the function with different numbers of arguments
print_numbers(1, 2, 3)print_numbers(10, 20, 30, 40, 50)
------ Operating systems command Linux/Unix basedimport os
os.path.exists('guests.txt') # file exists or not
out put is : Trueos.path.getsize('guests.txt') # what is the size of fileos.path.getmtime('guests.txt') # what is the time to modify file contents
os.path.getmtime('guests.txt')
1693380486.4203565os.path.isfile('guests.txt')True is existsos.path.abspath('guests.txt')os.getcwd() it gets the current working directoryos.mkdir('newdir')
os.chdir('newdir')os.getcwd()'F:\\0 Python\\newdir'os.listdir()[]os.chdir('..')os.getcwd()'F:\\0 Python'os.path.join(dir,filename) joins with \\ slashedhttps://docs.python.org/3/library/os.html for os.. full commands refer it.
==================================================file=open('spider.txt')
print(file.read())
To print whole file FROM CURRENT POSITION (REST OF LINES) on screen like type command of cmd
--------- An other Simple Example-----------------
Have a go at writing methods for a class.
Create a Dog class with dog_years based on the Piglet class shown before (one human year is about 7 dog years).
------------------- A VERY SIMPLE OO EXAMPLE----------------------class Furniture: color = "" material = ""
table = Furniture()table.color='brown'table.material='wood'
couch = Furniture()couch.color='red'couch.material='leather'
def describe_furniture(piece): return ("This piece of furniture is made of {} {}".format(piece.color, piece.material))
print(describe_furniture(table)) # Should be "This piece of furniture is made of brown wood"print(describe_furniture(couch)) # Should be "This piece of furniture is made of red leather"
Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'age': 30}
This way, you can handle both types of arguments flexibly in your functions!
Mixing them properly: If you want to mix positional and keyword arguments, always place positional arguments first:
pythonmy_func(2, a=1)
Here's a simple example to illustrate how *argv works:
pythondef print_numbers(*argv):
for number in argv:
print(number)
# Calling the function with different numbers of arguments
print_numbers(1, 2, 3)print_numbers(10, 20, 30, 40, 50)os.path.exists('guests.txt') # file exists or not
out put is : True
os.path.getmtime('guests.txt')
1693380486.4203565
file=open('spider.txt')
print(file.read())
To print whole file FROM CURRENT POSITION (REST OF LINES) on screen like type command of cmd
--------- An other Simple Example-----------------
Have a go at writing methods for a class. Create a Dog class with dog_years based on the Piglet class shown before (one human year is about 7 dog years).
================invert keys to values of dictionary==========
------------dictionary function================
-----------------------------------------------------------------
def count_letters(text): result={} for letter in text: if letter not in result: result[letter]=0 # if already not exists first initialize to 0 then add 1 next statment result[letter] += 1 return result print(count_letters('saeed hassan'))
==============================
Formatting expressions
Expr | Meaning | Example |
|---|---|---|
{:d} | integer value | '{:d}'.format(10.5) → '10' |
{:.2f} | floating point with that many decimals | '{:.2f}'.format(0.5) → '0.50' |
{:.2s} | string with that many characters | '{:.2s}'.format('Python') → 'Py' |
{:<6s} | string aligned to the left that many spaces | '{:<6s}'.format('Py') → 'Py ' |
{:>6s} | string aligned to the right that many spaces | '{:>6s}'.format('Py') → ' Py' |
{:^6s} | string centered in that many spaces | '{:^6s}'.format('Py') → ' Py ' |
Check out the official documentation for all available expressions.
======= string.REPLACE(oldstring,newstring)
E.g
'This is old email saeedhisbani@aasml.com it will be replace by saeedhisbani@alabbas.com'
email.replace('saeedhisbani','saeedHassan')
'This is old email saeedHassan@aasml.com it will be replace by saeedHassan@alabbas.com'
=======================
print('{:>.f} > sign means to alline to right'.format())
=============
'....'.join(['this','is'])
'this....is'
===================
'123'.isnumeric()
return True
=== RECURSION FUCTION
Using same function into function
def factorial(n):
if n < 1 :
return 0
return n + factorial(n-1)
print(factorial(0))
print(factorial(2))
print(factorial(3))
print(factorial(4))
===============================================
Fuction can return many value like
def func(seconds):
hours=
minutes=
return hours,minutes,second
your assign 3 values to 3 difference variable like
var1,var2,var3 = func(5000)
--------------------------------------------
radians(x) → a function that converts x from degrees to radians;
degrees(x) → acting in the other direction (from radians to degrees)
=========================
my_tuple = (1, 10, 100, 1000)
my_tuple[:-2] output will be (1,10) means [-2] value ie 100 will not include
=================
I am using this blog to save my Pythons Rough Notes Randomly.
This suggested by Mr. Harry my Python tutor https://www.youtube.com/watch?v=3C7Db8cRuec
Some of very handy functions in Python
map(function, list)
filter(bolean retrun function, list
also see reduce() function
-----------------------------------------------------------------------
I think it is about Django Servers
Today I also learn to access webserver data by using
GET data from WebServer
LOAD data on WebServer
PUT update data of WebServer
DELETE data from WebSever
=============== See continue statement is like loop statement in foxplus
for i in range(0,10):
if i%3==0:
print(i,'divisable by 3')
continue
print(i,'is not divisble by 3')
=================================================
3**2**2 = 81 NOT 36 calculate from right to left NOT from left to right
===================================================
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
# Choose the larger number
if number1 > number2: larger_number = number1
else: larger_number = number2
# Print the result
print("The larger number is:", larger_number)
A very Good Start.
ReplyDelete