展開全部
# coding:utf8
import random
def chkcoin(acoin):
basecoin = [1, 5, 10, 25]
flag = False
for bc in basecoin:
62616964757a686964616fe78988e69d8331333335336366if acoin == int(bc):
return True
else:
flag = True
if flag:
print 'Invalid entry'
return False
def tryAgain():
comd = raw_input('Try again (y/n)?: ')
if comd == 'y':
return True
elif comd == 'n':
print 'Thanks for playing ... goodbye'
return False
else:
print 'Command error! Please enter y or n.'
print 'Thanks for playing ... goodbye'
return False
if __name__ == '__main__':
print'''The purpose of this exercise is to enter a number of coin values
that add up to a displayed target value.
Enter coins values as 1-penny, 5-nickel, 10-dime, and 25-quarter.
Hit return after the lase entered coin value.
-----------------------
''',
rand = random.randint(1, 99)
print 'Enter coins that add up to %s cents, one per line.' % rand
isAgain = True
while isAgain:
coins = []
acoin = int(raw_input('Enter first coin: '))
if chkcoin(acoin):
coins.append(acoin)
else:
continue
while True:
tolcoin = 0
for coin in coins:
tolcoin += int(coin)
print tolcoin
if tolcoin == rand:
print 'Correct!'
if not tryAgain():
isAgain = False
break
elif tolcoin > rand:
print 'Sorry - total amount exceeds %s cents.' % rand
if not tryAgain():
isAgain = False
break
else:
pass
acoin = int(raw_input('Enter next coin: '))
if chkcoin(acoin):
coins.append(acoin)
else:
continue
if isAgain:
rand = random.randint(1, 99)
print 'Enter coins that add up to %s cents, one per line.' % rand
運作結果:
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
The purpose of this exercise is to enter a number of coin values
that add up to a displayed target value.
Enter coins values as 1-penny, 5-nickel, 10-dime, and 25-quarter.
Hit return after the lase entered coin value.
-----------------------
Enter coins that add up to 1 cents, one per line.
Enter first coin: 1
1
Correct!
Try again (y/n)?: y
Enter coins that add up to 72 cents, one per line.
Enter first coin: 25
25
Enter next coin: 25
50
Enter next coin: 25
75
Sorry - total amount exceeds 72 cents.
Try again (y/n)?: n
Thanks for playing ... goodbye
>>>
我這裡用的是list來存儲輸入的數字,累加,這隻是一種方法,你可以加工精簡。。。也可以用樓上兄弟的方法逐減,然後和0比較。希望你能解決這個問題。