Creating Variables
Unlike other
programming languages, Python has no command for declaring a variable.
A variable is when
you assign a value to the variable.
Example
a = 555
b =
"sateesh"
c = 1.314
d = 'm'
print(a)
print(b)
print(c)
print(d)
output:-
555
sateesh
1.314
m
Variable
Names
Variables do not need
to be declared with any particular type and can even change type after they
have been set.
Example
a = 555 # a is of type int
b = "sateesh" # a is now of type str
print(x)
output:-
sateesh
Variable
Names
A variable can have a
short name (like x and y) or a more descriptive name (name, age, car_name,
total_marks). 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 (name,
Name and NAME are three different variables)
- A
variable name must start with a letter or the underscore character
- A variable name cannot start with a number
Output Variables
The Python print statement is often used to output
variables.
To combine both text
and a variable, Python uses the + character:
Example
x = "awesome"
print("Python is " + x)
print("Python is " + x)
Python is awesome
You can also use
the + character to
add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z = x + y
print(z)
y = "awesome"
z = x + y
print(z)
Python
is awesome
For numbers,
the + character works
as a mathematical operator:
Example
x = 777
y = 76
print(x + y)
y = 76
print(x + y)
853
If you try to combine
a string and a number, It is not valid in Python. Python will give you an
error:
Example
x = 5
y = "John"
print(x + y)
y = "John"
print(x + y)
TypeError: unsupported operand type(s)
for +: 'int' and 'str'
No comments:
Post a Comment