gpt4 book ai didi

python - 我怎样才能使这个文本变量起作用?

转载 作者:行者123 更新时间:2023-12-03 08:55:49 26 4
gpt4 key购买 nike

该程序无法正常运行。在“您有以下汽车”之后,似乎无法打印汽车:

如何在def game()部分获取要更改的变量?

这是一个粘贴框: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()

最佳答案

如果要在功能中访问“汽车”,则必须将它们设置为全局变量。

试穿

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(),这将为“beauty”添加额外的空间并使输入不区分大小写

我还将添加换行符( \n)或空 print ()语句,以使输出更漂亮并更易于理解。这只会在您想要的位置添加一个空行。

关于python - 我怎样才能使这个文本变量起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26079900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com