Ask coding questions

← Back to all posts
can a varible be used in multiple files
eh506249 (3)

so i have a project where I want to make a variable in one .py file and also use that same variable in a different .py file. so far everything I've tried hasn't worked so far so i need help

Answered by ch1ck3n (2065) [earned 5 cycles]
View Answer
Comments
hotnewtop
ch1ck3n (2065)

let's say you want to make a variables.py

variables.py:

x = 1
doge = "awesome"

and you want to add it to main.py.

main.py:

print("doge is " + doge)

But you get an error saying doge is not defined. to fix this, (or import variables from another file) we can use the import keyword.

main.py:

from variables import * # the * means import all functions, classes, and variables.

print("doge is " + doge)

and we get that doge is awesome!

nice

(not: variables.py can be named anything, just make sure to change where you import from)