Author - Web Developer - Educator
Found 1 result for tag "tails"
RSS Feed

Python Progress: Coin Flip

Based on a conversation I had earlier today with Keat's brother, I took another whack at Python. I've been working on learning Python for a while, but never really got the hang of it since I'm mainly a PHP guy.

Anyway, based on some tutorials I learned today, I wrote a pretty nice Python script for calculating coin flips and reporting the outcome. Some of my Python-skilled friends may laugh, but I enjoyed writing this and testing my (limited) skills.

import time, random, os

#clear the screen

#define H and T, making them floats

#begin input

max_num = raw_input("How many times do you want to flip a coin? ")

if len(max_num)==0:
	#if no input, make 10 the default
	max_num = 10 
	print "No number specificed. Defalting to 10"

max_num = int(max_num) #convert to integer to make the calcualtions work 

#little helpful tip
if max_num >= 300:
	unit = str(round((max_num*.2)/60,2))+" minutes"
	unit = str(round(max_num*.2,2))+" seconds"

print "It will take "+unit+" to complete"

#flip the "coin" max_num times
for x in range(0,max_num):
	coin = random.randrange(2)
	if coin == 0:
		print "Heads" #report
		H+=1 #record
		print "Tails" #report
		T+=1 #record
	time.sleep(.15) #take a small break

#simple function to calcualte the percentage and report it, 
# instead of having to write this out more than once
def report(text,side):
	perc = round((side/max_num)*100, 2)
	print text+": "+str(perc)+"%"

#print "Heads: "+str(H)+" | Tails: "+str(T)

#finalize the reports
report("Heads", H)
report("Tails", T)


#Print the winning side
#print "\n"
if H>T:
	print '\033[1m'+"Heads Win!"+'\033[0m'
elif T>H:
	print '\033[1m'+"Tails Win!"+'\033[0m'
elif T==H:
	print "It's a tie!"

I've been trying to work on getting Python to work on the web, but my server doesn't really like WSGI or mod_python. I also tried TurboGears, but that didn't quite work as expected. I may be able to work on that better and get it incoroprated to to some Dynamic programming and offer that to clients.

Also, things may be changing at Shadow Development - could be for the worse or better. Personally, I think it will be for the better because I really enjoyed pushing my skillset and coding practices, so we'll see where it goes.

Tags:#python #php #coins #heads #tails #percent #tutorials