Headlines Today's Cyber Security Cryptography Algorithm Games Dev

Connecting Python to MS Access


Jonathan Caceres, Sep 20, 05:40
Steps to Connect Python to MS Access using pyodbc

Step 1: Install the pyodbc package
To start, install the pyodbc package that will be used to connect Python with Access. 
You can use the PIP install method to install the pyodbc package:

 pip install pyodbc

Step 2: Create the database and table/s in Access    [omitted] you know this


Step 3: Connect Python to Access


  [ Python code  ]

import pyodbc

conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=path where you stored the Access file\file name.accdb;')
cursor = conn.cursor()
cursor.execute('select * from table name')
   
for row in cursor.fetchall():
    print (row)






Python Logical Operators


Jonathan Caceres, May 17, 22:18
and Logical AND	If both the operands are true then condition becomes true.	(a and b) is true.
or Logical OR	If any of the two operands are non-zero then condition becomes true.	(a or b) is true.
not Logical NOT	Used to reverse the logical state of its operand.	Not(a and 


Python Bitwise Operators


Jonathan Caceres, May 17, 22:20
Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands −

a = 0011 1100

b = 0000 1101

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

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011
& Binary AND	Operator copies a bit to the result if it exists in both operands	(a & b) (means 0000 1100)
| Binary OR	It copies a bit if it exists in either operand.	(a | b) = 61 (means 0011 1101)
^ Binary XOR	It copies the bit if it is set in one operand but not both.	(a ^ b) = 49 (means 0011 0001)
~ Binary Ones Complement	It is unary and has the effect of 'flipping' bits.	(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift	The left operands value is moved left by the number of bits specified by the right operand.	a << 2 = 240 (means 1111 0000)
>> Binary Right Shift	The left operands value is moved right by the number of bits specified by the right operand.	a >> 2 = 15 (means 0000 1111)


Python Comparison Operators


Jonathan Caceres, May 16, 23:48
=	If the values of two operands are equal, then the condition becomes true.	(a == b) is not true.
!=	If values of two operands are not equal, then condition becomes true.	(a != b) is true.
<>	If values of two operands are not equal, then condition becomes true.	(a <> b) is true. This is similar to != operator.
>	If the value of left operand is greater than the value of right operand, then condition becomes true.	(a > b) is not true.
<	If the value of left operand is less than the value of right operand, then condition becomes true.	(a < b) is true.
>=	If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.	(a >= b) is not true.
<=	If the value of left operand is less than or equal to the value of right operand, then condition becomes true.	(a <= b) is t


Python Arithmetic Operators


Jonathan Caceres, May 16, 23:24
+ Addition		a + b = 30

- Subtraction		a – b = -10

* Multiplication	a * b = 200

/ Division		b / a = 2

% Modulus		b % a = 0

** Exponent	Performs exponential (power) calculation on operators	a**b =10 to the power 20

//                      9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
	
Floor Division - The division of operands 
where the result is the quotient in which the digits after the 
decimal point are removed. But if one of the operands is negative,
 the result is floored, i.e., rounded away from zero 
(towards negative infinity) −	


Syntax to develop GUI for Python


Jonathan Caceres, Apr 19, 00:36
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods,
tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit 
shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications.
Creating a GUI using tkinter is an easy task.

To create a tkinter app:

    Importing the module – tkinter
    Create the main window (container)
    Add any number of widgets to the main window
    Apply the event Trigger on the widgets.
   
    To create a main window, tkinter offers a method ‘Tk(screenName=None,  baseName=None,  className=’Tk’,
  useTk=1)’. To change the name of the window, you can change the className to the desired one. 
    
   import tkinter


    Object name : mainloop(): There is a method known by the name mainloop() is used when your application 
    is ready to run. mainloop() is an infinite loop used to run the application, wait for an event to occur 
    and process the event as long as the window is not closed. 
    m=tkinter.Tk() where m is the name of the main window object





    
    m.mainloop()




    import tkinter 
    m = tkinter.Tk() 
    ''' 
    widgets are added here 
    '''
    m.mainloop() 


    tkinter also offers access to the geometric configuration of the widgets which can organize 
    the widgets in the parent windows. There are mainly three geometry manager classes class.

1. pack() method:It organizes the widgets in blocks before placing in the parent widget.
2. grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent widget.
3. place() method:It organizes the widgets by placing them on specific positions directed by the programmer.






  Button
   w=Button(master, option=value)

  
    activebackground: to set the background color when button is under the cursor.
    activeforeground: to set the foreground color when button is under the cursor.
    bg: to set he normal background color.
    command: to call a function.
    font: to set the font on the button label.
    image: to set the image on the button.
    width: to set the width of the button.
    height: to set the height of the button.


   import tkinter as tk 
r = tk.Tk() 
r.title('Counting Seconds') 
button = tk.Button(r, text='Stop', width=25, command=r.destroy) 
button.pack() 
r.mainloop() 
 





  Canvas

    bd: to set the border width in pixels.
    bg: to set the normal background color.
    cursor: to set the cursor used in the canvas.
    highlightcolor: to set the color shown in the focus highlight.
    width: to set the width of the widget.
    height: to set the height of the widget.



from tkinter import *
master = Tk() 
w = Canvas(master, width=40, height=60) 
w.pack() 
canvas_height=20
canvas_width=200
y = int(canvas_height / 2) 
w.create_line(0, y, canvas_width, y ) 
mainloop() 

CheckButton: To select any number of options by displaying a number of options to a user as toggle buttons.
The general syntax is:

w = CheckButton(master, option=value)

There are number of options which are used to change the format of this widget. Number of options can be 
passed as parameters separated by commas. Some of them are listed below.

    Title: To set the title of the widget.
    activebackground: to set the background color when widget is under the cursor.
    activeforeground: to set the foreground color when widget is under the cursor.
    bg: to set he normal backgrouSteganography

    Break

  from tkinter import *
master = Tk() 
var1 = IntVar() 
Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W) 
var2 = IntVar() 
Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W) 
mainloop() 




    bd: to set the border width in pixels.
    bg: to set the normal background color.
    cursor: to set the cursor used.
    command: to call a function.
    highlightcolor: to set the color shown in the focus highlight.
    width: to set the width of the button.
    height: to set the height of the button.






from tkinter import *
master = Tk() 
Label(master, text='First Name').grid(row=0) 
Label(master, text='Last Name').grid(row=1) 
e1 = Entry(master) 
e2 = Entry(master) 
e1.grid(row=0, column=1) 
e2.grid(row=1, column=1) 
mainloop() 



Frame

    highlightcolor: To set the color of the focus highlight when widget has to be focused.
    bd: to set the border width in pixels.
    bg: to set the normal background color.
    cursor: to set the cursor used.
    width: to set the width of the widget.
    height: to set the height of the widget.

 

from tkinter import *
root = Tk() 
frame = Frame(root) 
frame.pack() 
bottomframe = Frame(root) 
bottomframe.pack( side = BOTTOM ) 
redbutton = Button(frame, text = 'Red', fg ='red') 
redbutton.pack( side = LEFT) 
greenbutton = Button(frame, text = 'Brown', fg='brown') 
greenbutton.pack( side = LEFT ) 
bluebutton = Button(frame, text ='Blue', fg ='blue') 
bluebutton.pack( side = LEFT ) 
blackbutton = Button(bottomframe, text ='Black', fg ='black') 
blackbutton.pack( side = BOTTOM) 
root.mainloop() 



    bg: to set he normal background color.
    bg to set he normal background color.
    command: to call a function.
    font: to set the font on the button label.
    image: to set the image on the button.
    width: to set the width of the button.
    height” to set the height of the button.


from tkinter import *
root = Tk() 
w = Label(root, text='GeeksForGeeks.org!') 
w.pack() 
root.mainloop() 







List box


    highlightcolor: To set the color of the focus highlight when widget has to be focused.
    bg: to set he normal background color.
    bd: to set the border width in pixels.
    font: to set the font on the button label.
    image: to set the image on the widget.
    width: to set the width of the widget.
    height: to set the height of the widget.

from tkinter import *

top = Tk() 
Lb = Listbox(top) 
Lb.insert(1, 'Python') 
Lb.insert(2, 'Java') 
Lb.insert(3, 'C++') 
Lb.insert(4, 'Any other') 
Lb.pack() 
top.mainloop() 






MenuButton

    activebackground: To set the background when mouse is over the widget.
    activeforeground: To set the foreground when mouse is over the widget.
    bg: to set he normal background color.
    bd: to set the size of border around the indicator.
    cursor: To appear the cursor when the mouse over the menubutton.
    image: to set the image on the widget.
    width: to set the width of the widget.
    height: to set the height of the widget.
    highlightcolor: To set the color of the focus highlight when widget has to be focused.



from tkinter import *
top = Tk() 
mb = Menubutton ( top, text = "GfG") 
mb.grid() 
mb.menu = Menu ( mb, tearoff = 0 ) 
mb["menu"] = mb.menu 
cVar = IntVar() 
aVar = IntVar() 
mb.menu.add_checkbutton ( label ='Contact', variable = cVar ) 
mb.menu.add_checkbutton ( label = 'About', variable = aVar ) 
mb.pack() 
top.mainloop() 






Menu
w = Menu(master, option=value)
master is the parameter used to represent the parent window.


    title: To set the title of the widget.
    activebackground: to set the background color when widget is under the cursor.
    activeforeground: to set the foreground color when widget is under the cursor.
    bg: to set he normal background color.
    command: to call a function.
    font: to set the font on the button label.
    image: to set the image on the widget.



from tkinter import *
root = Tk() 
menu = Menu(root) 
root.config(menu=menu) 
filemenu = Menu(menu) 
menu.add_cascade(label='File', menu=filemenu) 
filemenu.add_command(label='New') 
filemenu.add_command(label='Open...') 
filemenu.add_separator() 
filemenu.add_command(label='Exit', command=root.quit) 
helpmenu = Menu(menu) 
menu.add_cascade(label='Help', menu=helpmenu) 
helpmenu.add_command(label='About') 
mainloop() 










Radio buttons


    activebackground: to set the background color when widget is under the cursor.
    activeforeground: to set the foreground color when widget is under the cursor.
    bg: to set he normal background color.
    command: to call a function.
    font: to set the font on the button label.
    image: to set the image on the widget.
    width: to set the width of the label in characters.
    height: to set the height of the label in characters.


from tkinter import *
root = Tk() 
v = IntVar() 
Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W) 
Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W) 
mainloop() 





Scale


    cursor: To change the cursor pattern when the mouse is over the widget.
    activebackground: To set the background of the widget when mouse is over the widget.
    bg: to set he normal background color.
    orient: Set it to HORIZONTAL or VERTICAL according to the requirement.
    from_: To set the value of one end of the scale range.
    to: To set the value of the other end of the scale range.
    image: to set the image on the widget.
    width: to set the width of the widget.


from tkinter import *
master = Tk() 
w = Scale(master, from_=0, to=42) 
w.pack() 
w = Scale(master, from_=0, to=200, orient=HORIZONTAL) 
w.pack() 
mainloop() 




Scrollbars


    width: to set the width of the widget.
    activebackground: To set the background when mouse is over the widget.
    bg: to set he normal background color.
    bd: to set the size of border around the indicator.
    cursor: To appear the cursor when the mouse over the menubutton.

from tkinter import *
root = Tk() 
scrollbar = Scrollbar(root) 
scrollbar.pack( side = RIGHT, fill = Y ) 
mylist = Listbox(root, yscrollcommand = scrollbar.set ) 
for line in range(100): 
mylist.insert(END, 'This is line number' + str(line)) 
mylist.pack( side = LEFT, fill = BOTH ) 
scrollbar.config( command = mylist.yview ) 
mainloop() 




Text


    highlightcolor: To set the color of the focus highlight when widget has to be focused.
    insertbackground: To set the background of the widget.
    bg: to set he normal background color.
    font: to set the font on the button label.
    image: to set the image on the widget.
    width: to set the width of the widget.
    height: to set the height of the widget.

from tkinter import *
root = Tk() 
T = Text(root, height=2, width=30) 
T.pack() 
T.insert(END, 'GeeksforGeeks\nBEST WEBSITE\n') 
mainloop() 





Top level


    bg: to set he normal background color.
    bd: to set the size of border around the indicator.
    cursor: To appear the cursor when the mouse over the menubutton.
    width: to set the width of the widget.
    height: to set the height of the widget.


from tkinter import *
root = Tk() 
root.title('GfG') 
top = Toplevel() 
top.title('Python') 
top.mainloop() 





Spinbox


    bg: to set he normal background color.
    bd: to set the size of border around the indicator.
    cursor: To appear the cursor when the mouse over the menubutton.
    command: To call a function.
    width: to set the width of the widget.
    activebackground: To set the background when mouse is over the widget.
    disabledbackground: To disable the background when mouse is over the widget.
    from_: To set the value of one end of the range.
    to: To set the value of the other end of the range.

from tkinter import *
master = Tk() 
w = Spinbox(master, from_ = 0, to = 10) 
w.pack() 
mainloop() 





PannedWindow


    bg: to set he normal background color.
    bd: to set the size of border around the indicator.
    cursor: To appear the cursor when the mouse over the menubutton.
    width: to set the width of the widget.
    height: to set the height of the widget.

from tkinter import *
m1 = PanedWindow() 
m1.pack(fill = BOTH, expand = 1) 
left = Entry(m1, bd = 5) 
m1.add(left) 
m2 = PanedWindow(m1, orient = VERTICAL) 
m1.add(m2) 
top = Scale( m2, orient = HORIZONTAL) 
m2.add(top) 
mainloop() 



Urllib vs URllib2


Jonathan Caceres, Feb 29, 10:05
[ Python 2 ]
import urllib2
from bs4 import BeautifulSoup
html = urllib2.urlopen( "http://www.google.com" ).read()
soup = BeautifulSoup( html )




for python 3 it's a little different, (I always forget this and it constantly gets me)


[ Python 3 ]
import urllib.request

html = urllib.request.urlopen("http://www.google.com")
soup = BeautifulSoup(html)
html.close()


then use filter or tags attribute 
for tag in soup.find_all( "a", { "class" : "gb1" } ):
    print tag["href"]


PIP install on Windows


Jonathan Caceres, Nov 18, 22:24
C:\Users\username>py -3 -m ensurepip
Looking in links: C:\Users\username\AppData\Local\Temp\tmp9m7pea8l
Requirement already satisfied: setuptools in c:\users\username\appdata\local\programs\python\python37-32\lib\site-packages (40.6.2)
Requirement already satisfied: pip in c:\users\username\appdata\local\programs\python\python37-32\lib\site-packages (19.2.3)


You are using pip version 19.2.3


Jonathan Caceres, Nov 02, 21:56
pip

Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade
your Python as Python 2.7 won't be maintained after that date. A future  version
of pip will drop support for Python 2.7.


Fix ImportError: No module named requests


Jonathan Caceres, Oct 17, 12:12
OSX/Linux

Use $ sudo pip install requests (or pip3 install requests for python3) if you have pip installed

Alternatively you can also use sudo easy_install -U requests if you have easy_install installed.

Alternatively you can use your systems package manager:

For centos: yum install python-requests For Ubuntu: apt-get install python-requests


Windows

Use pip install requests (or pip3 install requests for python3) if you have pip installed 
and Pip.exe added to the Path Environment Variable.

Alternatively from a cmd prompt, use > Path\easy_install.exe requests, where 
Path is your Python*\Scripts folder, if it was installed. (For example: C:\Python32\Scripts)

If you manually want to add a library to a windows machine, you can download the compressed 
library, uncompress it, and then place it into the Lib\site-packages folder of 
your python path. (For example: C:\Python27\Lib\site-packages)


URL Request between Python2 and Python3


Jonathan Caceres, Oct 04, 23:53
Python 3:

import urllib.request

wp = urllib.request.urlopen("http://google.com")
pw = wp.read()
print(pw)

Python 2:

import urllib
import sys

wp = urllib.urlopen("http://google.com")
for line in wp:
    sys.stdout.write(line)


Nice video of how to setup Scrapy


Jonathan Caceres, Oct 05, 03:26