我已对您的代码进行了一些更改以使其正常工作,其中包括使用 # 符号指示的 cmets。
最重要的两件事是所有括号都需要关闭:
fun((x, y) # broken
fun((x, y)) # not broken
并且Python中的关键字都是小写的:
if, while, for, not # will work
If, While, For, Not # won't work
您可能对True 和False 感到困惑,它们可能应该是小写的。它们已经这样很久了,现在改变它们为时已晚。
budget = 100 # You need to initialize variables before using them.
def shoplist():
prices = { # I re-named the price list from list to prices
'apple' : 30, # because list is a reserved keyword. You should only
'orange' : 20, # use the list keyword to initialize list objects.
'milk' : 60, # This type of object is called a dictionary.
} # The dots .... would have caused an error.
# In most programming languages, you need to close all braces ().
# I've renamed buy to item to make it clearer what that variable represents.
item = input('What do you want to purchase? ')
# Also, you don't need to cast the value of input to str;
# it's already a str.
if item in prices:
# If you need an int, you do have to cast from string to int.
count = int(input('How many? '))
cost = count*prices[item] # Access dictionary items using [].
if cost > budget:
print('You can\'t afford that many!')
else:
# You can put data into strings using the % symbol like so:
print('That\'ll be %i.' % cost) # Here %i indicates an int.
else:
print('We don\'t have %s in stock.' % item) # Here %s means str.
shoplist()
许多初学者在 StackOverflow 上发布了损坏的代码,却没有说他们遇到错误或这些错误是什么。发布错误消息总是有帮助的。如果您还有其他问题,请告诉我。