# coding:utf8
import random
def chkcoin(acoin):
basecoin = [1, 5, 10, 25]
flag = False
for bc in basecoin:
if 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比较。希望你能解决这个问题。
追问在python3。。。里面貌似用不了。。还在修改中
还有就是 不用每一步都显示出那个现在的总数。 比如说 我按了1,之后下一次按了5, 这个时候不需要告诉我总共有6. 还有一个就是 当我按的时候 比如我直接输入空格, 代码直接崩溃了 并不是enter first coin
追答1、我的版本是py2.7.8,py3需要把print 'xxx'语句 换成 print('xxx');其他的不同可能还有输入函数吧raw_input()
2、提示现有总和,我是测试打印,你把print tolcoin这句注释掉即可
3、程序未加入输入非数字检测,你可以在chkcoin()方法里添加下