此程序无效。在“你有以下车辆”之后似乎无法打印汽车:
如何在def游戏()部分中更改变量?
这是一个pastebin:http://pastebin.com/pjsuWRYs
import random
car1 = ("car1")
car2 = ("car2")
car3 = ("car3")
car4 = ("car4")
car5= ("car5")
car6 = ("car6")
car7= ("car7")
car8 = ("car8")
car9 = ("car9")
def game():
print ("You have the following cars:")
print (car1)
print (car2)
print (car3)
print (car4)
print (car5)
print (car6)
print (car7)
print (car8)
print (car9)
print ("You selected Grand Thief Auto")
gta = input ("To commit GTA type GTA")
if gta in ("gta", "Gta", "GTA", "a"):
chance = random.randint(0,100)
if chance <= 1:
print ("You stole a Bugatti Veryron")
car1 = ("Bugatti Veryron")
elif chance <= 5:
print ("You stole a Ferrari Spider")
car2 = ("Ferrari Spider")
elif chance <= 10:
print ("You stole a Audi Q7")
car3 = ("Audi Q7")
elif chance <= 15:
print ("You stole a BMW X6")
car4 = ("BMW X6")
elif chance <= 20:
print ("You stole a Jaguar X Type")
car5 = ("Jaguar X Type")
elif chance <= 25:
print ("You stole a Ford Mondeo")
car6 = ("Ford Mondeo")
elif chance <= 30:
print ("You stole a Audi A3")
car7 = ("Audi A3")
elif chance <= 35:
print ("You stole a Ford Fiesta")
car8 = ("Ford Fiesta")
elif chance <= 40:
print ("You stole a Skoda Octavia")
car9 = ("Skoda Octavia")
elif chance <= 100:
print ("You got caught!")
game()
game()
答案 0 :(得分:0)
如果您想在功能中访问&#34;汽车,您必须将它们设置为全局变量。
尝试放
global car1, car2, car3, car4, car5, car6, car7, car8, car9
在print ("You have the following cars:")
之前和define game():
之后
我还建议使用列表或词典,而不是自己定义每个变量。
你可以:
cars = ["car1", "car2", "etc"]
# To change a value for "car2" for example, do this:
# List values (indexes) in Python are starting from 0
cars[1] = "Bugatti"
# To print the car name do:
print (cars[0])
print (cars[1])
# Etc.
或:
cars = { "car1" : "Bugatti", "car2" : "Ferarri", "car number" : "car name"}
# To change a value for "car2" for example, do this:
cars["car2"] = "Bugatti"
# And to print the car names:
print (cars["car1"])
print (cars["car2"])
如果您选择使用列表或词典,则必须同时设置cars
变量global
为了让事情变得更好,我建议将input ("To commit GTA type GTA")
更改为(input ("To commit GTA type GTA: ").lower()
,这将为&#34; beauty&#34;添加额外的空间。并使输入不区分大小写
我还会添加换行符(\n
)或空print ()
语句,以使输出更漂亮,更易于理解。这只会在你想要的地方添加一个空行。