Codes learning w3school
Codes learning w3school
if 5 > 2:
print("Five is greater than two!")
Example
import sys
print(sys.version)
exit()
Variables do not need to be declared with any particular type, and can even change type after they have
been set.
Example
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Example
a=4
A = "Sally"
#A will not overwrite a
Try it Yourself »
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
Example
2myvar = "John"
my-var = "John"
my var = "John"
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
myVariableName = "John"
Pascal Case
MyVariableName = "John"
Snake Case
my_variable_name = "John"
Try it Yourself »
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
Example
Unpack a list:
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Try it Yourself »
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Try it Yourself »
Also, use the global keyword if you want to change a global variable inside a function.
Built-in Data Types
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories: