Reputation: 45
The program runs fine for two times and then shows the error
prize= prize(n,door)
TypeError: 'str' object is not callable.
Please help me with my code, is there something I'm missing?
#program to simulate the 3 doors problem using random numbers
from random import *
door= [0 for i in range (3)]
C='y'
count=0
switch=0
noswitch=0
def shuffle():
doors= [0 for i in range (3)]
pick= randint(1,3)
if pick==1:
doors=['goat', 'goat', 'car']
elif pick==2:
doors=['goat', 'car', 'goat']
else:
doors = ['car', 'goat', 'goat']
return doors
def opgoatdoor(n, door):
for i in range (3):
while (i+1)!=n and door[i]!= 'car':
return i+1
def prize(n, door):
if door[n-1] =='car':
print '\nCongrats!! You just became the owner of a brand new Rolls Royce!!\n Ride away!'
return 't'
else:
print '\nSorry...guess you are best off with a goat! \n Better luck next time! '
return 'f'
while C=='y' or C=='Y':
count+=1
door= shuffle()
n= input('Choose a door (1,2,3): ')
num= opgoatdoor(n, door)
print ('Lets make this interesting...\n I will reveal a door for you, door no %d holds a Goat!!') %num
#print door
ch= raw_input('\n Now..Do you want to change your choice (press Y) or stick to your previous door(press N)? : ')
if ch =='y' or ch=='Y':
n= input('Enter your new door number: ')
prize= prize(n,door)
if prize =='t':
switch+=1
else:
prize= prize(n,door)
if prize =='t':
noswitch+=1
C= raw_input('Wanna play again?(Y/N): ')
print 'The no.of times you win a car for %d plays if you switch doors is %d and if you stick with your choice is %d ' %(count, switch, noswitch)
Upvotes: 0
Views: 2361
Reputation: 20391
You defined two variables named prize
in the same scope, a string and a function.
The second assignment of the name overrides the first, so prize
is now a string. Therefore, when you try to call your function you are actually trying to call a string- hence the error.
The solution to this is to rename either your function or your string to a different name.
Upvotes: 2
Reputation: 1124558
You cannot use the name prize
for both a variable and a function; in Python functions are first-class objects and bound to names just like strings are.
You'll have to rename one or the other.
Perhaps use prize_won
in the while
loop instead:
if ch =='y' or ch=='Y':
n= input('Enter your new door number: ')
prize_won = prize(n,door)
if prize_won == 't':
switch += 1
else:
prize_won = prize(n,door)
if prize_won == 't':
noswitch += 1
Upvotes: 3