Python - Variables and Types

Variables and Data Types

Everything in python is an object. Python is completely object oriented programming language which means there is no need to declare variables or their types before using them unlike C, C++ or Java.

This tutorial explains some of the basic types of variables in python.

Rules to Define a Variable in Python

  1. A variable name can only contain alphanumeric characters or and underscore character (a-z, A-Z, 0-9).
  2. A variable name must start with a letter or an underscore character.
  3. A variable name cannot start with a number or spacial character.
  4. Variable names are case-sensitive. For examples, variable 'noMangos' and NoMangos' are different.

Numerical Data Types

Two basic types of numerical are supported by python - integers and floating point numbers.

To define an integer varible use the following syntax.
myIntegerVariable = 3 
print(myIntegerVariable)

Output:

3
To define a floating point number you can use any of the following options.
# option 1
myFloatVariable = 3.0
print(myIntegerVariable)

# option 2
myFloatVariable = float(3)
print(myFloatVariable)

Output:

3.0
3.0

Strings

A string is a group of characters. You can use either single quotes or double quotes to define a string in python.
# define a string with single quotes
stringVariable = 'hello'
print(stringVariable)

# define a string with double quotes
stringVariable = "hello"
print(stringVariable)

Output:

hello
hello
What's the difference in the two options?

In you use double quotes to define a string you can easily include apostrophes whereas using single quotes would terminate the string.
stringVariable = "Double quotes strings, an easy way to add apostrophes"
print(stringVariable)

Output:

Double quotes strings, an easy way to add apostrophes
There are variety of ways to define strings to include things such as backslashes, Unicode characters and carriage returns. Those are covered in this tutorial but are present in Python Documentation.

We can use basic operators like +, - on numbers and strings to perform their usual meaning.
num1 = 1
num2 = 2
addition = num1 + num2
print(addition)

hello = "hello"
world = "world"
concatenatedWord = hello + " " + world
print(concatenatedWord)

Output:

3 
hello world
We can also assign values to more than one variables at the same time, on the same line.
x, y = 100, 111
print(x,y)

Output:

100 111
You cannot use numbers and operators for addition or subtraction.
numberVar = 10
stringVar = "Hello"

result = numberVar + stringVar # this will not work, it will give an error 

Please share this tutorial and comment your queries using POST A COMMENT button below, I respond immediately. Also if you feel this tutorial needs to be corrected or missing something, please comment.

Comments