#there is nothing like private or protected concept in python
#if we want to treat something as private we can use underscore '_'
# in front of the name,although it wont have any programming influence,
# but for the users understanding,also the objects starting with '_' won't be
# displayed if we use import *,although we can access using the modulename.objectname
# import blackjacktest1
# g = sorted(globals())
# for x in g:
# print(x)
# for x in globals():
# print(x)
# print (__name__)
# blackjacktest1.play()
#if you rename by prefexing any of the funtion with '_' and check the below loop will not return
#those funtions or objects
from blackjacktest1 import *
g = sorted(globals())
for x in g:
print(x)
#we can use '_' or '__' as variable name, thoughh it is not the proper way of naming variable
_ = 'a'
print(_)
__ = 'ab'
print(__)
personaldetails =('udai',23,'welcome')
name,_,__ = personaldetails
print(name,_,__)
Monday, 9 April 2018
Python - using underscore - Day 24
Sunday, 8 April 2018
Python - import challenge - blackjack game - Day 23
#this is extension of blackjack game to include the new game button and shuffle button
import tkinter as tkinter
import random
try:
import tkinter
except ImportError: # python 2
import Tkinter as tkinter
def load_images(card_images):
suits=['heart','club','diamond','spade']
face_cards=['jack','queen','king']
if tkinter.TkVersion >= 8.6:
extension = 'png'
else:
extension = 'ppm'
#for each suit retrieve the image for the cards
for suit in suits:
#first the number cards 1 to 10
for card in range(1,11):
name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
image = tkinter.PhotoImage(file = name)
card_images.append((card,image))
#next the Face Cards
for card in face_cards:
name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
image = tkinter.PhotoImage(file = name)
card_images.append((10,image))
def deal_card(frame):
#pop the next card of the top of the deck
next_card= deck.pop(0)
#if the player keeps on playing new game then all the cards will be used so
deck.append(next_card)
#add the image to the label and display the label
tkinter.Label(frame,image=next_card[1],relief = 'raised').pack(side = 'left')
#now return the cards face value
return next_card
def score_hand(hand):
# Calculate the total score of all cards in the list.
# Only one ace can have the value 11, and this will be reduce to 1 if the hand would bust.
score = 0
ace = False
for next_card in hand:
card_value = next_card[0]
if card_value == 1 and not ace:
ace = True
card_value = 11
# score += card_value
score = score + card_value
# if we would bust, check if there is an ace and subtract 10
if score > 21 and ace:
# score -= 10
score = score - 10
ace = False
return score
def deal_dealer():
dealer_score= score_hand(dealer_hand)
while 0 < dealer_score <17:
dealer_hand.append(deal_card(dealer_card_frame))
dealer_score= score_hand(dealer_hand)
dealer_score_label.set(dealer_score)
player_score = score_hand(player_hand)
if player_score>21:
resulttext.set('Dealer Wins!')
elif dealer_score > 21 or dealer_score player_score:
resulttext.set('Dealer Wins!')
else:
resulttext.set('Draw!')
# player_score_label.set(player_score)
# if player_score>21:
# resulttext.set ('Dealer Wins')
# def deal_player():
# deal_card(player_card_frame)
def deal_player():
player_hand.append(deal_card(player_card_frame))
player_score= score_hand(player_hand)
player_score_label.set(player_score)
if player_score>21:
resulttext.set ('Dealer Wins')
# global player_score
# global player_ace
# card_value = deal_card(player_card_frame)[0]
# if card_value ==1 and not player_ace:
# player_ace = True
# card_value = 11
# player_score = player_score + card_value
# # if we would bust,check if there is an ace and subtract
# if player_score>21 and player_ace:
# player_score = player_score - 10
# player_ace = False
# player_score_label.set(player_score)
# if player_score>21:
# resulttext.set("Dealer Wins")
# print(locals())
def new_game():
global dealer_card_frame
global player_card_frame
global dealer_hand
global player_hand
# embedded frame to hold the card images
dealer_card_frame.destroy()
dealer_card_frame = tkinter.Frame(card_frame, background='green')
dealer_card_frame.grid(row=0, column=1, sticky='ew', rowspan=2)
# embedded frame to hold the card images
player_card_frame.destroy()
player_card_frame = tkinter.Frame(card_frame, background="green")
player_card_frame.grid(row=2, column=1, sticky='ew', rowspan=2)
resulttext.set("")
# Create the list to store the dealer's and player's hands
dealer_hand = []
player_hand = []
deal_player()
dealer_hand.append(deal_card(dealer_card_frame))
dealer_score_label.set(score_hand(dealer_hand))
deal_player()
def shuffle():
random.shuffle(deck)
def play():
deal_player()
dealer_hand.append(deal_card(dealer_card_frame))
dealer_score_label.set(score_hand(dealer_hand))
deal_player()
mainwindow.mainloop()
mainwindow = tkinter.Tk()
#setup the screens and frame for the dealer and the player
mainwindow.title("blackjack")
mainwindow.geometry("640x480")
mainwindow.configure(background = "green")
resulttext = tkinter.StringVar()
result = tkinter.Label(mainwindow,textvariable = resulttext)
result.grid(row=0,column=0,columnspan=3)
card_frame= tkinter.Frame(mainwindow,relief = 'sunken',borderwidth = 1,background = 'green')
card_frame.grid(row=1,column=0,sticky = 'ew',columnspan = 3,rowspan=2)
dealer_score_label = tkinter.IntVar()
tkinter.Label(card_frame,text = 'Dealer',background ='green',fg='white').grid(row=0,column=0)
tkinter.Label(card_frame,textvariable = dealer_score_label,background ='green',fg='white').grid(row=1,column=0)
#embedded Frame hold the card images
dealer_card_frame=tkinter.Frame(card_frame,background = 'green')
dealer_card_frame.grid(row=0,column=1,sticky='ew',rowspan=2)
player_score_label = tkinter.IntVar()
tkinter.Label(card_frame,text = 'Player',background ='green',fg='white').grid(row=2,column=0)
tkinter.Label(card_frame,textvariable = player_score_label,background ='green',fg='white').grid(row=3,column=0)
#embedded Frame hold the card images
player_card_frame=tkinter.Frame(card_frame,background = 'green')
player_card_frame.grid(row=2,column=1,sticky='ew',rowspan=2)
button_frame = tkinter.Frame(mainwindow)
button_frame.grid(row=3,column=0,columnspan = 3,sticky = 'w')
dealer_button=tkinter.Button(button_frame,text = 'Dealer',command = deal_dealer)
dealer_button.grid(row=0,column=0)
player_button=tkinter.Button(button_frame,text = 'Player',command = deal_player)
player_button.grid(row=0,column=1)
new_game_button=tkinter.Button(button_frame,text = 'New Game',command = new_game)
new_game_button.grid(row=0,column=2)
shuffle_button = tkinter.Button(button_frame, text="Shuffle", command=shuffle)
shuffle_button.grid(row=0, column=3)
#load cards
cards = []
load_images(cards)
# print(cards)
# print(id(cards))
#create a new deck of cards and shuffle them
deck = list(cards) + list(cards) + list(cards)
shuffle()
# Create the list to store the dealer's and player's hands
dealer_hand = []
player_hand = []
if __name__ == '__main__':
play()
import blackjacktest1
print (__name__)
blackjacktest1.play()
Python - function challenge - blackjack game extension - Day 23
#this is extension of blackjack game to include the new game button and shuffle button
import tkinter as tkinter
import random
try:
import tkinter
except ImportError: # python 2
import Tkinter as tkinter
def load_images(card_images):
suits=['heart','club','diamond','spade']
face_cards=['jack','queen','king']
if tkinter.TkVersion >= 8.6:
extension = 'png'
else:
extension = 'ppm'
#for each suit retrieve the image for the cards
for suit in suits:
#first the number cards 1 to 10
for card in range(1,11):
name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
image = tkinter.PhotoImage(file = name)
card_images.append((card,image))
#next the Face Cards
for card in face_cards:
name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
image = tkinter.PhotoImage(file = name)
card_images.append((10,image))
def deal_card(frame):
#pop the next card of the top of the deck
next_card= deck.pop(0)
#if the player keeps on playing new game then all the cards will be used so
deck.append(next_card)
#add the image to the label and display the label
tkinter.Label(frame,image=next_card[1],relief = 'raised').pack(side = 'left')
#now return the cards face value
return next_card
def score_hand(hand):
# Calculate the total score of all cards in the list.
# Only one ace can have the value 11, and this will be reduce to 1 if the hand would bust.
score = 0
ace = False
for next_card in hand:
card_value = next_card[0]
if card_value == 1 and not ace:
ace = True
card_value = 11
# score += card_value
score = score + card_value
# if we would bust, check if there is an ace and subtract 10
if score > 21 and ace:
# score -= 10
score = score - 10
ace = False
return score
def deal_dealer():
dealer_score= score_hand(dealer_hand)
while 0 < dealer_score <17:
dealer_hand.append(deal_card(dealer_card_frame))
dealer_score= score_hand(dealer_hand)
dealer_score_label.set(dealer_score)
player_score = score_hand(player_hand)
if player_score>21:
resulttext.set('Dealer Wins!')
elif dealer_score > 21 or dealer_score player_score:
resulttext.set('Dealer Wins!')
else:
resulttext.set('Draw!')
# player_score_label.set(player_score)
# if player_score>21:
# resulttext.set ('Dealer Wins')
# def deal_player():
# deal_card(player_card_frame)
def deal_player():
player_hand.append(deal_card(player_card_frame))
player_score= score_hand(player_hand)
player_score_label.set(player_score)
if player_score>21:
resulttext.set ('Dealer Wins')
# global player_score
# global player_ace
# card_value = deal_card(player_card_frame)[0]
# if card_value ==1 and not player_ace:
# player_ace = True
# card_value = 11
# player_score = player_score + card_value
# # if we would bust,check if there is an ace and subtract
# if player_score>21 and player_ace:
# player_score = player_score - 10
# player_ace = False
# player_score_label.set(player_score)
# if player_score>21:
# resulttext.set("Dealer Wins")
# print(locals())
def new_game():
global dealer_card_frame
global player_card_frame
global dealer_hand
global player_hand
# embedded frame to hold the card images
dealer_card_frame.destroy()
dealer_card_frame = tkinter.Frame(card_frame, background='green')
dealer_card_frame.grid(row=0, column=1, sticky='ew', rowspan=2)
# embedded frame to hold the card images
player_card_frame.destroy()
player_card_frame = tkinter.Frame(card_frame, background="green")
player_card_frame.grid(row=2, column=1, sticky='ew', rowspan=2)
resulttext.set("")
# Create the list to store the dealer's and player's hands
dealer_hand = []
player_hand = []
deal_player()
dealer_hand.append(deal_card(dealer_card_frame))
dealer_score_label.set(score_hand(dealer_hand))
deal_player()
def shuffle():
random.shuffle(deck)
mainwindow = tkinter.Tk()
#setup the screens and frame for the dealer and the player
mainwindow.title("blackjack")
mainwindow.geometry("640x480")
mainwindow.configure(background = "green")
resulttext = tkinter.StringVar()
result = tkinter.Label(mainwindow,textvariable = resulttext)
result.grid(row=0,column=0,columnspan=3)
card_frame= tkinter.Frame(mainwindow,relief = 'sunken',borderwidth = 1,background = 'green')
card_frame.grid(row=1,column=0,sticky = 'ew',columnspan = 3,rowspan=2)
dealer_score_label = tkinter.IntVar()
tkinter.Label(card_frame,text = 'Dealer',background ='green',fg='white').grid(row=0,column=0)
tkinter.Label(card_frame,textvariable = dealer_score_label,background ='green',fg='white').grid(row=1,column=0)
#embedded Frame hold the card images
dealer_card_frame=tkinter.Frame(card_frame,background = 'green')
dealer_card_frame.grid(row=0,column=1,sticky='ew',rowspan=2)
player_score_label = tkinter.IntVar()
tkinter.Label(card_frame,text = 'Player',background ='green',fg='white').grid(row=2,column=0)
tkinter.Label(card_frame,textvariable = player_score_label,background ='green',fg='white').grid(row=3,column=0)
#embedded Frame hold the card images
player_card_frame=tkinter.Frame(card_frame,background = 'green')
player_card_frame.grid(row=2,column=1,sticky='ew',rowspan=2)
button_frame = tkinter.Frame(mainwindow)
button_frame.grid(row=3,column=0,columnspan = 3,sticky = 'w')
dealer_button=tkinter.Button(button_frame,text = 'Dealer',command = deal_dealer)
dealer_button.grid(row=0,column=0)
player_button=tkinter.Button(button_frame,text = 'Player',command = deal_player)
player_button.grid(row=0,column=1)
new_game_button=tkinter.Button(button_frame,text = 'New Game',command = new_game)
new_game_button.grid(row=0,column=2)
shuffle_button = tkinter.Button(button_frame, text="Shuffle", command=shuffle)
shuffle_button.grid(row=0, column=3)
#load cards
cards = []
load_images(cards)
# print(cards)
# print(id(cards))
#create a new deck of cards and shuffle them
deck = list(cards) + list(cards) + list(cards)
shuffle()
# Create the list to store the dealer's and player's hands
dealer_hand = []
player_hand = []
new_game()
mainwindow.mainloop()
Saturday, 7 April 2018
Python - function challenge - blackjack game - Day 22(after 1 day)
#this program explains how to achieve the blackjack game
#the key points to note here are
#pop funtion,using the same code of function to avoid repetition
#load images from file to frame,shuffling of cards,calculating scores
#then use of the global keyword to avoiding shadowing of the global variable inside the function
import tkinter as tkinter
import random
def load_images(card_images):
suits=['heart','club','diamond','spade']
face_cards=['jack','queen','king']
#for each suit retrieve the image for the cards
for suit in suits:
#first the number cards 1 to 10
for card in range(1,11):
name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
image = tkinter.PhotoImage(file = name)
card_images.append((card,image))
#next the Face Cards
for card in face_cards:
name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
image = tkinter.PhotoImage(file = name)
card_images.append((10,image))
def deal_card(frame):
#pop the next card of the top of the deck
next_card= deck.pop(0)
#add the image to the label and display the label
tkinter.Label(frame,image=next_card[1],relief = 'raised').pack(side = 'left')
#now return the cards face value
return next_card
def deal_dealer():
dealer_score= score_hand(dealer_hand)
while 0 < dealer_score <17:
dealer_hand.append(deal_card(dealer_card_frame))
dealer_score= score_hand(dealer_hand)
dealer_score_label.set(dealer_score)
player_score = score_hand(player_hand)
if player_score>21:
resulttext.set('Dealer Wins!')
elif dealer_score > 21 or dealer_score player_score:
resulttext.set('Dealer Wins!')
else:
resulttext.set('Draw!')
# player_score_label.set(player_score)
# if player_score>21:
# resulttext.set ('Dealer Wins')
# def deal_player():
# deal_card(player_card_frame)
def deal_player():
player_hand.append(deal_card(player_card_frame))
player_score= score_hand(player_hand)
player_score_label.set(player_score)
if player_score>21:
resulttext.set ('Dealer Wins')
#below code is used for testing the global,local shadowing concept
# global player_score
# global player_ace
# card_value = deal_card(player_card_frame)[0]
# if card_value ==1 and not player_ace:
# player_ace = True
# card_value = 11
# player_score = player_score + card_value
# # if we would bust,check if there is an ace and subtract
# if player_score>21 and player_ace:
# player_score = player_score - 10
# player_ace = False
# player_score_label.set(player_score)
# if player_score>21:
# resulttext.set("Dealer Wins")
# print(locals())
def score_hand(hand):
#calculate the total score of all cards in the list
# only one can have the value 11,and this will be reduce to 1 if the hand would bust.
score = 0
ace = False
for next_card in hand:
card_value = next_card[0]
if card_value == 1 and not ace:
ace = True
card_value = 11
score = score + card_value
#if we would bust ,check if there is an ace and subtract 10
if score > 21 and ace:
score =score - 10
ace = False
return score
mainwindow = tkinter.Tk()
#setup the screens and frame for the dealer and the player
mainwindow.title("blackjack")
mainwindow.geometry("640x480")
mainwindow.configure(background = "green")
resulttext = tkinter.StringVar()
result = tkinter.Label(mainwindow,textvariable = resulttext)
result.grid(row=0,column=0,columnspan=3)
card_frame= tkinter.Frame(mainwindow,relief = 'sunken',borderwidth = 1,background = 'green')
card_frame.grid(row=1,column=0,sticky = 'ew',columnspan = 3,rowspan=2)
dealer_score_label = tkinter.IntVar()
tkinter.Label(card_frame,text = 'Dealer',background ='green',fg='white').grid(row=0,column=0)
tkinter.Label(card_frame,textvariable = dealer_score_label,background ='green',fg='white').grid(row=1,column=0)
#embedded Frame hold the card images
dealer_card_frame=tkinter.Frame(card_frame,background = 'green')
dealer_card_frame.grid(row=0,column=1,sticky='ew',rowspan=2)
player_score_label = tkinter.IntVar()
tkinter.Label(card_frame,text = 'Player',background ='green',fg='white').grid(row=2,column=0)
tkinter.Label(card_frame,textvariable = player_score_label,background ='green',fg='white').grid(row=3,column=0)
#embedded Frame hold the card images
player_card_frame=tkinter.Frame(card_frame,background = 'green')
player_card_frame.grid(row=2,column=1,sticky='ew',rowspan=2)
button_frame = tkinter.Frame(mainwindow)
button_frame.grid(row=3,column=0,columnspan = 3,sticky = 'w')
dealer_button=tkinter.Button(button_frame,text = 'Dealer',command = deal_dealer)
dealer_button.grid(row=0,column=0)
player_button=tkinter.Button(button_frame,text = 'Player',command = deal_player)
player_button.grid(row=0,column=1)
#load cards
cards = []
load_images(cards)
# print(cards)
# print(id(cards))
#create a new deck of cards and shuffle them
deck = list(cards)
random.shuffle(deck)
#Create the list to store the dealers and players hands
dealer_hand = []
player_hand = []
deal_player()
dealer_hand.append(deal_card(dealer_card_frame))
deal_player()
mainwindow.mainloop()
Friday, 6 April 2018
Python function -circle challenge 1 - Day 21(after 1 day)
#instead of using the for loop outside we can plot it in the parabol
#funtion itself
import math
import tkinter
def parabola(page,size):
for x in range(-size,size):
y = x * x/size
plot(page,x,y)
#the formula behind this is for circle it is enough to draw one quadrant and
#then negating it the axis will provide the symmetry and make an circle
#ie .. we have y = h + (math.sqrt(radius ** 2 -((x-g)**2)))
#we want y = h - (math.sqrt(radius ** 2 -((x-g)**2)))
#but minus y is actually -y = h - (math.sqrt(radius ** 2 -((x-g)**2)))
#so we add 2 * h back onto -y
def circle(page,radius,g,h):
for x in range(g,g + radius):
y = h + (math.sqrt(radius ** 2 -((x-g)**2)))
plot(page,x,y)
plot(page,x,2* h - y)
plot(page,2 * g - x,y)
plot(page,2 * g - x,2* h - y)
def draw_axes(page):
page.configure(scrollregion=(-200,-200,200,200))
page.create_line(-200,0,200,0, fill="blue")
page.create_line(0,200,0,-200, fill="blue")
def plot(canvas,x,y):
canvas.create_line(x,-y,x+1,-y+1,fill="red")
mainwindow = tkinter.Tk()
mainwindow.title("Parabola")
mainwindow.geometry("640x480")
canvas = tkinter.Canvas(mainwindow,width=640,height= 480)
canvas.grid(row=0,column=0)
print(id(canvas))
draw_axes(canvas)
parabola(canvas,100)
parabola(canvas,150)
circle(canvas,100,100,100)
circle(canvas,100,100,-100)
circle(canvas,100,-100,100)
circle(canvas,100,-100,-100)
circle(canvas,30,30,30)
circle(canvas,30,30,-30)
circle(canvas,30,-30,30)
circle(canvas,30,-30,-30)
# for x in range(-100,100):
# y = parabola(x)
# plot(canvas,x,-y)
mainwindow.mainloop()
Python function scope - Day 20(after 20 days)
#this will explain the scope of the variable
#we can use locals() to know the variable in that scopre,this can be used only inside functions
import tkinter
def parabola(x):
y = x * x/100
return y
def draw_axes(canvas):
#the canvas variable here is different from the canvas outside
#of this function
# canvas.update
#here the x and y origin are not fetching properly so hardcoded the values
# x_origin = canvas.winfo_width ()/2
# y_origin = canvas.winfo_height()/2
# x_origin = canvas.winfo_width ()
# y_origin = canvas.winfo_height()
canvas.configure(scrollregion=(-200,-200,200,200))
canvas.create_line(-200,0,200,0, fill="blue")
canvas.create_line(0,200,0,-200, fill="blue")
#this will give the object location(address),we can differentiate object of same names
#using this id()
print(id(canvas))
print(locals())
def plot(canvas,x,y):
canvas.create_line(x,y,x+1,y+1,fill="red")
mainwindow = tkinter.Tk()
mainwindow.title("Parabola")
mainwindow.geometry("640x480")
canvas = tkinter.Canvas(mainwindow,width=320,height= 480)
canvas.grid(row=0,column=0)
#we have created two canvas to show how the scope works
canvas2 = tkinter.Canvas(mainwindow,width=320,height= 480)
canvas2.grid(row=0,column=1)
print(id(canvas))
print(id(canvas2))
draw_axes(canvas)
draw_axes(canvas2)
for x in range(-100,100):
y = parabola(x)
plot(canvas,x,-y)
mainwindow.mainloop()
Thursday, 15 March 2018
Python function eg - Day 20
def python_food():
print("Spinach is good for health")
python_food()
print (python_food())
def center_text():
width = 50
text = 'Spinach is good for health'
leftalignment = (width - len(text))//2
print(' '*leftalignment,text)
center_text()
print('='*20)
def center_text1(text):
width = 50
leftalignment = (width - len(text))//2
print(' '*leftalignment,text)
center_text1('Spinach is Good for Health')
center_text1('Excecise is goood for body')
center_text1('Life is worth living')
center_text1('Love yourself')
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
"""
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
"""
pass
Subscribe to:
Posts (Atom)


