Python Variables & Data Types (With Easy Examples)
Variable and Data Type in Python
Introduction
After learning Python syntax and indentation, the next most important topic is variables and data types. Every beginner must understand this because variables are used to store values, and data types are used to define the kind of data they contain.
In this blog, you'll learn more about variables, how to declare them, and different data types in Python.
No prior data knowledge is required.
What is a variable?
A variable is used to store data in memory, whose memory values can be changed or manipulated during program run.
In python to create a variable, just assign a value to its name. Suppose you have to create a variable to assign a student's name, then you can just name the variable Student and assign a value to it. If you need to create a variable to store age, write 'Age' and assign the value to it. In Python, we don't need to declare the data type, as the language automatically determines the data type.
For example:
Student = "Mr. Python"
Age= "16"
Rules for naming variables:
- Name must start with a letter (a-z) (both capital and small)
- Can also start with underscore (eg: _School, _age)
- Can not start with numbers and can not use keywords(eg.: for, if, def)
Python is dynamically typed.
What are Data types?
c. Floating point data type
In Python, floating-point numbers represent machine-level double-precision floating-point numbers. It stores a decimal number.ex- num=2.13
price=9.002
2. Data types for String
A string can hold any type of known characters, i.e., letters, numbers, and special characters of any known scripted language.
following are all legal strings in Python:
"abcd" , "1234" , "#@$%", "???/" and much more anything that is written inside quote " " or ' '.
A Python string is a sequence of characters, and each character can be individually accessed using an index.
3. List
A list in Python represents a group of comma-separated values of any data type written inside square brackets. Values in the list can be changed or modified. For instance :
numbers = [1,2,3,4,5]names =["Joyti", "Drishti", "Geeta"]
4. Tuple
Tuples are represented as a group of comma-separated values of any data type within parentheses. Values in a tuple can not be modified, e.g.,
weeks = ("mon", "tue", "wed")
5. Dictionary
A dictionary is an unordered set of comma-separated key-value pairs written within {}. e.g.,
student={ "name": "Rahul",
"age": 20,
"marks": 88
}
Checking Data Type
Use the type() function to find the data type of the value. e.g.,
x= 10print(type(x))
The output of the above code is<class 'int'>
Summary
- Variable store data
- Python automatically assign data types
- Common data types are integer, float, boolean, list, tuple, dictionary, string.
Checking Data Type
Summary
- Variable store data
- Python automatically assign data types
- Common data types are integer, float, boolean, list, tuple, dictionary, string.
Comments
Post a Comment