#4 Variables in Python / Python Lessons for Beginners

by Alex
#4 Variables in Python / Python Lessons for Beginners

Previous lesson: Python Syntax

How to create variables

Unlike other programming languages, Python has no command to declare a variable. A variable is created when you assign it a value.

x = 5
y = "Sasha"
print(x)
print(y)

Conclusion:

5
Sasha

It is not necessary to specify a specifictype of variable when declaring it. You can even change their type after creation.

x = 4 # now x is int
x = "Alyona" # now x is str
print(x)

Conclusion:

Aljona

Variable Name

A variable can have a short name (e.g., x and y) or a more meaningful name(age, carname, total_volume). The rules for variables in Python:

  • A variable name must start with a letter or underscore character.
  • It cannot begin with a number.
  • A variable name can only contain alphanumeric characters and underscores (Az, 0-9 and _)
  • Variable names are case sensitive(age, Age and AGE are three different variables)

Remember that variables are case-sensitive

Variable output

The Python print function is often used to output variables: To combine both text and variable, Python uses the +

x = "unbelievable."
print("Python " + x)

Output:

Python is improbable

You can also use the + symbol to add a variable to another variable:

x = "Python "
y = "unbelievable"
z = x + y
print(z)

Output:

Python is unbelievable

For numbers, the + symbol works like a mathematical operator:

x = 5
y = 10
print(x + y)

Conclusion:

15

If you try to concatenate a string and a number, Python will show you an error message:

x = 5
y = "Sasha"
print(x + y)

Output:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Related Posts

LEAVE A COMMENT