Variable Types

Variable Types


Variables are nothing but reserved memory locations to store values. It means that when you create a variable, you reserve some space in the memory.

 

In other or common language Variables act like a container that is capable to contain something whatsoever you wanna store in that.

Suppose, you want to go somewhere and you wanna carry some water you have many types of container which can store water but what is good for you?

You have two options 1st is tank and 2nd is bottle. What will you choose?

I hope everyone of you will choose bottle because you can carry it anywhere easily and it is more convenient as well. But now situations are change now you have to store water for a day. where you will cook food, wash cars, do cleaning....etc. In this case one bottle is not enough at all for this kind of need. 

In programing there are many types container but you will have to choose one of them according to your need.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store integers, decimals or characters in these variables.

Assigning Values to Variables

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
 

The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.

coding = "python"
print(variable)
 

Output:    

python

  

 In the above code, we assigned a value python to the variable "python". Then, we printed out the value assigned to coding i.e. python   

Output:    

python

Multiple Assignment

Python allows you to assign a single value to several variables simultaneously.

For example-

a = b = c = 1

Here, an integer object is created with the value 1, and all the three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables.

For example- 

a, b, c = 1, 2, "john" 

Here, two integer objects with values 1 and 2 are assigned to the variables a and b  
respectively, and one string object with the value "john" is assigned to the variable c.

Rules and Naming Convention for Variables

1.Constant and variable names should have a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:

var_with_lowercase
VAR_WITH_UPPERCASE
varWithcamelCase
VarWithCapWords

2.Create a name that makes sense. For example, vowel makes more sense than v.

If you want to create a variable name having two words, use underscore to separate them. For example:

my_name
current_salary 

3.Use capital letters possible to declare a constant. For example:

PI
G
MASS
SPEED_OF_LIGHT
TEMP

4.Never use special symbols like !, @, #, $, %, etc.

5.Don't start a variable name with a digit.

Literals

In the beginning we have seen what  is container and what it does. Basically conatainer stores something and whatsoever it stores, we call that "Literals" in porgaming language.
 "Literals are values that you provide or assigned to any variable"

Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as follows:

Numeric Literals

Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different numerical types: IntegerFloat, and Complex


Output : 

In above code

1. We assigned integer literals into different variables. Here, a is binary literal, b is a decimal literal, c is an octal literal and d is a hexadecimal literal.

2. When we print the variables, all the literals are converted into decimal values.

3. 10.5 and 1.5e2 are floating-point literals. 1.5e2 is expressed with exponential and is equivalent to 1.5 * 102.

4. We assigned a complex literal i.e 3.14j in variable x. Then we use imaginary literal (x.imag) and real literal (x.real) to create imaginary and real parts of complex numbers.

String literals

A string literal is a sequence of characters surrounded by quotes. We can use both single, double, or triple quotes for a string. And, a character literal is a single character surrounded by single or double quotes.



Output

This is Python
C
This is a multiline string with more than one line code.
Ünicöde
raw \n string

In the above program, This is Python is a string literal and C is a character literal.

The value in triple-quotes """ assigned to the multiline_str is a multi-line string literal.

The string u"\u00dcnic\u00f6de" is a Unicode literal which supports characters other than English. In this case, \u00dc represents Ü and \u00f6 represents ö.

r"raw \n string" is a raw string literal.


Boolean literals

A Boolean literal can have any of the two values: True or False.

x = (1 == True)
y = (1 == False)
a = True + 4
b = False + 10

print("x is", x) print("y is", y) print("a:", a) print("b:", b)

Output

x is True
y is False
a: 5
b: 10

In the above program, we use boolean literal True and False. In Python, True represents the value as 1 and False as 0. The value of x is True because 1 is equal to True. And, the value of y is False because 1 is not equal to False.

Similarly, we can use the True and False in numeric expressions as the value. The value of a is 5 because we add True which has a value of 1 with 4. Similarly, b is 10 because we add the False having value of 0 with 10.


Special literals

Python contains one special literal i.e. None. We use it to specify that the field has not been created.

drink = "Available"

food = None

def menu(x):

if x == drink:

print(drink)

else:

print(food)

menu(drink)

menu(food)

Output

Available
None

In the above program, we define a menu function. Inside menu, when we set the argument as drink then, it displays Available. And, when the argument is food, it displays None.


Literal Collections

There are four different literal collections List literals, Tuple literals, Dict literals, and Set literals.


Output

['apple', 'mango', 'orange']
(1, 2, 3)
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'e', 'a', 'o', 'i', 'u'}

In the above program, we created a list of fruits, a tuple of numbers, a dictionary dict having values with keys designated to each value and a set of vowels.


 

Standard Data Types

This is one of the crucial  thing in any programing language, for instance yougo your school and you carry notebooks,books,pen,water-bottle,lunch-box....ect.

How can you carry all those things? The simple way that everyone knows use a bag and putt all those things in bag. 

In above example books.notebooks,pens,bottle these all are diffrent types of thing.

In progarming language if you want to store many kind of literals in one variable in this case you have to use standard data types.

The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.

Python has five standard data types

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary

Let' explore one by one

Python Numbers   

Number data types store numeric values. Number objects are created when you assign a value to them. For example-

 

var1 = 1
var2 = 4  

Python supports three different numerical types −

1. int (signed integers)
2. float (floating point real values)
3. complex (complex numbers)
 

All integers in Python 3 are represented as long integers. Hence, there is no separate number type as long.

A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are real numbers and j is the imaginary unit.

Python Strings

Strings in Python are identified as a contiguous set of characters represented in the  
quotation marks. Python allows either pair of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.
 

var = "Hello World!"

print(var)
print(var[2:5])
print(2:)
print(var * 2)
print(var + "TEST")

This will produce the following result-

Hello World!
llo
llo World!  
Hello World!Hello World!

Hello World!TEST

Python Lists

Lists are the most versatile of Python's compound data types. A list contains items  
separated by commas and enclosed within square brackets ([]). To some extent, lists are  
similar to arrays in C. One of the differences between them is that all the items belonging  
to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with  
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus  
(+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd 
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) # Prints concatenated lists

This produces the following result-

['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

Python Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a  
number of values separated by commas. Unlike lists, however, tuples are enclosed within parenthesis.
The main difference between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

For example-

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print(tuple) # Prints complete tuple
print(tuple[0]) # Prints first element of the tuple
print(tuple[1:3]) # Prints elements starting from 2nd till 3rd print(tuple[2:]) # Prints elements starting from 3rd element print(tuple * 2) # Prints list two times print(tuple + tinytuple) # Prints concatenated tuple

This produces the following result-

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john') 

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists −

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list[0] = "change"  # Invalid syntax with tuple
tuple[0] = "change" # Invalid syntax with tuple

Python Dictionary

Python's dictionaries are kind of hash-table type. They work like associative arrays or  hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example-

#!/usr/bin/python3
dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print (dict['one']) # Prints value for 'one' key print (dict[2]) # Prints value for 2 key print (tinydict) # Prints complete dictionary print (tinydict.keys()) # Prints all the keys print (tinydict.values()) # Prints all the values 
This produces the following result
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Post a Comment

0 Comments