473,831 Members | 2,326 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Basic coin flipper program - logical error help

I'm just learning Python. I've created a simple coin flipper program -
here is the code:

[source]
#Coin flipper
import random

heads = 0
tails = 0
counter = 0

coin = random.randrang e(2)

while (counter < 100):
if (coin == 0):
heads += 1
counter += 1
else:
tails += 1
counter += 1

coin = random.randrang e(2)
print "\nThe coin landed on heads", heads, "times."
print "\nThe coin landed on tails", tails, "times."
[/source]

<<<I'm sure the [source] tags don't work - I through them in there
anyway.>>>

The program runs - however - it will give me 100 heads OR 100 tails.
Can someone spot the logic error?

Thanks

~Dan

Feb 22 '06
12 2861
wes weston wrote:
DannyB wrote:
I'm just learning Python. I've created a simple coin flipper program -

....
Dan,
Looping is easier with:
for x in range(100):
if random.randint( 0,1) == 0:
heads += 1
else:
tails += 1


Or, continuing with that theme:

for x in range(N):
heads += random.randint( 0, 1)

As in:

import random
N = 100
heads = 0
for x in range(N):
heads += random.randint( 0, 1)
print "%d heads and %d tails." % (heads, N - heads)
Feb 22 '06 #11
DannyB said unto the world upon 21/02/06 06:14 PM:
I'm just learning Python. I've created a simple coin flipper program -
here is the code:

[source]
#Coin flipper
import random

heads = 0
tails = 0
counter = 0

coin = random.randrang e(2)

while (counter < 100):
if (coin == 0):
heads += 1
counter += 1
else:
tails += 1
counter += 1

coin = random.randrang e(2)
<snip>

The program runs - however - it will give me 100 heads OR 100 tails.
Can someone spot the logic error?


<snip>

Your original question is long since answered. But I've a style point.
As Dennis Lee Bieber pointed out, you don't need all three
accumulators. If you keep to the overall style of your code, you can
avoid repeating yourself as:
while (counter < 100):
counter += 1 # No point in putting this in each branch
coin = random.randrang e(2)
if (coin == 0):
heads += 1
else:
tails += 1
For roughly the same style, I'd go with:

heads = 0
count = 100

for i in range(count):
if random.randrang e(2):
heads += 1

tails = count - heads

HTH,

Brian vdB
Feb 22 '06 #12

"Paul McGuire" <pt***@austin.r r._bogus_.com> wrote in message
news:yU******** **********@torn ado.texas.rr.co m...
<bo****@gmail.c om> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. . sort, then groupby.
import itertools
import random
h,t = [len(list(g)) for k,g in itertools.group by(sorted([random.randrang e(2) for i in xrange(100)]))]
print h,t

By the way, sort + groupby generalizes beyond just coin-flipping. Here is a
modified version that simulates die rolls.

-- Paul

import itertools
import random

NUM_ROLLS = 1000
dieRolls = [random.randrang e(6)+random.ran drange(6)+2 for i in
xrange(NUM_ROLL S)]

# create dummy list entries for impossible rolls of 0 and 1
rolls = [None,None]

rolls += [len(list(g)) for k,g in itertools.group by(sorted(dieRo lls))]

# print out nice histogram
for i,r in enumerate(rolls ):
if i > 1:
print "%2d - %s" % (i,"*"*int(roun d(r/10.0)))
prints:

2 - ***
3 - *****
4 - *********
5 - **********
6 - ***************
7 - *************** ***
8 - **************
9 - *********
10 - *******
11 - *******
12 - ***

Feb 22 '06 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1681
by: Jon Monteleone | last post by:
Greetings, I posted a few days back and didnt get much of a response, so I figured I would post again with more detail. I am running gnome under fedora core 4. I want a kid to be able to drop a quarter into a coin slot and get 15 minutes of time on an account that has "restricted" Internet access via the firefox web browser. We are experimenting with different ways to allow kids to safely surf the web during school hours while...
3
16944
by: viewsonic | last post by:
Help, im a student that has to write a program for counting coins. Half of the program works but the other half doesn.t should have the following parameters. output is: Name Date total number of coins number of quarters number of dimes
4
10351
by: junaidnaseer | last post by:
Hi ! I am facing a problem that I have defined a function which when called in the same file generates an error as follows; " visual c error C2371 redefinition basic types see declaration of the function . " Could anyone please help me with this . Thank you
52
5414
by: celerysoup16 | last post by:
I've written this coin toss program, and can't figure out why it isn't giving accurate results... cheers, Ben #include <stdlib.h> #include <stdio.h> #define H 1 #define T 0 #define SENTINEL -1
7
10773
by: Joey | last post by:
I don't care what .net language this come in but I really need to determine if a disk is dynamic or basic. I have posted something in the WMI group but no one knows how to do it. Does anyone have any idea how I can determine this? At this point I don't care if it is a third plugin freeware app I use that writes it to a text file that I could read out. Thanks!
5
3847
by: sallyk57 | last post by:
I have to make a program that would ask a user for their guess (heads or tails) and tells them if its correct or not then it has to ask the user if they want to play again. I figured out how to do this but the part that i am stuck on is how to print a summary at the end of this program tracking how many wins and how many losses. import cs1.Keyboard; public class CoinToss6 { public static void main(String args) { ...
6
6078
blackstormdragon
by: blackstormdragon | last post by:
I just started a C++ class and now we're doing loops and have to make a coin flipping program. Well here's mine: #include<iostream> #include<cstdlib> using namespace std; int flip(); void main () { int coin, counter, tails = 0, heads = 0; for (counter = 1; counter <= 100; counter++)
1
2912
by: chrspta | last post by:
I am new to Visual basic. I need a program using VB6 that converts txt files to excel file.Description is in the below: The form should have the Drive list, Dir list, file list and cmdConvert button. Once pulling down the drive list and clicking to the specific drive, folders will be shown in the dir list. When clicking the folders in the dir list, files in that certain folder should apprear in the file list, but this program should limit...
8
24930
by: PAK11 | last post by:
This is what i have so far.......I need to add a function named coin to simulate a coin toss where heads is represented by a 1 and tails a 2. The outcome of the toss should be printed and the result should be return to the main program. I'm having trouble figuring it out, can anyone please help? #include <iostream> using namespace std; # include <ctime> int coin();
0
9793
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9642
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10494
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10534
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7748
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5619
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5780
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4416
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.