好吧,这是我写过的最长的代码,所以如果它有点乱,我道歉。第一次计算机科学任务。
def main():
#generate random value
import random
rand = random.randint(1, 99)
#instructions
print("""The purpose of this exercise is to enter a number of coin values
that add up to a displayed target value. Enter coins as 1=penny, 5-nickel,
10-dime, 25-quarter. Hit return after the last entered coin value.""")
#defining function for 'first coin'
def firstCoin ():
coins = []
global coins
coin = int(input("Enter first coin: "))
if coin > rand:
print("Sorry, total value exceeds", rand, "cents.")
again = input("Try again (y/n): ")
if again == "y" or "Y":
main()
else:
sys.exit() #ends program
elif coin in possible:
coins.append(coin)
nextCoinplease()
#defining function for 'next coin'
def nextCoinplease ():
while True:
nextcoin = (input("Enter next coin: "))
if nextcoin in possible:
coins.append(nextcoin)
elif nextcoin == "":
break
else: print("Invalid entry.")
#making lists
possible = [1, 5, 10, 25]
print("Enter coins that add up to", rand, "cents, one per line.") #program start
firstCoin ()
sumcoin = sum(coins)
print(sumcoin)
if sumcoin == rand:
print("Correct!")
else:
print("Invalid entry.")
firstCoin()
main()
所以,这是我的问题。由于某种原因,函数nextCoinplease中的用户输入不会被添加到列表" coins",只有函数firstCoin的第一个输入。这意味着总和(硬币)实际上只是第一个输入。我不能为我的生活找出原因,所以任何意见都会非常感激,谢谢!
答案 0 :(得分:0)
您有两个input
语句,一个用于获取coin
,另一个用于获取nextcoin
。它们是不同的。有什么区别?
(我故意不直接给出答案,因为从你到目前为止所写的内容来看,我相信你可以根据这个暗示来解决这个问题。)
答案 1 :(得分:0)
input
的返回类型是一个字符串,因此nextcoin in possible
总是失败,因为possible
只包含整数。尝试使用int()
将输入解析为整数。
答案 2 :(得分:0)
您的代码永远不会检查rand
是否等于sumCoin
,因此它永远不会停止。我已修复此问题,此代码现在可以使用。
我移动了if
语句,该语句在rand == sumCoin
的{{1}}循环开头检查while
是否为nextCoinPlease()
,以便检查sumCoin
值在输入每个下一个硬币值之前,一旦它等于rand
就会停止。
import random
import sys
def main():
rand = random.randint(1, 99)
print('''The purpose of this exercise is to enter a number of coin values \
that add up to a displayed target value. Enter coins as 1=penny, \
5=nickel, 10-dime, 25-quarter. Hit return after the last entered \
coin value.''')
coins = []
def firstCoin():
coin = int(input("Enter first coin: "))
if coin > rand:
print('Sorry, total value exceeds ', rand, ' cents.')
again = input('Try again? (y/n): ')
if again == 'y' or 'Y':
main()
else:
sys.exit()
elif coin in possible:
coins.append(coin)
nextCoinPlease()
def nextCoinPlease():
while True:
sumCoin = sum(coins)
print('Total Value: ' + str(sumCoin))
print ''
if sumCoin == rand:
print('Correct! You Win!')
sys.exit()
elif sumCoin > rand:
print('You exceeded the total value! You lose! Try again!')
sys.exit()
nextCoin = (input('Enter next coin: '))
if nextCoin in possible:
coins.append(nextCoin)
elif nextCoin == "":
break
else:
print('Invalid entry.')
possible = [1, 5, 10, 25]
print('Enter coins that add up to', rand, 'cents, one per line.')
firstCoin()
main()