Reputation: 11
I'm writing a python program that asks you to predict a die. You start with 5 euro and you earn 5 euro if you win, lose 1 euro if you're 1 off and lose 3 euro if you're more than 1 off.
def main():
while True:
saldo = 5
y = input("[R]oll or [S]top")
if y == "r" :
p = input("What is your prediction?")
from random import randint
x = randint(1, 6)
print(x)
if p == x:
saldo = saldo +5
elif p == int(x-1) or p == int(x+1):
saldo = saldo -1
else:
saldo = saldo -3
print ("saldo is " , saldo)
elif y == "s" :
saldo = saldo
print ("eindsaldo is " , saldo)
return
else:
print ("Enter r or s")
main()
The random part is working but not the saldo part and I can't figure out what is going wrong. I am new at Python but got some experience on Javascript and other basic programming languages. This looks like it should work though.
Upvotes: 0
Views: 514
Reputation: 15204
Take a look at the below code. I took the liberty to make additional changes to make the whole thing more Pythonic and efficient.
Update2: I took the liberty to make some small adjustments (Antonvbr)
from random import randint # 1
def main(saldo):
while True:
y = input("[R]oll or [S]top").lower() # 3
if y == "r" :
p = input("What is your prediction?") #4
while p not in list("123456"):
print("Enter a valid number 1-6")
p = input("What is your prediction?")
p = int(p) # convert to integer
x = randint(1, 6)
print(x)
if p == x:
saldo += 5
elif abs(p-x) == 1:
saldo -= 1
else:
saldo -= 3
print ("saldo is {}".format(saldo)) # 5
elif y == "s" :
print ("stop! saldo is {}".format(saldo))
return saldo
else:
print ("Enter R/r or S/s") # Not case sensitivt anymore
startsaldo = 5
saldo = main(startsaldo) #2
Explanation:
you do not want to import on every iteration, import functions are always made first
as mentioned by others saldo
needs to be initialized once only. Normally parameters like these are injected in the function and returned back when the function quits.
"R"
or "S"
but comparing against "r"
and "s"
. In Python, case matters.Also generally, var = var + 1
is written like var += 1
in Python. Same applies with -
too.
Upvotes: 2
Reputation: 2107
Your saldo
is initialised inside the while loop.
This means every time you start at the beginning of the loop, your saldos are set to 5.
def main()
saldo = 5
while True:
y = input("[R]oll or [S]top")
...
Move the saldo = 5
outside the while loop.
Upvotes: 2