Python

#TicTacToe game

from tkinter import *
import tkinter.messagebox

mainWin = Tk()
mainWin.title("Tic Tac Toe")

click = True

def checker(buttons):
 global click
 if buttons["text"] == " " and click == True:
 buttons["text"] = 'X'
 click = False
 elif buttons["text"] == " " and click == False:
 buttons["text"] = 'O'
 click = True
 elif(
 (button1["text"] == 'X' and button2["text"] == 'X' and button3["text"] == 'X') or
 (button4["text"] == 'X' and button5["text"] == 'X' and button6["text"] == 'X') or
 (button7["text"] == 'X' and button8["text"] == 'X' and button9["text"] == 'X') or
 (button1["text"] == 'X' and button4["text"] == 'X' and button7["text"] == 'X') or
 (button2["text"] == 'X' and button5["text"] == 'X' and button8["text"] == 'X') or
 (button3["text"] == 'X' and button6["text"] == 'X' and button9["text"] == 'X') or
 (button1["text"] == 'X' and button5["text"] == 'X' and button9["text"] == 'X') or
 (button3["text"] == 'X' and button5["text"] == 'X' and button7["text"] == 'X')
 ):
 tkinter.messagebox.showinfo("Winner : X", "You have just won a game")

elif(
 (button1["teOt"] == 'O' and button2["teOt"] == 'O' and button3["teOt"] == 'O') or
 (button4["teOt"] == 'O' and button5["teOt"] == 'O' and button6["teOt"] == 'O') or
 (button7["teOt"] == 'O' and button8["teOt"] == 'O' and button9["teOt"] == 'O') or
 (button1["teOt"] == 'O' and button4["teOt"] == 'O' and button7["teOt"] == 'O') or
 (button2["teOt"] == 'O' and button5["teOt"] == 'O' and button8["teOt"] == 'O') or
 (button3["teOt"] == 'O' and button6["teOt"] == 'O' and button9["teOt"] == 'O') or
 (button1["teOt"] == 'O' and button5["teOt"] == 'O' and button9["teOt"] == 'O') or
 (button3["teOt"] == 'O' and button5["teOt"] == 'O' and button7["teOt"] == 'O')
 ):
 tkinter.messageboO.showinfo("Winner : O", "You have just won a game")

buttons = StringVar()
button1 = Button(mainWin,text=" ",font = ('Times 26 bold'), height=4, width=8,command=lambda:checker(button1))
button1.grid(row=1,column=0,sticky=S+N+E+W)

button2 = Button(mainWin,text=" ",font = ('Times 26 bold'), height=4, width=8,command=lambda:checker(button2))
button2.grid(row=1,column=1,sticky=S+N+E+W)

button3 = Button(mainWin,text=" ",font = ('Times 26 bold'), height=4, width=8,command=lambda:checker(button3))
button3.grid(row=1,column=2,sticky=S+N+E+W)

button4 = Button(mainWin,text=" ",font = ('Times 26 bold'), height=4, width=8,command=lambda:checker(button4))
button4.grid(row=2,column=0,sticky=S+N+E+W)

button5 = Button(mainWin,text=" ",font = ('Times 26 bold'), height=4, width=8,command=lambda:checker(button5))
button5.grid(row=2,column=1,sticky=S+N+E+W)

button6 = Button(mainWin,text=" ",font = ('Times 26 bold'), height=4, width=8,command=lambda:checker(button6))
button6.grid(row=2,column=2,sticky=S+N+E+W)

button7 = Button(mainWin,text=" ",font = ('Times 26 bold'), height=4, width=8,command=lambda:checker(button7))
button7.grid(row=3,column=0,sticky=S+N+E+W)

button8 = Button(mainWin,text=" ",font = ('Times 26 bold'), height=4, width=8,command=lambda:checker(button8))
button8.grid(row=3,column=1,sticky=S+N+E+W)

button9 = Button(mainWin,text=" ",font = ('Times 26 bold'), height=4, width=8,command=lambda:checker(button9))
button9.grid(row=3,column=2,sticky=S+N+E+W)

mainWin.mainloop()

py

#Inheritence and Modularity in Python

#------------------testing.py----------------------------
class Test:
    a = 10
    b = 0
    def __init__(self, x, y):
        self.a = x
        self.b = y
    def sum(self):
        return self.a + self.b
    def diff(self):
        return abs(self.a - self.b)
    def mult(self):
        return self.a*self.b

#---------------end of FileA.py------------------------
#------------------FileB.py----------------------------
from testing import Test

testObj = Test(100,200)

class extra(Test):
 pass

def main():
 print(testObj.sum())
 exobj = extra(20,50)
 print('{} + {} = {}'.format(exobj.a,exobj.b,exobj.sum()))


if 'name' == main():
 main()

#Practising Class

import random
import pygame

STARTING_BLUE_BLOBS = 10
STARTING_RED_BLOBS = 10

WIDTH = 800
HEIGHT = 600
WHITE = (255,255,255)
BLACK = (0,0,0)
BLUE = (0,0,255)
RED = (255,0,0)
GREEN = (0,255,00)

game_display = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Blob World')
clock = pygame.time.Clock()



class Blob:
    def __init__(self,color):
        self.x = random.randrange(0 ,WIDTH)
        self.y = random.randrange(0,HEIGHT)
        self.size = random.randrange(10,20)
        self.color = color

    def move(self):
        self.move_x = random.randrange(-1,2)
        self.move_y = random.randrange(-1,2)
        self.x += self.move_x
        self.y += self.move_y

        if self.x < 0: self.x = 0
        elif self.x >WIDTH : self.x = WIDTH

        if self.y < 0: self.y = 0
        elif self.y > HEIGHT: self.y = HEIGHT


def draw_environment(blob_list):
    game_display.fill(WHITE)
    for blob_dict in blob_list:
        for blob_id in blob_dict:
            blob = blob_dict[blob_id]
            pygame.draw.circle(game_display,blob.color,[blob.x,blob.y],blob.size)
            blob.move()
    pygame.display.update()


def main():
    blue_blobs = dict(enumerate([Blob(BLUE) for i in range(STARTING_BLUE_BLOBS)]))
    red_blobs = dict(enumerate([Blob(RED) for i in range(STARTING_RED_BLOBS)]))
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        draw_environment([blue_blobs,red_blobs])
        clock.tick(60)

if __name__ == '__main__':
    main()


blob

#Understanding Methods:

#NOTE : A method is same as function except it is used within a Class and does not necessarily return values

class Account:
    '''Simple  account class with balance'''
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
        print('Account created for ' +self.name)
    def deposit(self, amount) :
        if amount >= 0:
            self.balance +=amount

    def withdraw(self, amount):
        if 0< amount <= self.balance:
            self.balance -= amount
            print('{} is withdrwan'.format(amount))
            self.show_balance()
        else:
            print('Not allowed')
            self.show_balance()

    def show_balance(self):
        print('balance is {}'.format(self.balance))

if __name__ == '__main__':
    saurav = Account('Saurav',0)
    saurav.show_balance()

    saurav.deposit(1000)
    saurav.show_balance()

    x = int(input('Enter value : '))
    saurav.withdraw(x)

#Class Attributes and Instance attributes

class Kettle(object):
    power_source = 'electricity'
    def __init__(self, make, price):
        self.make = make
        self.price = price
        self.ON = False

    def swith_on(self):
        self.ON = True

kenwood = Kettle('kenwood',9.99)
hamilton = Kettle('hamilton',14.55)
print('{} kettle cost {} and {} kettle cost {}'.format(kenwood.make,kenwood.price,hamilton.make,hamilton.price))

print('Models : {0.make} costs {0.price} and {1.make} costs {1.price}'.format(kenwood,hamilton))

print(hamilton.ON)
hamilton.swith_on()
print(hamilton.ON)

print(Kettle.swith_on(kenwood))
#why none

kenwood.power = 1.5
print(kenwood.power)
#Note : though we do not have any variable named POWER in class kettle,
# still we can perform the above declaration/assignment as python supports dynamic programming

#print(hamilton.power)  This is not possible as we have not assigned any value to hamilton.powe
hamilton.power = 12
print(hamilton.power)
#But this is possible as we have done assignment for hamilton.power

print('{} : for Kettle class -------- {} : for hamilton -------- {} : for kenwood'.format(Kettle.power_source,hamilton.power_source,kenwood.power_source))
hamilton.power_source = 'heat'
print('{} : for Kettle class -------- {} : for hamilton -------- {} : for kenwood'.format(Kettle.power_source,hamilton.power_source,kenwood.power_source))

Kettle.power_source = 'ATOMIC'

print('{} : for Kettle class -------- {} : for hamilton -------- {} : for kenwood'.format(Kettle.power_source,hamilton.power_source,kenwood.power_source))
#Note : Class Attributes can be used as a static variable only if it is accesses as ClassName.VariableName (Like Kettle.power_source) in our case.
#if the attribute is modified by any of the instance, only attribute value for that instance is modified.
#even if you modify the class attribute to a new value, instance attribute value is kept the same. Like Heat as power source for hamilton in our case.
#Though we modified the Class attribute to charcoal but instance attribute(if modified) is lept as 'heat' and not modified
print('-'*100)
print(Kettle.__dict__)
print(kenwood.__dict__)
print(hamilton.__dict__)
#while accessing values, an instance first checks in its own instance dictionary, if not found it uses values of its Class Attributes
#As instance of hamilton has power_source = heat, hence it will not take values from its class Class Attributes. Whereas, kenwood will take power_source values from its class attributes

#UNDERSTANDING CLASSES

class Kettle(object):
    def __init__(self,make,price):
        self.make = make
        self.price = price
        self.ON = False

kenwood = Kettle('kenwood',9.99)
hamilton = Kettle('hamilton',14.55)
print('{} kettle cost {} and {} kettle cost {}'.format(kenwood.make,kenwood.price,hamilton.make,hamilton.price))

print(type(kenwood))
print(type(hamilton))

if type(kenwood) == type(hamilton):
    print('They are instance of same class, hence have similar features with different attributes')
else:
    print('Aha!!! are you sure what you wanna ask')

#Installing PyGame

Navigate to your directory of Python-Scripts and run the command as below

D:\Downloads\Softwares\python download\python-installed\Scripts>pip install pygame
Collecting pygame
 Downloading https://files.pythonhosted.org/packages/e4/1f/23e1620de98d3eff46cbd470dc9465c5b860c06d37787781d756135b512b/pygame-1.9.3-cp36-cp36m-win_amd64.whl (4.2MB)
 100% |████████████████████████████████| 4.2MB 819kB/s
Installing collected packages: pygame
Successfully installed pygame-1.9.3

D:\Downloads\Softwares\python download\python-installed\Scripts>

#A Simple Web Spider

from multiprocessing import Pool
import bs4 as bs
import random
import requests
import string

def randomUrl():
    rand = random.randint(2,10)
    websiteName = ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(4))
    url = ''.join(['http://www.',websiteName,'.com'])
    return url

def handleLocalLinks(url,link):
    if link.startswith('/'):
        return ''.join([url,link])
    else:
        return link

def get_links(url):
    try:
        resp = requests.get(url)
        soup = bs.BeautifulSoup(resp.text, 'lxml')
        body = soup.body
        links = [link.get('href') for link in body.find_all('a')]
        links = [handleLocalLinks(url,link) for link in links]
        links = [str(link.encode('ascii')) for link in links]
        return links

    except TypeError as TE:
        print(TE)
        print('Type error !!! May be we are trying to iterate over an empty list')
        return []
    except IndexError as IE:
        print(IE)
        print('Index Error !!! May be we are trying to iterate over emplty list')
        return []
    except AttributeError as AE:
        print(AE)
        print('Attribute Error!!! May be we are missing attrinutes in our search')
        return []
    except Exception as E:
        print(str(E))
        #log this error in a file
        return []

def main():
    noOfProcessors = 50
    p = Pool(processes=noOfProcessors)
    parse_us = [randomUrl() for _ in range(noOfProcessors)]
    data = p.map(get_links, [link for link in parse_us])
    data = [url for url_list in data for url in url_list]
    p.close()

    with open('urls.txt','w') as f:
        f.write(str(data))

if __name__ == '__main__':
    main()

#Generating Random website names of length 1-10

import random
import string

def random_starting_url():
    rand = random.randint(1,10)
    websiteName= ''.join(random.SystemRandom().choice(string.ascii_lowercase) for i in range(rand))
    url = ''.join(['http://www.',websiteName,'.com'])
    return url

url = random_starting_url()
print(url)

Installing BautifulSoup

https://www.crummy.com/software/BeautifulSoup/bs4/download/
download latest version. This will give you a tar.gz zip file. Unzip using 7zip/WinZip,etc and navigate to find setup.py file
Now 
cmdLine>setup.py install
let it complete :  Done

#Understanding Pool and Processes and returning values back to calling process

#pool allows us to create a pool of process workers
from multiprocessing import Pool

def job(num):
    print('i m in job func - {}'.format(num))
    return num

if __name__ =='__main__':
    p = Pool(processes=10)
    #here we are specifying 10 process, Start Task manager to verify this
    data = p.map(job,'Hello')
    #instead of 'Hello' string you can use any iterable, even generators
    #You can not pass the arguemnt through parantheseis like regular function,
    # Here you have to use above method to pass argument
    p.close()
    print(type(data))
    #The output of the p.map() is stored in a list
    print('I m in main - {}'.format(data))

#Simple Multiprocessing

#In general if we do not use Multiprocessing we can only use 16% of the CPU by a Python program
# Due to GIL(Global Interpreter lock) : meant for memory management locks
# as many functionality depends on GIL value, we are not suppose to increase this,
# Hence Multiprocessing helps using CPU-cores more optimally

import multiprocessing
x=0
def justPrinting(num):
    print('I am the Child Thread!!! ', num)

print('Main thread !!!', x+1)
if __name__ == '__main__':
    for i in range(200):
        Th1 = multiprocessing.Process(target=justPrinting, args=(i,))
        #If you want to pass arguments in the process you can do it directly as you do in other methods
        # or you can use 'args' key work.
        # If you are passing only one argument make sure to end it with a comma ','
        Th1.start()
        # Th1.join()

#Breaking ATM-PIN using Generators – Shorter/Smarter Code

#Note Only the length of the code is reduced. The number of execution remains the same
ATM_PIN = (4,2,0,6)

def combo_gen():
    for p1 in range(10):
        for p2 in range(10):
            for p3 in range(10):
                for p4 in range(10):
                    yield (p1,p2,p3,p4)

count =0
for (a,b,c,d) in combo_gen():
    count += 1
    if(a,b,c,d) == ATM_PIN:
        print('Cracked your Lock : {}'.format((a,b,c,d)))
        break

print('It took me {} chances to crack it'.format(count))

#Breaking ATM-PIN by Brute-force : Stupid Long Way

print('-'*40)
ATM_PIN = (9,1,0,2)
count =0
flag = False
for p1 in range(10):
    for p2 in range(10):
        if flag == True:
            break
        for p3 in range(10):
            if flag == True:
                break
            for p4 in range(10):
                if flag == True:
                    break
                count += 1
                if (p1,p2,p3,p4) == ATM_PIN:
                    print('Cracked your Lock : {}'.format((p1,p2,p3,p4)))
                    flag = True
                    if flag == True:
                        break

print('It took me {} chances to crack it'.format(count))

#Zip Function

#The zip function takes elements from multiple enumerator and pack them into 1. So that they share same index value

x = [1,2,3,6,11]
y = [65,32,6,61,2]
z = ['a','bc','xyz','pqr','st']

for a,b,c in zip(x,y,z):
    print('{:>2} {:>2} {:>3}'.format(a,b,c))
print('-'*20)
for i in zip(x,y,z):
    print(i)
print('-'*20)
print(list(zip(x,y,z))) #you can easily convert a zip to a list
print('-'*20)
print(dict(zip(y,z))) #you can easily convert a zip to a dictionary, but with only 2 inputs: key-value
print('-'*20)
[print(a,b,c) for a,b,c in zip(x,y,z)]
print('-'*20)
#Note: a is just a single valued variable which iterates over the zip,
# hence outside the iteration/enumeration block the value of a is the value it had at the end of the zip,
# for example - 11 in our case
# as x is list hence it as list variable

print(x)
print(a)

#Enumerators with more than one loop-variable

exList = ['left','right','up','down']
exDict = {'name':'saurav','city':'Calcutta','hobbies':'Programming'}
exTuple= 'Today','is','Sunday'
for i,j in enumerate(exList):
    print(i,j)

print('-'*10)
for i,j in enumerate(exDict):
    print(j,exDict[j])

print('-'*10)
for i,j in enumerate(exTuple):
    print(i,j)

print('----------\nUsing Method 2\n----------')
[print(i,j) for i,j in enumerate(exList)]
print('-'*10)
[print(j,exDict[j]) for i,j in enumerate(exDict)]
print('-'*10)
[print(i,j) for i,j in enumerate(exTuple)]

#Exploring generator-nesting

input_list = [5,43,52,10,55,76,78,95,11,105]

def div_by_five(num):
    if num%5==0:
        return True
    else:
        return False

xyz = (i for i in input_list if div_by_five(i))

abc = []
for i in input_list:
    if div_by_five(i):
        abc.append(i)

for x in xyz:
    print(x)

[print(i) for i in xyz]

print('-'*20)

[[print('{:2} X {:2} is {:2}'.format(j,i,j*i))for i in range(1,4)] for j in range(1,4)]
print('-'*20)
pqr = ([[(q,p) for p in range(5)]for q in range(5)])

print([i for i in range(10)])
print('-'*20)
print([i for i in pqr])

#Exploring Difference between Generator and Memory variable

import time
x1 = time.time()
xyz = [i for i in range(500000)]
x2 = time.time()
print('List completed in {} seconds'.format(x2-x1))
xyz = (i for i in range(500000))
x3 = time.time()
print('Generator completed in {} seconds'.format(x3-x2))

#Exploring ARGPARSE through cmd Line

import argparse
import sys
import os

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--x',type=float,default=1.0,
                        help='What is the first number ?')
    parser.add_argument('--y',type=float,default=1.0,
                        help='What is the second number ?')
    parser.add_argument('--operation',type=str,default='sum',
                        help='Available Operation ? sum, subs, mult, div')
    args = parser.parse_args()
    sys.stdout.write(str(calculator(args)))

def calculator(args):
    op = args.operation
    a = args.x
    b = args.y

    if op == 'sum':
        return a+b
    elif op == 'subs':
        return abs(a-b)
    elif op == 'mult':
        return a*b
    elif op == 'div':
        return max(a/b,b/a)
    else:
        'please type help to know more'

if __name__ == '__main__' :
    main()

#Working with Thread and Queue

import threading
from queue import Queue
import time

print_lock = threading.Lock()
def exampleJob(worker):
    time.sleep(0.5)
    with print_lock:
        print(threading.current_thread().name, worker)

def threader():
    while True:
        exampleJob(q.get())
        q.task_done()

q= Queue()

for x in range(10):
    t = threading.Thread(target=threader)
    t.daemon = True
    t.start()

start = time.time()

for worker in range(20):
    q.put(worker)

q.join()
print('Entire job took : ', time.time() - start)

#Parsing Websites with re and urllib

import urllib.request
import urllib.parse
import re

url = 'http://pythonprogramming.net'
values = {'s':'basics',
          'submit':'search'
          }
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url,data)
resp = urllib.request.urlopen(req)
respData = resp.read()

# print(respData)

paragraps = re.findall(r'<p>(.*?)</p>',str(respData))

for p in paragraps:
    print(p)

 

#REGEX

#it means identying patterns from string/inputs

regExList = '''
Identifiers:
\d any number
\D anything but a number
\s space
\S anything but a space
\w any character
\W anything but a character
. any character, except for a newline
\b the white space around the words
\. a period

Modifiers:
{1,3}   we are expecting 1-3
+       match 1 or more
?       match 0 1
*       match 0 or more
$       match the end of the string
^       match the beginning of the String
|       either/or
[]      range or 'variance' example [A-Za-z0-9]
{x}     expecting 'x' amount

White Spce Characters
\n      new line
\s      space
\t      tab
\e      escape
\f      form feed
\r      return

DONT FORGET!
. + * ? [] $ ^ () {} \ \ 
'''
print(regExList)

import re
exampleString ='''
Jessica is 15 years old, and Daniel is 27 years old.
Edward is 97, and hos grandfather, Oscar, is 102.
'''
#Now let us run REGEX in exampleString

ages = re.findall(r'\d{1,3}',exampleString)
names = re.findall(r'[A-Z][a-z]*',exampleString)

print(ages)
print(names)

for i in range(0,len(ages)):
    print('{} is {} years old'.format(names[i],ages[i]))

 

#Exploring urllib and user-agent headers

import urllib.request
import urllib.parse

try:
    x = urllib.request.urlopen('https://www.google.co.in/search?q=testing')
    print(x.read)
except Exception as myExcp:
    print(str(myExcp))

#The Above method may forbid you from visiting few sites, as these website block users based on their User-Agent/Browser-Agent value
try:
    url='https://www.google.co.in/search?q=testing'
    headers={}
    headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0'
    req = urllib.request.Request(url,headers=headers)
    resp=urllib.request.urlopen(req)
    respData = resp.read()

    saveFile = open('withHeders.txt','w')
    saveFile.write(str(respData))
    saveFile.close()

except Exception as e:
    print(str(e))

#Exploring urllib

import urllib.request
import urllib.parse

# x = urllib.request.urlopen('https://www.pythonprogramming.net/search/?q=basic')
# print(x.read)

pref = 'http://'
myInput = 'pythonprogramming.net'
url = pref+myInput
values = {'':'search',
          'q' : 'basic'
          }
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url,data)
resp = urllib.request.urlopen(req)
respData = resp.read()

print(respData)

 

#Working With Exception handling

import csv

glcodes = []
maingroups = []

with open('maingroup_master.csv', 'r') as myFileLink:
    readComma = csv.reader(myFileLink,delimiter = ',')
    for row in readComma:
        glcode = row[0]
        maingroup = row[1]

        glcodes.append(glcode)
        maingroups.append(maingroup)

print(glcodes)
print(maingroups)

try:
    whatCode = input('Enter Code to see maingroup')
    CodeIndex = glcodes.index(whatCode)
    print(maingroups[CodeIndex])
#except Exception, excp :       this is used in python 2.x
except Exception as exps:
    print(exps)

#Working with CSV files

import csv

glcodes = []
maingroups = []

with open('maingroup_master.csv', 'r') as myFileLink:
    readComma = csv.reader(myFileLink,delimiter = ',')
    for row in readComma:
        glcode = row[0]
        maingroup = row[1]

        glcodes.append(glcode)
        maingroups.append(maingroup)

print(glcodes)
print(maingroups)

whatCode = input('Enter Code to see maingroup')
CodeIndex = glcodes.index(whatCode)
print(maingroups[CodeIndex])

 

#Exploring Module Functionality

#Make sure both the filenames are under same root directory path

#Filename = ScratchPad.py
def ex(data):
    print(data)
def sum(a,b):
    return a+b
-----------------------------------
#Filename = extraScratchPad.py
import ScratchPad
ScratchPad.ex('Hello Python')
x = ScratchPad.sum(21,3)

print('X = ',x)

 

#Importing Modules in Python

from statistics import mean as m,variance as v, stdev as sd

exm = [1,2,43,5,1,7,6.9,7,9,1]
print(m(exm))
print(sd(exm))
print(v(exm))

#Exploring Functions and tkinter

from tkinter import *

def parabola(myCanvas, size):
    for x in range(-size,size):
        y = x*x/size    # /100 though is mathematically incorrect, but we are doing this just to fit in the grapgh area
        plot(myCanvas,x,-y)
        # -y because conventional python tkinter values goes positive from up to down, but co-ordinate system acts just the opposite

def draw_axes(myCanvas):
    myCanvas.update()
    x_origin = myCanvas.winfo_width()/2
    y_origin = myCanvas.winfo_height()/2
    myCanvas.configure(scrollregion=(-x_origin, -y_origin , x_origin , y_origin))
    myCanvas.create_line(-x_origin,0,x_origin,0,fill='red')
    myCanvas.create_line(0,-y_origin,0,y_origin,fill='purple')

def plot(myCanvas, x, y):
    myCanvas.create_line(x,y, x+1,y+1, fill='blue')

mainWin = Tk()
mainWin.geometry('640x480')
mainWin.title('The parabola')

myCanvas = Canvas(mainWin,width=600,height=600)
myCanvas.grid(row=0,column=0)
draw_axes(myCanvas)


parabola(myCanvas, 100)
parabola(myCanvas, 200)



mainWin.mainloop()
parabola

from tkinter import *

def parabola(x):
    y = x*x/100    # /100 though is mathematically incorrect, but we are doing this just to fit in the grapgh area
    return y

def draw_axes(myCanvas):
    myCanvas.update()
    x_origin = myCanvas.winfo_width()/2
    y_origin = myCanvas.winfo_height()/2
    myCanvas.configure(scrollregion=(-x_origin, -y_origin , x_origin , y_origin))
    myCanvas.create_line(-x_origin,0,x_origin,0,fill='red')
    myCanvas.create_line(0,-y_origin,0,y_origin,fill='purple')

def plot(myCanvas, x, y):
    myCanvas.create_line(x,y, x+1,y+1, fill='blue')

mainWin = Tk()
mainWin.geometry('640x480')
mainWin.title('The parabola')

myCanvas = Canvas(mainWin,width=300,height=600)
myCanvas.grid(row=0,column=0)
draw_axes(myCanvas)

myCanvas2 = Canvas(mainWin,width=300,height=600,background='white')
myCanvas2.grid(row=0,column=1)
draw_axes(myCanvas2)


for x in range(-500,500):
    y=parabola(x)
    plot(myCanvas,x,-y)
    plot(myCanvas2,x,y)
    # -y because conventional python tkinter values goes positive from up to down, but co-ordinate system acts just the opposite

mainWin.mainloop()

from tkinter import *

def parabola(x):
    y = x*x/100    # /100 though is mathematically incorrect, but we are doing this just to fit in the grapgh area
    return y

def draw_axes(myCanvas):
    myCanvas.update()
    x_origin = myCanvas.winfo_width()/2
    y_origin = myCanvas.winfo_height()/2
    myCanvas.configure(scrollregion=(-x_origin, -y_origin , x_origin , y_origin))
    myCanvas.create_line(-x_origin,0,x_origin,0,fill='black')
    myCanvas.create_line(0,-y_origin,0,y_origin,fill='black')

def plot(myCanvas, x, y):
    myCanvas.create_line(x,y,x+1,y+1,fill='red')

mainWin = Tk()
mainWin.geometry('640x480')
mainWin.title('The parabola')
myCanvas = Canvas(mainWin,width=600,height=600)
myCanvas.pack()
draw_axes(myCanvas)

for x in range(-500,500):
    y=parabola(x)
    plot(myCanvas,x,-y)
    # -y because conventional python tkinter values goes positive from up to down, but co-ordinate system acts just the opposite

mainWin.mainloop()

parabola

#Exploring tkinter for Window/Scene creation

try:
    import tkinter
except ImportError:
    import Tkinter as tkinter
#Python 2 and below uses 'Tkinter' instead of 'tkinter'
import os

myWindow = tkinter.Tk()
myWindow.title('Grid Demo')
myWindow.geometry('640x480-500-200') #horizontalLength-verticalLength spacing: -500 and -200 are position

label1 = tkinter.Label(myWindow,text='[tkinter - Grid Demo]')
label1.grid(row=0,column=0,columnspan=3)


myWindow.columnconfigure(0,weight=1)
myWindow.columnconfigure(1,weight=1)
myWindow.columnconfigure(2,weight=3)
myWindow.columnconfigure(3,weight=3)
myWindow.columnconfigure(4,weight=3)

myWindow.rowconfigure(0,weight=1)
myWindow.rowconfigure(1,weight=10)
myWindow.rowconfigure(2,weight=1)
myWindow.rowconfigure(3,weight=3)
myWindow.rowconfigure(4,weight=3)

myFileList = tkinter.Listbox(myWindow)
myFileList.grid(row=1, column=0, sticky='nsew', rowspan=2)
myFileList.config(border=2, relief='sunken') #flat, solid, groove, raised, solid, sunken ,etc

for zone in os.listdir('C:\\'):
    myFileList.insert(tkinter.END,zone)
myListScroll = tkinter.Scrollbar(myWindow, orient=tkinter.VERTICAL, command=myFileList.yview())
myListScroll.grid(row=1,column=1,rowspan=2,sticky='nsw')
#As we have filelist and Scrollbar ... its time to link them
myFileList['yscrollcommand']=myListScroll.set

#frame for the raadio buttons
myOptionFrame = tkinter.LabelFrame(myWindow, text='file Details')
myOptionFrame.grid(row=1,column=2,sticky='ne')

myRBvalue = tkinter.IntVar()
myRBvalue.set(3)
radio1 = tkinter.Radiobutton(myOptionFrame,text='FileName',value=1,variable = myRBvalue)
radio2 = tkinter.Radiobutton(myOptionFrame,text='PATH',value=2,variable = myRBvalue)
radio3 = tkinter.Radiobutton(myOptionFrame,text='TimeStamo',value=3,variable = myRBvalue)

radio1.grid(row=0,column=0,sticky='w')
radio2.grid(row=1,column=0,sticky='w')
radio3.grid(row=2,column=0,sticky='w')

#Widget for TextPad Area
myResultLabel = tkinter.Label(myWindow,text='Result-')
myResultLabel.grid(row=2,column=2,sticky='nw')

myResulytText = tkinter.Entry(myWindow)
myResulytText.grid(row=2,column=2,sticky='sw')

#widget for time spinners
myTimeFrame = tkinter.LabelFrame(myWindow,text='Time')
myTimeFrame.grid(row=3,column=0,sticky='ewn')
myTimeFrame['padx'] = 36

#TimeSpinners
myHourSpinner = tkinter.Spinbox(myTimeFrame,width=2,values=tuple(range(0,24)))
myMinSpinner = tkinter.Spinbox(myTimeFrame,width=2,from_=0, to=59)  #you can even use range instead of from and to, both does the same things, but remember from_ and not from and to as it is
mySecSpinner = tkinter.Spinbox(myTimeFrame,width=2,from_=0, to=59)

myHourSpinner.grid(row=0,column=0)
tkinter.Label(myTimeFrame,text=' : ').grid(row=0,column=1)
myMinSpinner.grid(row=0,column=2)
tkinter.Label(myTimeFrame,text=' : ').grid(row=0,column=3)
mySecSpinner.grid(row=0,column=4)

#Day Spinner Frame
myDayFrame = tkinter.Frame(myWindow)
myDayFrame.grid(row=4,column=0,sticky='ewn')
#date labes
myDayLabel = tkinter.Label(myDayFrame,text='Day')
myMonthLabel = tkinter.Label(myDayFrame,text='Month')
myYearLabel = tkinter.Label(myDayFrame,text='Year')
myDayLabel.grid(row=0,column=0,sticky='w')
myMonthLabel.grid(row=0,column=1,sticky='w')
myYearLabel.grid(row=0,column=2,sticky='w')

#DateSpinners
monthTuple = 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
myDaySpinner = tkinter.Spinbox(myDayFrame,width=5,from_=1,to=31)
myMonthSpinner = tkinter.Spinbox(myDayFrame,width=5,values = monthTuple)
myYearSpinner = tkinter.Spinbox(myDayFrame,width=5,from_=2000,to=2099)

myDaySpinner.grid(row=4,column=0,sticky='es')
myMonthSpinner.grid(row=4,column=1,sticky='es')
myYearSpinner.grid(row=4,column=2,sticky='es')

#Buttons
okButton = tkinter.Button(myWindow,text='OK')
cancelButton = tkinter.Button(myWindow,text='Cancel',command=myWindow.quit)

okButton.grid(row=4,column=3,sticky='w')
cancelButton.grid(row=4,column=3,sticky='e')


myWindow.mainloop()

OUTPUT:
TkinterGrid

#Exploring tkinter with grid geometry manager

import tkinter

myWindow = tkinter.Tk()
myWindow.title('This is myTitle')

myLeftFrame = tkinter.Frame(myWindow)
myRightFrame = tkinter.Frame(myWindow)

label1 = tkinter.Label(myWindow,text='This is myLabel1')
label2 = tkinter.Label(myWindow,text='This is myLabel2')
label3 = tkinter.Label(myWindow,text='This is myLabel3')

button1 = tkinter.Button(myRightFrame,text='This is button1')
button2 = tkinter.Button(myRightFrame,text='This is button2')
button3 = tkinter.Button(myWindow,text='This is button3')

myCanvas = tkinter.Canvas(myLeftFrame, relief = 'raised', borderwidth=1)

label1.grid(row=0,column=0)
label2.grid(row=3,column=1)
label3.grid(row=2,column=2)

myLeftFrame.grid(row=1,column=1)
myRightFrame.grid(row=4,column=4)

button1.grid(row=2,column=0)
button2.grid(row=1,column=2)
button3.grid(row=3,column=2)

myCanvas.grid(row=0,column=5)

myLeftFrame.config(relief='sunken',borderwidth=1)
myRightFrame.config(relief='sunken',borderwidth=1)
myLeftFrame.grid(sticky='ns')

myWindow.mainloop()

#Exploring Tkinter with pack geometry manager

import tkinter

# tkinter._test()
# print(tkinter.TkVersion)
# print(tkinter.TclVersion)

firstWindow = tkinter.Tk()
firstWindow.title('The Title is here')
firstWindow.geometry('460x480')
label = tkinter.Label(firstWindow, text='The Label is here')
label.pack(side='top')

canvas = tkinter.Canvas(firstWindow,relief='raised', borderwidth=1)
canvas.pack(side='left',fill=tkinter.Y)

#for X it does not work the same way like 'Y'. You have to include 'expand=True' if we use side = 'left'
# but if you use side = 'top', 'X' can be used directly but for 'Y' you have to use expand=True parameter
# canvas.pack(side='left',fill=tkinter.X,expand=True)
# The concept is based on preference chosen by 'side'... if you choose horizontal - left/right the Y can be directly used but not X. Similarly for vartical X cab be directly used but not 'Y'
# if you use 'BOTH'. then also you have to use expand=True accordingly

leftFrame = tkinter.Frame(firstWindow)
leftFrame.pack(side='left',anchor='n',fill=tkinter.Y,expand=False)

rightFrame = tkinter.Frame(firstWindow)
rightFrame.pack(side='right',anchor='e',fill=tkinter.Y,expand=False)


button1 = tkinter.Button(firstWindow,text='This is Button1')
button2 = tkinter.Button(firstWindow,text='This is Button2')
button3 = tkinter.Button(firstWindow,text='This is Button3')
button4 = tkinter.Button(rightFrame,text='This is Button4')
button5 = tkinter.Button(firstWindow,text='This is Button5')
button6 = tkinter.Button(leftFrame,text='This is Button6')
button1.pack(side='left')
button2.pack(side='top')
button3.pack(side='right')
button4.pack(side='left',anchor='sw')
button5.pack(side='top',anchor='s')
button6.pack(side='right',anchor='e')

#you can skip anchor tag if you want to use any Button/Label/Etc in Frames/Etc

firstWindow.mainloop()

#TIMEZONES

import pytz
import datetime

withTZ = {}
withoutTZ = {}
for x in sorted(pytz.country_names):
 #print('{} : {} : {}'.format(x,pytz.country_names[x],pytz.country_timezones.get(x)))
 if pytz.country_timezones.get(x) == None:
 # print('{} name is {}'.format(x,pytz.country_names[x]))
 # print(pytz.country_names(x))
 withoutTZ[x] = pytz.country_timezones.get(x)
 else:
 withTZ[x] = pytz.country_timezones.get(x)

print('-'*40)
for i in withoutTZ:
 print('{} is NONE'.format(i))

print('-'*40)
for i in withTZ:
 print('{} is {}'.format(i,withTZ[i]))

#USING TURTLE to CREATE PATTERN

from turtle import circle, done, left, right

for i in range(12):
 circle(75)
 left(30)
done()

#Appending objects to a list in the shelve

#Use of temporary variable and assignment for updating

import shelve

egg_toast = ['egg', 'Butter' , 'bread']
corn_flakes = ['corn_flakes','milk']
sandwich = ['vegies','bread','butter','spice','ketchup']

with shelve.open('Breakfast') as shelveLink:
    shelveLink['first'] = egg_toast
    shelveLink['second'] = corn_flakes
    shelveLink['third'] = sandwich

with shelve.open('Breakfast') as shelveRead:
    shelveRead['fifth'] = 'Hello World'
    shelveRead['extra'] = 'This task is getting lengthy'

sr = shelve.open('Breakfast')
tempList = sr['first']
tempList.append('peanuts')

#we need to use a tempList to append things because, Shelve does not give us a file, it load the file into memory, we read from memory
# though if you
# sr['first'].append('pea nuts')
#does not give any warning/error but it does not write back to the file
#to write back to the file we have to use assignment operator only
#NOTE: you can also include WRITEBACK=TRUE during shelve open and thus you can directly write back to memory without the use of any temporary variable as here
#You can also use sync() method to clear the memory

sr['first'] = tempList

for i in sr:
    print('{} is {} '.format(i,sr[i]))

#ACCESSING SHELVES ITEMS,VALUES AND KEYS

import shelve
fruitNames = shelve.open('ShelveMethod1')
print('-'*40)
for i in fruitNames.items():
    print(i)
print('-'*40)
for v in fruitNames.values():
    print(v)
print('-'*40)
for k in fruitNames.keys():
    print(k)
print('-'*40)

#Operating on Shelve

#Method1
import shelve
#Step1 lets create a shelve, Its a kind of Dictionary saved in a DB file
with shelve.open('ShelveMethod1') as fruit:
    fruit['first'] = 'Orange is tangy'
    fruit['second'] = 'Mango is sweet'
    fruit['third'] = 'lemons are good for lemonades'
    fruit['fourth'] = 'Grapes are for fox'
    fruit['fifth'] = 'Adam ate that apple'

    print(fruit['first'])

# Step2 lets open the Shelve now, You can comment off the code above

fruitName = shelve.open('ShelveMethod1')

for i in fruitName:
    print('{} Fruits is {}'.format(i,fruitName[i]))

fruitName.close() 
#You can also use 'with shelve.open('ShelveMethod1') 
# as 
# fruit as fruitName = shelve.open('ShelveMethod1')'
#They both mean the same thing
#That will be you Method2
---------------------------------------------
#NOTE : avoid keeping name of the file same as any of the import package you wish to include this may create issue
#A shelve is basically a dictionary which is instead of storing in memory we store in a persistent file/DB
#all operations/methods of dictiony are valid for shelve
#NOTE : KEY of the shelve can only be a STRING, where as in dictionry it can be any immutable object like tuple or anything
#the underlying file or DB neing used depends on your python engine

import shelve

with shelve.open('shelveFile') as shelveLink:
    shelveLink['first'] = 'Orange is Tangy'
    shelveLink['second'] = 'Mango is sweet'
    shelveLink['third'] = 'Grapes are in bunch'
    shelveLink['four'] = 'Lemon taste sour'
    shelveLink['Apple'] = 'Adam ate this apple'

# You can comment-off code above and check code below
shelveReading = shelve.open('shelveFile')
shelveReading['fifth'] = 'Apple is good for health'
shelveReading['extra'] = 'I am confused here'
shelveReading

for i in shelveReading:
    print('{} is {}'.format(i, shelveReading[i]))

———————————————————-

#OPERATING ON PICKLE

import pickle
myTuple = 'Saurav','Gupta','Male', (
                                      ('Country' , 'Inida'),
                                      ('State','West Bengal'),
                                      ('City','Kolkata')
                                  )
odd = range(1,10,2)
even = range(2,10,2)
myNum = 3123

with open('PickleFile.pickle','wb') as pickleLink:
    pickle.dump(myTuple,pickleLink,protocol=pickle.HIGHEST_PROTOCOL)
    pickle.dump(odd,pickleLink,protocol=pickle.DEFAULT_PROTOCOL)
    pickle.dump(even,pickleLink,protocol=0)
    pickle.dump(myNum,pickleLink,protocol=3)
# Now You can Comment-Off the code above to check if Pickle file written can be read or not

with open('PickleFile.pickle','rb') as pickleReading:
    myTuple2 = pickle.load(pickleReading)
    odd2 = pickle.load(pickleReading)
    even2 = pickle.load(pickleReading)
    myNum2 = pickle.load(pickleReading)
#Order of load must be same as order of dump

fName , lName, gender, Address = myTuple2
country, state, city = Address

print(fName)
print(city)
print(Address)
print(fName)
print(myNum2)
print(odd2)
for i in odd2:
    print(i,end=' ')

 

#Search words in the document

myReading = open('C:\\Users\\SouravG\\Desktop\\testing2.txt','r')
print('='*100)
myReading2 = open('D:\\sample.txt','r')

lineCount =0
myWord = input('Word to search : ')
myFlag = 0
for currLine in myReading:
    lineCount += 1
    if myWord.lower() in currLine.lower():
        print("{} - {}".format(lineCount,currLine))
        myFlag += 1

if myFlag == 0:
    print('Not Found')
else:
    print('You have {} matches'.format(myFlag))

myReading.close()


# print('='*100)
# print('It is same as example above')
# print('By using "WITH" keyword we dont have to worry about closing the file explicitly')

myWord = input('Enter Your Word : ')
count = 0
lineNum =0
with open('C:\\Users\\SouravG\\Desktop\\testing2.txt','r') as myReading:
    for currLine in myReading:
        lineNum +=1
        if myWord.lower() in currLine.lower():
            count += 1
            print('{} - {}'.format(lineNum,currLine))
if count==0:
    print('Not found')
else:
    print('{} matches found'.format(count))
#Direction Game explaining use of Dictionary, list and 
#using Dictionary inside a list

location = {0 : 'near you computer, learning Python',
            1 : 'at End of the road',
            2 : 'at top of the hill',
            3 : 'inside a building',
            4 : 'in a valley',
            5 : 'in a forest'
            }

exits = [{"Q" : 0},
         {"Q" : 0, "W" : 2,"E" : 3, "N" : 5,"S" : 4},
         {"Q" : 0, "N" : 5},
         {"Q" : 0, "W" : 1},
         {"Q" : 0, "N" : 1,"W" : 2},
         {"Q" : 0, "S" : 1,"W" : 2}
         ]
loc = 1
while True:
    availableExist = ''
    print('YOU ARE : ', end='')
    for direction in exits[loc].keys():
        availableExist += direction +', '

    print(location[loc])

    if loc == 0:
        break

    direction = input('Avaialble exists are '+availableExist).upper()
    print()
    if direction in availableExist:
        loc = exits[loc][direction]
    else:
        print('You are not allowed there')

pyhonGame

 

# Dictionary Examples
fruitDictionary = {'apple':'red, healthy fruit',
         'mango':'yellow, sweet fruit',
         'pear' : "green, odd shaped fruit",
         'grapes' : 'small fruit, which the fox did not get'}

while True:
    fruitName = input('Enter Fruit name : ')
    if  fruitName == None:
        print('say a fruit name or type exit to exit')
    elif fruitName in fruitDictionary:
        fruitFound = fruitDictionary[fruitName]
        print(fruitFound)
    elif fruitName == 'exit':
        break
    else:
        print(fruitName+' not found')
#Printing binary without using binary convertion

myList = []
newNum = 0
myNum = int(input('Enter a number : '))

print('{:b}'.format(myNum))

while int(myNum) / 10 > 0 :
    myList.append(int(myNum %2))
    myNum /= 2

print(myList[::-1])

for i in myList[::-1]:
    print(i**2,end='')

 

# DECIMAL, BINARY, HEX and Octal
mobile = 80136,91634,70444

for k in mobile:
    print("{0:>5} : decimal , {0:>010b} : binary, {0:>010x} : hex, {0:>010o} : octal".format(k))

print('-'*10+'END HERE'+'-'*10)
print('='*50)
print('-'*10+'Some More examples'+'-'*10)

print('-'*10+'Hex Operations'+'-'*10)

hex1 = 0x2d4
hex2 = 0xf
hex3 = 0x11
# hex4 = x25
# hex4 is not allowed as it does not have prefix of '0' Zero
print(hex1)
print(hex2)
print(hex3)
print("{} in decimal ".format(hex2*hex1))
print("{:>015b} in binary".format(hex2*hex1))
print("{:>06x} in HEX".format(hex2*hex1))
print("{:>06o} in octal".format(hex2*hex1))


print('-'*10+'Octal Operations'+'-'*10)
oct1 = 0o32
oct2 = 0o7
oct3 = 0o44
# oct1 = o256
# oct4 is not allowed as it does not have prefix '0'
print(oct1)
print(oct2)
print(oct3)
# print(oct1)
print('{0:>03} in decimal'.format(oct1*oct2))
print('{0:>08b} in binary'.format(oct1*oct2))
print('{0:>04x} in Hex'.format(oct1*oct2))
print('{0:>04o} in Octal'.format(oct1*oct2))

print('-'*10+'Binary Operations'+'-'*10)
bin1 = 0b1010101
bin2 = 0b1011111
bin3 = 0b1011

print(bin1)
print(bin2)
print(bin3)

print('{0:>03} in decimal'.format(bin1*bin2))
print('{0:>08b} in binary'.format(bin1*bin2))
print('{0:>08x} in Hex'.format(bin1*bin2))
print('{0:>08o} in Octal'.format(bin1*bin2))
print('='*10 + 'Example 1' + '='*10)
myTuple = 'a','b','c'
print(myTuple)

print('a','b','c')

print(('a', 'b', 'c'))
print("Above is actually treated as a tuple ")

print('='*10 + 'Example 2' + '='*10)

myAlbum1 = "FirstTrackName","Artist1","50 Songs"
myAlbum2 = "SecondTrackName","Artist2","10 Songs"
myAlbum3 = "ThirdTrackName","Artist3","20 Songs"
myAlbum4 = "FourthTrackName","Artist4","5 Songs"
myAlbum5 = "FifthTrackName","Artist5","25 Songs"
myAlbum6 = "SixthTrackName","Artist6","40 Songs"

for i in range(0,len(myAlbum1)):
    print(myAlbum1[i])


print('-'*10 + 'Tuples are immutable' + '-'*10)
print('-'*10 + 'but we can create new with same name and drop the older version' + '-'*10)
print(myAlbum1)
# myAlbum1[1] = "Artist8"
# this is not allowed, as Tuples is non mutable
#Python allows indexing and Slicing
#based on values of the myAlbum1 before this line
#myAlbum[0],myAlbum[1],myAlbum[2] can be accessed easily
#Now these values can be mapped into a new tuple
#we are naming in myAlbum1, hence this will create a new tuple with name myAlbum1
#hence dropping previous myAlbum1

myAlbum1 = myAlbum1[0],'Artist8',myAlbum1[2]
print(myAlbum1)


print('-'*10 + 'List are Mutable' + '-'*10)
myList = ['hello', 'World', 'Python', 1991]
print(myList)
myList[1] = 'Everyone'
print(myList)

print('-'*10 + 'Mapping feature of Python is Kool' + '-'*10)
print('-'*10 + 'This is called Unpacking The tuple' + '-'*10)
track, artist, song = myAlbum1
print(track)
print('='*10 + 'Example 1' + '='*10)

week_list = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
my_days = iter(week_list)
for i in range(0,len(week_list)):
    next_day = next(my_days)
    print(next_day)

print('='*10 + 'Same as above' + '='*10)
week_list = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
for i in week_list:
    print(i)

print('='*10 + 'Example 2' + '='*10)

myStr = '1234567890'
for i in myStr:
    print(i, end='\t')

print()
print('='*10 + 'Same as above' + '='*10)
myStr = '1234567890'
for i in iter(myStr):
    print(i, end='\t')

print("\n===============Example new===============")
# no matter what higer range value you give it will use same amount of memory
evenList = list(range(0,10,2))
oddList = list(range(1,10,2))

myNum = evenList + oddList

print(sorted(myNum))
print(range(0,5,2)==range(0,7,2))

myString = 'nrael ot nuf os si nohtyP'
print(myString[::-1])

print(myString)

 

even=[2,4,6,8]
odd=[1,3,5,7,9]
number = even+odd
arranged_number = sorted(number)
print(arranged_number)
if number == arranged_number:
    print("Numbers are equal")
else:
    print("Not equal")

if arranged_number == sorted(number):
    print("But it is same NOW")
else:
    print("Still, not same")

 

myList1=['a','']
myList2=list('abc de')

print(" myList1 = {} \n myList2 = {}".format(myList1,myList2))
if myList1 == myList2 :
    print("They are equal")
print(list(' This is Strange to me'))
#Note == does content check and not reference check
# Hence even though odd and another_odd below references difference object
# but their content is same, hence they pass the '==' check

even = [2,4,6,8]
another_even = even
if even == another_even:
    print("Even and Another_Even are equal, hence they point to same object")
else:
    print("Even and Another_Even1 are not equal, hence they do not point to same object")
another_even.sort(reverse=True)
print("{} Printing Even now".format(even))

print("+++++++++++++++++++++++++++++")

odd = [1,3,5,7,9]
another_odd = list(odd)
if odd == another_odd:
    print("Odd and Another_Odd are equal, hence they point to same object")
else:
    print("Odd and Another_Odd are not equal, hence they do not point to same object")
another_odd.sort(reverse=True)
print("{} Printing Odd now".format(odd))

 

#Guessing Game
import random

randNum = random.randint(1,6)
print(randNum)
myNum =-1
while myNum != 0:
    myNum = int(input("Please enter a Number 1-10"))
    if myNum>10 or myNum <0:
        print("{} is not allowed".format(myNum))
        continue
    elif myNum-randNum>0:
        print("choose lower")
    elif myNum-randNum<0:
        print("Choose higer")
    else:
        print("Congrats you got {}".format(randNum))
        break

 

print("Palindrome".center(20,"*"))
name = input("Enter Word : ")
end = len(name) - 1
checkFlag = 0
for i in range(int(len(name)/2)):
 print(" {} and {} ".format(name[i], name[end-i]))
 if name[i].lower() == name[end-i].lower():
 continue
 else:
 checkFlag =1

if checkFlag == 0:
 print("Pallindrome")
else:
 print("No")

 

print("Fibonacci".center(20,"*"))
def fibonaci(n):
    if n <=1:
        return 1
    else:
        return fibonaci(n-2) + fibonaci(n-1)

n = int(input("Enter Number : "))
for i in range(n):
    print(fibonaci(i))

 

ipAddress = input("Enter The IP address ")
# 172.98.09.876
block = 0
seperator = 1
for elements in ipAddress:
    if elements == '.':
        print("{} block has\t{} elsements".format(seperator,block))
        seperator +=1
        block=0
    else:
        block+=1
else:
    if elements != '.':
        print("{} block has\t{} elsements".format(seperator,block))

Design a site like this with WordPress.com
Get started