W3schools - Python_Variable
찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요
Variables
Are containers for storing data values
Python has no command for declaring a var
Var is created the moment first assign a value to it
Vars don’t need to declared with any particular type, and can even change type after they have been set
String var can be declared either by using single or double quotes
x = 5 # x is of type int
y = “Hello”
print(x) # output 5
x = “3” # x is now of type str
print(x) # output “3”
x = str(x) # If you want to specify the data type of a var, this can be done with casting
print(x) # output 3
print(type(x)) # output int, you can get the data type of a var with the type() func
Variable names
case-sensitive
Must start with a letter or the underscore character
Can’t start with a number
Can only contain alpha-numeric characters and underscores
Assign Multiple
Python allows to assign values to multiple vars in one line
x,y,z = “I”, “am”, “spongebob” # Make sure the number of vars matches the number of values
print(z) # output “spongebob”
Unpack a Collection
Python allows to extract the values into var
friends = [“Patrick”, “Squidward”, “Gary”, “Sandy”]
a,b,c,d = friends
print(a) # output “Patrick”
Global
Var that are created outside of a func are known as global var
Global var can be used by everyone, both inside of func and outside
x = “awesome”
def func():
print(“Python is ” + x)
func() # output “Python is awesome”
If you create a var with the same name inside a func, this var will be local, and can only be used inside the func
The global var with the same name will remain as it was, global and with the original value
def func2():
x = “pretty”
print(“Python is ” + x)
func2() # output “Python is pretty”
# Can create a global var inside a func using `global`
def func3():
global x
x = “fantastic”
func3()
print(“python is ” + x) #output “Python is fantastic”
Data type
Text : str
Numeric : int, float, complex
Sequence : list, tuple, range
Mapping : dict
Set : set, frozenset
Boolean : bool
Binary : bytes, bytearray, memoryview
Data Type | Assign | Specific, Casting |
---|---|---|
str | x = “Hello” | x = str(“Hello”) |
int | x = 20 | x = int(20) |
float | x = 20.5 | x = float(20.5) |
complex | x = 1j | x = complex(1j) |
list | x = [“apple”, “banana”] | x = list((“apple”, “banana”)) |
tuple | x = (“apple”, “banana”) | x = tuple((“apple”, “banana”)) |
range | x = range(6) | x = range(6) |
dict | x = {“name”: “spongebob”, “age” : 20} | x = dict(name= “spongebob”, age=36) |
set | x = {“apple”, “banana”} | x = set((“apple”, “banana”)) |
frozenset | x = frozenset({“apple”, “banana”}) | x = frozenset({“apple”, “banana”}) |
bool | x = True | x = bool(5) |
bytes | x = b“Hello” | x = bytes(5) |
bytearray | x = bytearray(5) | x = bytearray(5) |
memoryview | x = memoryview(bytes(5)) | x = memoryview(bytes(5)) |