My Rough PYTHON Random Notes as advice by Mr. Harry (codewithharry.com) started From 15 Aug 23


=========================================
import re pattern = r"\d+" string = "Some text. 123. Some text. 321" occurrences = re.finditer(pattern, string) print([o.group() for o in occurrences])
-------------------------------
import re




---------------------------------------------
Which operators can be used instead of "SET" object methods?
print('a.union(b) == ', a   | b, a.union(b))
print('a.intersection(b) ==',a & b, a.intersection(b) )
print('a.difference(b) ==',a-b,a.difference(b) )
print('a.symmetric_difference(b) ==', a^b ,a.symmetric_difference(b))

a= {1, 2, 3}
b= {3, 4, 5}
a.union(b) ==  {1, 2, 3, 4, 5} {1, 2, 3, 4, 5}
a.intersection(b) == {3} {3}
a.difference(b) == {1, 2} {1, 2}
a.symmetric_difference(b) == {1, 2, 4, 5} {1, 2, 4, 5}

==============================================
import re   
match = re.search(r'.+','Hello,\nGeeks', re.DOTALL)
print(match)

Hello, Geeks
----------------------------------------------------------------------
pattern = re.compile(r"cookie") sequence = "Cake and cookie" pattern.search(sequence).group()
'cookie'
-------------------------------------------------------------
## Matches any character except 5 re.search(r'Number: [^5]', 'Number: 0').group()
out Put will be
'Number: 0'
-------------------------------
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.

Combining *args and **kwargs

You can use both in the same function definition:

python
def 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.com

Here's a simple example to illustrate how *argv works:

python
def 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 based
import os
os.path.exists('guests.txt') # file exists or not
out put is : True
os.path.getsize('guests.txt') # what is the size of file
os.path.getmtime('guests.txt') # what is the time to modify file contents
os.path.getmtime('guests.txt')
1693380486.4203565
os.path.isfile('guests.txt')
True is exists
os.path.abspath('guests.txt')
os.getcwd() it gets the current working directory
os.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 \\ slashed
https://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).

Here is your output:
21

Awesome! You've now learned about writing your own methods!
------------------- 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"

================invert keys to values of dictionary==========

# very simple
def invertkeytovalue(dic): newdic={} for mkey,mvalues in dic.items(): for mvalue in mvalues: newdic[mvalue]=mkey return newdic dic={"Hard Drives": ["IDE HDDs", "SCSI HDDs"],"PC Parts": ["IDE HDDs", "SCSI HDDs", "High-end video cards", "Basic video cards"], "Video Cards": ["High-end video cards", "Basic video cards"]} print(invertkeytovalue(dic))

------------dictionary function================

d={'a':11,'b':22,'c':33} d.items() dict_items([('a', 11), ('b', 22), ('c', 33)]) d.values() dict_values([11, 22, 33]) d.keys() dict_keys(['a', 'b', 'c'])


-----------------------------------------------------------------

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

email

'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)

 

Comments

Post a Comment

Popular posts from this blog

PANDAS micro course by www.Kaggle.com https://www.kaggle.com/learn/pandas

Course No 2 Using Python to Interact with the Operating System Rough Notes

Introduction to Git and GitHub https://www.coursera.org/learn/introduction-git-github/