Variable And Data Types In Python - Learn Python For Beginners Free

VARIABLE AND DATA TYPES

Variable

Variables are like small boxes made in computer memory in which anything can be stored. When we declare a variable, the computer assigns certain memory to that variable. Values ​​can be stored in the memory location of each variable. Again the value of that location can be accessed and utilized using that name when needed. Variables are the names that are used to store data in the program. In this chapter, we will learn how to do this in Python. Before that, let's find out what kind of data can be. We usually use 2 types of numbers. Integers and decimal numbers. In the language of the program, the first is an integer, the second is float and the rest of the letters and symbols are called characters.

The programming language is designed to facilitate the processing of Number, character, and string type data aggregates. This is done for the purpose of getting effective output or information. Data processing is done through the periodic execution of specific instructions or instructions used in a program. To create a program, it needs some basic elements like keyword, identifier, constant, string, some special symbols or operators, etc. Each of these elements is called a token in the C language. The characters, numbers, or symbols that are used to create these tokens can be divided into four parts. . E.g.

Letters: Upper & Lowercase from A to Z

  • Digits 0, 1, 2 ---- All decimal digits up to 9 Special Characters (Special Characters) Comma (,), Semicolon (;), colon (:), quotation
  • mark ("), backslash (\), dollar sign ($), underscore (-) & ampersand, ^ caret, * asterisk, - Minus sign, + plus sign, <opening angle bracket (or less than sign),> There are more characters on the keyboard besides Letters and Digits, including closing angle bracket, (or greater than sign).

  • White Spaces (Blank space), Horizontal tab, Carriage return, Newline or From feed, etc. between two letters or words.



Assigning Values to Variables

An equal (=) symbol is used to store any value in a variable. So far we have not used any variables in the chapters. So whenever we type a number text or statement in the Python console and press the Enter key, its output is shown in the next line. But if we store a value in a variable (with an equal sign) and press enter then the output will not come in the next line. Instead, the value on the right side of the equal sign will be stored in the variable on the left side of the equal sign which we can use by mentioning the name in the next statement.

Variable: Variable usually means variable. However, in the language of the program, variables are the names of certain memory ranges. However, for the convenience of programming, the data used in the program is stored in memory before being used in the program. And to save any data in memory, you need to know the address of the memory location in which you want to save, which is a difficult task for the program. To avoid this complication, one or more memory cell names are used and the data is stored under that name instead of directly using the memory location address to store the data during programming. The main purpose of using this variable to name the memory cell used by the programmer in the program is to use the address of the memory location to store the data in the memory location. This variable can have any name, but there are some rules to follow in determining the name of a variable in the Python program. It is discussed below:

Rules for naming variables:

  • Programming Essentials
  • When writing variables in Python, variables are defined according to certain rules.
  • The name of the variable must be one word. That is, variables cannot be viewed in this way by my variable 10.
  • The first letter must be an alphabetic letter (uppercase or lowercase) or underscore such as Nafis, a, b, the variable can be written as a variable but 1name, @nafis, 7a,% b can be written later without the first letter using the letter, underscore, number Yes, but Python's convention is that the name of the variable should always start with a lowercase letter.
  • Not the same variable. Python Case Sensitive means a = and A W
  • Python has some reserved keywords that cannot be used.

E.g., if, else, elif, for, while break, continue, except, as, in, is, True, False, yield, None, del, class, etc.

>>> this_is_a_normal_name = 7.

>>> 123abc

Syntaxerror: invalid syntax

>>> space are not allowed SyntaxError: invalid syntax

Explain why the following variables are not valid for the Python program:

Variable

5a

Reason for not being accurate

The first letter digit of the variable is used

Special characters (.) Are used between names

This is a Python keyword.

Blank space between variable names is not acceptable.

Classification of variables: There are four types of C-variables. E.g.


Explain why these are not valid for the Python program:

  • Reason for not being accurate
  • The first letter digit of the variable is used. Special character (-) is used between names.
  • This is a Python keyword.
  • Blank space between variable names is not acceptable


Causes of incorrect variables

  1. Integer type variable 2. Character type variable (Character type variable)
  2. Float type variable
  3. Double type variable


Integer type variable: This variable works with integer type data. It can contain positive and negative integers and its limitation is - no comma (,) can be used between numbers when writing integer numbers from 32768 to + 32767. 

Example: a = 10. (2) Character type

Variable: This variable works with Character type data. It can be used to hold a character equivalent to any number between - 128 to + 127. That means the computer key can accept variables in all the characters on the board. It can be used in two ways. Namely (a) using direct letters. That is if the character variable is ch and its value a has to be given

To write. char_ch = 'a'; In this case, you must use a single quotation on both sides of the character. Character data can also be provided using ASCII values. In this case, the value of the character has to be provided according to the ASCII code. If the value of the character variable named ch is to be given as a, then do not write char ch = 'a' as the ASCII code value of a is 97 so char ch = 97; It can be written in this way. Such a variable occupies 1-byte space in memory.

Afloat type variable is used to work with float type data. That is Decimal numbers can be given as values ​​of variables. For example: \ Pi oat ~ a = 10.25. Float type data

Example. Hyte occupies space in such variable memory. The value of the float variable is 3-40-38

Can be given up to 3-40 + 38.


(4) Double type variable is used to work with variable double type data. This Can work with data larger than float type. The value of this variable becomes 17ee + 308 in 1-7e-308 Stays and occupies 8-byte space in memory. Such as double a = 1.7e300. An example of double data


Local & Global Variable

The properties of a variable in a C-program vary depending on the position in which it is used. The position of the variable

The variables of a C-program can be divided into two parts depending on the properties or the scope. E.g.

- Local variable

- Global variable

Local Variable: Variables whose function is limited to a specific part or function

Is limited to what is called a local variable. When the value and existence of a variable is limited to the corresponding function only

Stays. This value cannot be used directly in other functions. 7 as long as a function is worked on

The local variables of the function remain active. Local variables automatically at the end of the function of a function

The memory range allocated for becomes empty. The result is the same name and data type local in two or more functions

Variables can be used and there is no problem.


Global Variable: When the functionality of a variable is not limited to a specific function

Since its value can be used in all functions it is called a global variable. The value and existence of a global variable

It is not limited to specific blocks or functions but extends throughout the program. Of such variable functions

Not in; Is declared on the function. printf ("Value of Local Variable x =% d", x)


Output:

Value of Global Variable x = 100 Value of Local Variable x = 20 Multiple Variable Assignment

(State Multiple Assignment)

Python allows multiple variable declarations on the same line. A specific value can be stored for so many variables. Again, multiple values ​​can be stored together for multiple variables. This method of variable declaration in Python is called multiple variable assignments. E.g.


Assignment:

>>> x = 7 >>> print (x)

7

>>> print (x + 3)

10

>>> print (x)

7

In the example above, 7 (an integer number) is first stored in a variable x. In the next line, that x has been sent as an argument for the X print () function. And we already know that if something is sent as argument X of the print function, it gets printed. So, the number x i.e. 7 is printed on the screen. The same thing has been done in the print (x + 3) line. Here basically print (7 + 3) this statement is executed, because the value of x is 7. plus 3 plus

The number 10 is sent as an argument to the print function which is printed on the screen.

Done.

In the last print statement, we were also able to print the value of x i.e. 7 with the name of the variable. So to speak, a

Variables store their values ​​throughout the entire program.

Describe Standard Data Types

Programming means data processing. Programming is impossible without data. To write a program on a computer, the computer must input data for that particular program. Any value used in the program is data. Python can work with almost all types of data like integer, float point, character, screening, logical, etc. However, there are five types of standard data types in Python based on data quality, type, and memory space-saving. E.g.


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


Numbers: Numbers are any type of number. Python supports 4 types of numbers. E.g.


* int (a small integer)

* long (can be expressed as large integers, octal or hexadecimal)

* float

* complex



Strings: Strings are letters/words used in quotation marks (“*). With the help of different slice operators ([[and [:]), it can be seen as a part of a defined string or as a different rearrangement output. E.g.


#! / usr / bin / python str = Hello Hasan

print str # Prints the complete string

print str [0] # Prints first character of the string

print str [2: 5] # Prints characters starting from 3rd character print str [2:] # Prints string starting from 3rd character

print str 2 # Prints string two times print str + "Welcome" # Prints concatenated string


Hello Hasan!

H

llo

llo Hasan!


Hello Hasan! Hello Hasan!

Hello Hasan! Welcome

Lists list is a separate item with commas in brackets (1). E.g.

# 1 / usr / bin / python

list [Mahi 786, 2.23, 'Hasan', 702) tinylist- [132, 'Hasan']

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: 1 # Prints elements starting from 3rd element

print tiny list 2 # Prints list twice. print list + finalist #Prints concatenated lists


The result

['Akhi', 786, 2.23, Anu ', 70,200000000000003] Akhi

[786, 2.23]

[2.23, 'Hasan', 70.200000000000003]

[123, 'Hasan', 123, Hasan '[' Akhi ', 786, 2.23, Hanan', 70.200000000000003, 123, Hasan)


Tuples: Tuple and List are basically the same, the only difference is that Tuple uses parentheses (), but List uses brackets []. Also, the value of Tuple cannot be changed later (read-only values), but the value of List can be updated.


Example of tuple:

#! / usr / bin / python

tuple = ('Mahi', 786,2.23, 'Hasan', 70.2) tinytuple = (123, 'Mahi')

print tuple # prints complete list

print tuple [0] # Prints first element of the list

print tuple [1: 3] # Prints elements starting from 2nd to 3rd print tuple [2:] # Prints elements starting from 3rd element

print tiny tulle * 2 # Prints list two times print tuple + tiny tulle # Prints concatenated lists

The result

(Akhi ', 786,2.23,' Hasan ', 70.200000000000003)

Akhi

(786, 2.23)

(2.23, 'Hasan,' 70.200000000000003)

(123, 'Hasan', 123, 'Hasan') ('Akhi', 786, 2.23, 'Hasan', 70.200000000000003, 123, 'Hasan') The following Tuple code is incorrect because attempting to change / update Tuple's value Done. But for the list

33 is correct.


#! / usr / bin / python tuple = ('Akhi', 786, 2.23, 'Hasan',

70.2)

list = ['Akhi', 786, 2.23, 'Hasan', 70.2]

tuple [2] = 1000 # Invalid syntax with tuple list [2) 1000 # Valid syntax with


Dictionary: Key-Value in pairs in the dictionary. Any data type can be a key, although numbers or strings are usually recorded as a key. On the other hand, any number/object can be recorded as a value. The dictionary is expressed using Bracket এবং and the dictionary with Bracket [].


Value is assigned. E.g.


#! / usr / bin / python

dict = 1

dict ['one'] = "This is one" dict [2] = "This is two"


tinydict = name 'name': 'Anu', 'code', 6734, 'dept ,:' sales'} print dict ['one' # Prints value for 'one' key Print tinkydict # Prints complete dictionary print tinydict. keys () # Prints all the keys and prints tinydict. values ​​() # Prints all the values


Print dict [2] # Prints value for 2 key


The result

This is one

This is two

'dept': 'sales,' 'code;' 6734 'name': 'Anu'

['dept', 'code', name ']

['sales, 6734,' Anu]

Note that there is no need to keep the order, serial or order in the dictionary

3 Data type conversion


Explain Data Type Conversion

Data Type conversion means converting a variable from one type to another. It is also called typecasting. Python has some built-in functions for typecasting. We can easily use them if we want. So far we have learned about integers, floats, and strings data types. To convert to this type

The functions are - int), float, str) respectively.

Conversion at Integer

The int () function is used to convert from string or float to integer.

# String to Integer Conversion >>> int ("123")

123

#float to Integer Conversion >>> int 12.3)

12

Note: When converting from string to integer, care must be taken so that there are no non-numeric characters in the string.

>>> int ("123a")

Traceback (most recent call last): File "<stdin>, line 1, in <module>

ValueError: invalid literal for int () with base 10: '123a'

Conversion at float

The float () function is used to convert a string or integer to afloat.

# String to float Conversion

>>> float ("123.456") 123.456

# integer to float Conversion

>>> float (123) 123.0


Note: In this case also, when converting from string to float, care must be taken in the string so that there is no nonnumo ACTRIPLE CAMERA and not more than one decimal point.

"Now think about it, if the string has a decimal number inside it and you have to use the integer int () function? The answer is no.

In that case, if the string needs to be converted to a float first and the float to an integer, is it necessary to use the int () function? The answer is no.


>>> float ("123456) 123.456

>>> int (123,456)

123

>>> int ("123456)

Traceback (most recent call last): File, "<stdin>", line 1, in <module>

ValueError: invalid literal for int () with base 10: '123.456'

Conversion to string


I will use the str () function to convert any variable string without any restrictions. We have to use string conversion when we write more than one variable inside the Print function. >>> print ("Float =" + str (10.5) + "Integer = str (50))

Float = 10.5 Integer = 50 The following are some of the functions of data type conversion.

Function

int (x [, basel)

long (x [, base])

float (x)

comlex (real [, imag])

str (x)

repr (x)

eval (str)

tuple (s)

list (s)

set (s)

dict (d)

frrozenset (s)

chr (x)

unichr (x)

ord (x).

hex (x)

oct (x)


Description

Converts x to integers, and specifies the base if x is a string

Converts x to a long integer, and specifies the base if x

Is a string.

Converts x to a floating-point number.

Creates complex numbers.

Converts * to a string representation.

Converts x to an expression string. Evaluates a string and creates a new object.

Converts s to a tuple.

Converts s to list.

Converts s to set.

Creates a dictionary. However, d must be tuples of (key, value) format

Must be.

Converts s to frozen set.

Converts an integer number to a character.

Converts an integer number to a Unicode character. A single character expresses its integral meaning.

Converts an integer to a hexadecimal string.

Converts an integer to an octal string.


If you are really interested in the programming language visit this relevant article

Post a Comment

Thanks for your comment

Previous Post Next Post