Python Tutorial

Introduction Python Features Python Applications Python System Requirements Python Installation Python Examples Python Basics Python Indentation Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Python Recursion Anonymous/Lambda Function in Python python apply() Function Python lambda() Function

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Python Super function Python Static Method Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python Python Yield vs Return

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Math Module Python Import Module Python Time Module Python Random Module Python Calendar Module CSV Module in Python Python Subprocess Module Python Subprocess

Python MySQL

Python MySQL Python MySQL Client Update Operation Delete Operation Database Connection Creating new Database using Python MySQL Creating Tables Performing Transactions

Python MongoDB

Python MongoDB

Python SQLite

Python SQLite

Python Data Structure Implementation

Python Stack Python Queue Python Linked List Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Linear regression Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Python Collections Python Commands Python Data Visualization Python Debugger Python DefaultDict Python Enumerate

Python 2

What is Python 2

Python 3

Anaconda in Python 3 Anaconda python 3 installation for windows 10 List Comprehension in Python3

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Best resources to learn Numpy and Pandas in python Check Letter in a String Python Python Console Python Control Statements Convert Float to Int in Python using Pandas Difference between python list and tuple Importing Numpy in Pycharm Python Key Error Python NewLine Python tokens and character set Python Strong Number any() Keyword in python Best Database in Python Check whether dir is empty or not in python Comments in the Python Programming Language Convert int to Float in Python using Pandas Decision Tree Classification in Python End Parameter in python __GETITEM__ and __SETITEM__ in Python Python Namespace Python GUI Programming List Assignment Index out of Range in Python List Iteration in Python List Index out of Range Python for Loop List Subtract in Python Python Empty Tuple Python Escape Characters Sentence to python vector Slicing of a String in Python Executing Shell Commands in Python Genetic Algorithm in python Get index of element in array in python Looping through Data Frame in Python Syntax of Map function in Python After Python What Should I Learn Python AIOHTTP Alexa Python Artificial intelligence mini projects ideas in python Artificial intelligence mini projects with source code in Python Find whether the given stringnumber is palindrome or not First Unique Character in a String Python Python Network Programming Python Interface Python Multithreading Python Interpreter Data Distribution in python Flutter with tensor flow in python Front end in python Iterate a Dictionary in Python Iterate a Dictionary in Python – Part 2 Allocate a minimum number of pages in python Assertion Errors and Attribute Errors in Python Checking whether a String Contains a Set of Characters in python Python Control Flow Statements *Args and **Kwargs in Python Bar Plot in Python Conditional Expressions in Python Function annotations() in Python How to Write a Configuration file in Python Image to Text in python import() Function in Python Import py file in Python Multiple Linear Regression using Python Nested Tuple in Python Python String Negative Indexing Reading a File Line by Line in Python Python Comment Block Base Case in Recursive function python ER diagram of the Bank Management System in python Image to NumPy Arrays in Python NOT IN operator in Python One Liner If-Else Statements in Python Sklearn in Python Cube Root in Python Python Variables, Constants and Literals What Does the Percent Sign (%) Mean in Python Creating Web Application in python Notepad++ For Python PyPi TensorFlow Python | Read csv using pandas.read_csv() What is online python free IDE What is Python online compiler Run exec python from PHP What are the Purposes of Python Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Bitwise Operators Python Identifiers Python Matrix Multiplication Python AND Operator Python Logical Operators Python Multiprocessing Python Unit Testing __init__ in Python Advantages of Python Is Python Case-sensitive when Dealing with Identifiers Python Boolean Python Call Function Python History Python Image Processing Python main() function Python Permutations and Combinations Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python What is Python compiler GDB Python coding platform Python Classification Python | a += b is not always a = a + b PyDev with Python IDE Character Set in Python Best Python AI Projects _dict_ in Python

How to

How to Substring a String in Python How to Iterate through a Dictionary in Python How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python How to Open a file in python with Path How to run a Python file in CMD How to change the names of Columns in Python How to Concat two Dataframes in Python How to Iterate a List in Python How to learn python Online How to Make an App with Python How to comment out a block of code in Python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Number Pattern Programs in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason, Python is easy to access and readability, a general-purpose programming language, and is famous for developers.

In any programming language, fundamental concepts are the foundation; hence, in this article, we will learn the concept of python variables, python constants and python literals as Python is an object-oriented programming language famous for its readability and clear syntax.

We can use it as a procedure-oriented language as well. We can run it on many platforms like Windows, Linux,and MAC.

For example, in Java, we write a code of 250 to 360 lines of code. We can write 10 to 15 lines in Python with the same code, which is a time-reducing process for developers.

What are Variables?

A variable is like a memory location where we can store a value. Now, what we store as a value may or may not change in future.

Now coming back to Python, we have to assign a value to declare a variable.

A variable is created as soon as we assign a value to it. Unlike other programming languages like C, C++, Java, etc., it does not need any commands, which require additional commands for declaration and assignment purposes.

Variable Declaration

x = 50
y = "ABC"
print(x)
print(y)

Output

Python Variables, Constants and Literals

From the above-given example program, we had declared two variables, x and y, and assigned values to them: 50 to x and "ABC" to variable y. When we run this code, we will get 50 and ABC.

We can also perform operations on these variables like addition, subtraction, multiplication, and division, that is, arithmetic operators.

It gives an error if we declare a variable and do not assign any value.

x

Output

Python Variables, Constants and Literals

Now, we try by giving a value to a variable.

x = 45

Output

Here no error will produce because we had declared a variable and assigned a value to it.

Now, we perform an example program to understand better.

x = 20
y = 20
x*y

Output

Python Variables, Constants and Literals

We applied an arithmetic operation that is multiplication for x and y values. The result obtained is 400.

When we declare one lower case and one upper case variable, the result will produce without errors.

x = 20
Y = 20
x*Y

Output

Python Variables, Constants and Literals

The result is the same as the result of the above code; it is not compulsory to declare a variable of all lower and upper cases, and it may be a combination of both.

Variable Data Types

There are six data types in Python, depending on the property they possess.

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

Numbers

Numbers are numerical data types means they have numerical values, and we also have data types like integer, float,and complex numbers. So, integers mainly consist of whole numbers without any decimal point numbers.

We will produce a floating-point number if we add a decimal point number to a whole number.

For complex, we use "j" as an imaginary part,which is added to a number.

For Boolean, it only returns either true or false. So, we use Boolean only for categorical output.

First, we try this as an example.

x = 60
type(x)

Output

Python Variables, Constants and Literals

We used a variable and assigned a value (60) to it. We will use the type () method to find the variable type.

 Let us try another example for this type.

x = 20.09
type(x)

Output

Python Variables, Constants and Literals

The result produced is "float" because we had given a variable with a value of 20.09. So, the value is a decimal point number we get the output as the float. 

To get the output as complex, follow the below code.

x = 45j
print(x)

Output

Python Variables, Constants and Literals

The result produced is "complex" because we had given a variable with the value "45j". When we declare a value with an integer combined with j, the result will be as above.

To understand the Boolean variable, we take a variable and assign a value as 30>20.

When we check the type of that variable, we get it as "bool". Let us understand this by an example.

num = 30 > 20
type(num)

Result

Python Variables, Constants and Literals

It will show us a Boolean type variable because we have used an operator called greater than.It shows a correct type because 30 is greater than 20.

When we only give num as an input, it will give TRUE.

Python Variables, Constants and Literals

Now we will discuss string data type in Python.

String data types in Python are written in "single" or "double quotes". To know better about this, we will discuss an example.

x = 'hello'
y = "world"
z = input()
print("here is an example", x, y, z)

Output

Python Variables, Constants and Literals

From the above code, we had given two variables, x and y, of string data type, and string values 'hello' and "world". We use the square brackets with an index number to access the string values.

At first, we will learn about index numbers by taking an example.

name = 'ABC'
len(name)

Result

3

So, the length of the string is "3". The index numbers will start from "0", and here the letter A index will be "0", and it will move till the end of the string. So, here the end letter is "C", and the index number for the letter "C" is 2. The string length is three, and the index number starts from "0".

Let us try to access the letter from the string using the index number.

name = 'ABC'
name[2]

Result

C

When we write the index number as "2", we will get the letter "C", which has the index number 2.

Well, we will perform operations on strings.

For example, we can change the case of the string; we can replace the values in the string. So, let us check whether to replace the value in the strings or not.

Try to update a value here at index number 2. Instead of the letter C, take B. It throws a type error because we had given the index number as 2. The error is that the string object does not support the item assigned, meaning strings are immutable,and wecan not change them.

Now, to access the series of letters from the string, we can specify the starting index and the colon(:) we can also determine the ending index.

When we give,

name = 'ABC'
name[0:2]

 The above code returns 'AB.' The starting index is "0", and the ending index is "2."

Let us make all letters into uppercase letters.

name = 'Hello World'
name.upper()

Result

Python Variables, Constants and Literals

It returns all the letters in uppercase.

Similarly, we can make all the letters lower case.

name = 'Hello World'
name.lower()

Result

Python Variables, Constants and Literals

It gives all the letters in lower case.

To access the values from the end of the string, we can specify the index numbers by giving negative values.

name = 'ABC'
name[-1]

Result

Python Variables, Constants and Literals

The result is "C", as we had given the negative index as "-1".

So, this was all about the string data type. Now we will move to the "List" data type.

List

A list is a collection of arrays which are changeable and ordered, which means they have indexes just like strings. So, we use the square brackets to declare a list. As we can see here, we have a list named "Fruits", and inside the square brackets, we have the list value.

Example

Fruits = ['apple', 'kiwi', 'banana']
print(Fruits)

Result

Python Variables, Constants and Literals

We must understand that we can declare different data types in the list and merge integers and strings or use other data types in the list. So, let us take an example.

Let's declare a list first and give some integer values and some duplicate values as well. 

Example

mylist = [10, 20, 30, "hello", "courses"]
mylist

Result

Python Variables, Constants and Literals

We get the values which are declared in the list.

Now, let us try to access the list using index numbers like in the string.

mylist = [10, 20, 30, "hello", "courses"]
mylist = [2:4]

Result

Python Variables, Constants and Literals

We get the result as [30, hello]

We can also update the index values just like as strings.

mylist = [10, 20, 30, "hello", "courses"]
mylist = [2] = 35

The result will be [10, 35, 30, "hello", "courses"]

Result

Python Variables, Constants and Literals

We can also add the value to the list using the append() method.

By using this method, it will add the elements to the end of the list.

mylist = [10, 20, 30, "hello", "courses"]
mylist.append(40)
mylist

Result

Python Variables, Constants and Literals

It shows that 40 is added at the end of the list using the append() method. We can also add the element in the middle of the list.

We can also insert an element or string in the middle of the list using the "insert()" method.

Let us take an example showing the insert method.

Example

mylist = [10, 20, 35, 30, "ABC", "courses", 10]
mylist.insert(5, 100)
mylist

Result

Python Variables, Constants and Literals

From the above output, we noticed that element 100 is added at index number 5. So, the difference between insert and append is that by using append, we can only add elements at the end of the list, but by the insert method, we can add the values specifying the index number.

Now, let us do a few operations here on strings. So, let us try reversing the list using the reverse() function.

mylist = [10, 20, 35, 30, "ABC", "courses", 10]
mylist.reverse()
mylist

Result

Python Variables, Constants and Literals

So, by using the reverse() function, we can also reverse the list.

Let us move on to the topic "DICTIONARY"

Dictionary

Dictionary is a collection just like a list, but it is unordered, changeable and indexed. So, we have a key-value pair in a dictionary, and we can use the key as indexes because they are "unique", but we can duplicate the values in the dictionary.

So, let us take an example here. We have the dictionary name as animals and declare the key-value pairs in the curly braces. Let us try this one.

animals = {'mammals' : 'whale', 'reptiles' : 'snake', 'amphibians': 'frogs'}
print(animals)

Result

Python Variables, Constants and Literals

Let us try another example to understand better.

courses = {1: 'python', 2: 'data science', 'third': machine learning'}
courses

We have successfully declared a dictionary with the name "courses" and given values to it. When we print these values, we get the output as follows:

Result

Python Variables, Constants and Literals

We get the result as a key-value pair.

We can access the values in the dictionary using "keys" as indexes.

courses = { 1:'python', 2:'data science', 'third': 'machine learning'}
courses['third']

Result

Python Variables, Constants and Literals

From the above, we understood that when we access the third element, we get the value as "machine learning".

For a similar purpose, we can give the get() method to find the key value there.

courses = { 1:'python', 2:'data science', 'third': 'machine learning'}
courses.get('third')

Result

Python Variables, Constants and Literals

We get the result same as the standard method.

 When we want to replace a value with other, we place the key name and the new element to add to a program.

Example

courses = { 1:'python', 2:'data science', 'third': 'machine learning'}
courses['third']='Ruby'
courses

Result

Python Variables, Constants and Literals

We observed that we had replaced a key with a new value, and it was "Ruby".

 We can also add key-value pairs by using square brackets. So, place a key name and a new element to be added.

courses = { 1:'python', 2:'data science', 'third': 'Ruby'}
courses['four']='machine learning
courses

Result

Python Variables, Constants and Literals

We observed that a new key and a value are added to the dictionary.

Tuple

A tuple is ordered and unchangeable, which means it is immutable, just like a string. We can not make any changes to the tuple once we declare it. But we can have duplicate values as well. Let us try to understand it with an example.

animals = ('lion', 'tiger', 'monkey')
print(animals)

Output

Python Variables, Constants and Literals

We have a tuple named "animals" and a few values.

animals = (10, 10, 20, 'tiger', 'lion, 'giraffe', 'tiger')
animals[2]

Result

Python Variables, Constants and Literals

 We see that tuples are indexed as well. We can use the index value to access the values from the tuple.

Now, since it is immutable and we cannot change it, there are not many operations we can perform on the tuple. But we can count the number of duplicate values using the count() function. We have a duplicate value named "tiger" from the above code. So we will check how many times the tiger has repeated the above.

animals = (10, 10, 20, 'tiger', 'lion', 'giraffe', 'tiger')
animals.count('tiger')

Result

Python Variables, Constants and Literals

So, the value "tiger" was repeated two times in the code.

Let us quickly move on to "SET" now.

Set

A set is a collection like a list or a dictionary, but it is unordered, and there are no duplicate entries. Let us discuss with an example.

Example

myset = {10, 20, 30, 40, 40, 50, 'ABC', 'courses'}
myset

Result

Python Variables, Constants and Literals

We observed that the output was standard set without any exact values by giving duplicate values.

Now, we try to access the elements by using the index number.

myset = {10, 20, 30, 40, 40, 50, ABC, courses}
myset[2]


Result

Python Variables, Constants and Literals

We observed the error that the "set" object does not support indexing which means the set does not have any indexes, and every time will print a set, it will show us a random value. So, this was all about sets, and we moved to "RANGE."

Range

The range is used whenever we are iterating through values. Suppose we want numbers from 0 to 10, and let us put them in the list to get the values.

range(10)
Python Variables, Constants and Literals

We get the output as a range (0,10). The range denotes the minimum and maximum values.

list(range(11)

Result

Python Variables, Constants and Literals

When trying to print values from 0 to 10, we used the "list" to print the range of numbers. When we give 11 in a range, it will provide the values of the list, that is, from 0 to 10.

It is all about range. We take a miscellaneous example; we have two dictionaries with some values.

a = {1, 2, 3, 4}
b = {4, 5, 4, 5, 6}
c = [a, b]
c

Result

Python Variables, Constants and Literals

Let us try to make a list for combining the values of a and b. Let us see by executing it. Printing the value of c will show us that the list c has dictionary a and b values.

It shows that we can make a list with other data types. For example, we can incorporate a dictionary over there. We can also do with the tuple or a set, and if we want some values that we don't want to change in the future, we can make it a tuple and declare it in a list so that we cannot change the value in the future. For example, if we don't want to access any values using indexes, we can make it by using a set so that it will not have any indexes.

So, that is all about data types.

Type Conversion

Suppose we have an integer variable with ten values and a string that says name = 'name'.

x = 10
name = 'name'
x + name

Result

Python Variables, Constants and Literals

When we try to add those integers and strings, it will show a "type error," which says an unsupported operand type. Now for this type, we will use a type conversion here.

Type conversion is used we are trying to covert a type of variable to another data type.

We have many functions here.

  1. int()-This function changes any data type to an integer data type.
  2. float ()-This function changes any data type to float data type.
  3. tuple()-This function changes any data type to the tuple.
  4. list()-This function changes any data type to list.
  5. set()-This function changes any type to a set.
  6. dict()-This function changes any data type to a dictionary.

Now let us look at the example.

x = 10
name = 'name'
str(x) + name
Python Variables, Constants and Literals

When we change the data type of integer to a string, we get the result as error-free. So, it is all about type conversion.

Let us take another example. So, we had a dictionary here with the name "b".

Example

b = {4, 5, 4, 5, 6}
list(b)

Result

Python Variables, Constants and Literals

We used a list function and specified "b" over there. So, we convert a dictionary into a list. So, this is what type conversion means.

Python constants

A python constant is a variable whose value cannot be changed. It is helpful to think of constants as containers containing information that will not change later.

Naming conventions for variables and constants in Python:

  1. Terminology should be a purpose.
  2. Use camelCase notation
  3. Use capital letters to represent a constant symbol like @, #, $, %, etc., should not be used.
  4. Don't start with a digit.
  5. Constants are put into python modules and meant not to be changed.
  6. Constants and variables' 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 (_).

Let us go for a demonstration.

Assigning values to constant in Python

In Python, constants are in-built, declared, and assigned in a module.

So, the meaning of module is a new file containing variables, functions, etc., that will import to the main file.

Let us go for a demonstration using constants.

#Declaring and assigning value to constants
PI=3.14
GRAVITY=9.8

The above values we assigned are built-in constants and contain a constant value, and we must write all the constant names in capital letters. There will be no execution for the above because there is no print statement.

#Declaring and assigning value to a variable
#Declaring and assigning value to a variable
a = "Apple."
print(a)


#Changing the value of a variable
a = "Aeroplane"
print(a)


a = 100
print(a)




#Assigning multiple values to a variable
b, c, d = 1, 2.5, "Hello"
print(b, c, d)


#Assigning the same value to multiple variables
b = c = d = 5
print(b, c, d)




Result

Python Variables, Constants and Literals

We defined how to determine, declare, and assign values to variables.

From above, "a" is a string type, and when we print those values, it will show the same as the print statement.

Changing the value of a variable can be done by reassignment. So, a = "Aeroplane", and when we print this statement, it prints the statement.

Following the line, we gave an integer variable and assigned a value "10" to it, which prints that integer value. So, we observed that when we provide a new value for the same variable, it prints the old and unique value irrespective of data types.

We can also find that the same variable is sometimes initialized with the string and sometimes with the integer, and all these are allowed in Python because Python is a dynamic type language. It means the variable's data types will decide during the runtime. So, during runtime, the variable's value will contain that will determine the variable's data type. In the case of Python, there is no need to declare the variable separately; at the beginning of the code, we can define a variable when we require to use them. We can find that a= "Aeroplane" in the code, so that "a" has got the string data type, and the next part of the code "a" is treated as a string until and unless it is initialized with another data type.

We can also assign multiple values to a variable. So, the codes b, c, and d is the variables that will assign with 1, 2.5, and Hello in a single line.

We can also assign the same value to multiple variables using the same statement in the same line. From above, b = c = d = 5. That is, three variables are assigned to the same value in a single statement and single assignment. So, 5 5 5 will print as the output.

Literals in Python

Literal may be defined as a quantity whose value cannot be changed during the execution of a program.

Types of Literals

These literals are mainly classified into five types.

  1. String
  2. Numeric
  3. Boolean
  4. None
  5. Sequence

And again, strings are of two types:

  1. Single line
  2. Multi line

Numeric is categorized into three types:

  1. Integer
  2. Real
  3. Complex

The sequence is categorized into four types:

  1. List
  2. Tuple
  3. Dictionary
  4. Set

Let us discuss them one by one in brief.

Python Variables, Constants and Literals

String Literals

String literal is a collection of multiple characters. Types of string literal are:

  1. Single Line: It is the collection of various characters within a pair of single quotes (') or double quotes (").

Examples:

"India", 'rs.100', "A", 'Grade', "Fathers name", '1-x-5-k-9'.

      2. Multiline: The collection of multiple characters across multiple lines. It can be created as given in the following examples:

Example:

str = 'Hey'\Hii'

Backslash allows continuing string at the next line.

Example 2:

str = '''Hey Hii'''

Triple quotes at the beginning and end allow the string to continue at multiple lines.

Example 3:

str = """Hey Hii"""

The triple-double quotes at the beginning and end allow the string to continue at multiple lines.

'Hii Hello'

Result

Python Variables, Constants and Literals
"Hii Hello"

Result

Python Variables, Constants and Literals
"hii\
hello"

Result

Python Variables, Constants and Literals

There is no use of what are the quotes for input, and the result will be displayed in a single quote.

Numeric Literal

Numeric literals are those literals which can contain digits only. Types of numeric literals are:

  1. Integer literals
  2. Floating point literals
  3. Complex literals

Integer literals

Integer literals are those which contain numbers without a decimal point. They can be both negative as well as positive. Types of integer literals are: 

Decimal: It has the digits from 0 to 9

       Example: 1234, 45, 70

Octal: It can contain digits from 0 to 7 prefixed with 0o(Zero prefixed by o).

Hexadecimal: It can contain digits from 0 to 9 and alphabets from A to F where A=10, B=11, C=12,      D=13, E=14 and F=15. It is prefixed with 0x.

Example: 0X12, 0XF9A

Binary: It can contain digits 0 and 1. They are prefixed with 0b (Zero followed by alphabet 'b').

Example: 0b101

10

Result

Python Variables, Constants and Literals
0o12

Result

Python Variables, Constants and Literals

It has shown "10"; the octal will convert to a decimal value.

0x12

Result

Python Variables, Constants and Literals

Again, it does the same because it is an octal number, converted into a decimal value of 18.

0b101
Python Variables, Constants and Literals

We gave binary as an input, and we can see that it is showing "5", which is the decimal equivalent of binary 101.

It is all about string literals. Now we will discuss "Floating point literals".

Floating Point Literals

They are also known as real literals. They can contain decimal points to them. They can be written in two ways:

  1. Fractional form
  2. Exponent form

Fractional form

In fractional form, a real number contains a whole number followed by a decimal point(.), further followed by a fractional part. We can omit digits before or after the decimal point, and they can contain both negative and positive values.

Example

12.33, 0.345, -45.344

Exponential form

In this form, a real number is represented in terms of the power of 10. The power of 10 is defined by alphabets E or e. The real number in exponential form has two parts:

  1. Mantissa: The digits before the symbol E from the Mantissa part.
  2. Exponent: The exponent part can only contain integers.
Python Variables, Constants and Literals

          Example: 1.33*105 can be represented as 1.33E5.

          Let us display this one by practical.

2.5

Result

Python Variables, Constants and Literals
2.5e3

Result

Python Variables, Constants and Literals

The above value is exponential, and the output is 2500. 2.5 is multiplied by 1000, that is 10^3.

If the power is enormous, that is 2.5e35; then it will be shown as 2.5e+35.

2.5e35

Result

Python Variables, Constants and Literals

Complex Literal

Complex literals are of the form A + Bj.

Here A and B are real values. A is termed as real part, and B is termed as imaginary part.

"j" represents the square root of -1, an imaginary number.

Example

2.3+3.5j

Here 2.3 is the real value, and 3.5j is the imaginary value.

None literal

It represents something that has not been created yet and is described as None.

Python does not display anything when we try to declare a variable with no value stored; None will be shown.

Example

True
Python Variables, Constants and Literals
False
Python Variables, Constants and Literals
None

Sequence literals

A sequence is a group of comma-separated values. They are of four types.

  1. List: A collection of separate comma values within the pair of square brackets.

 Example:

[10, 20, 30, 40]

Result

Python Variables, Constants and Literals

    2. Tuple: It is a collection of separate comma values within the pair of

     Parenthesis.  

Example

(1, 2, 3, 4)

Result

Python Variables, Constants and Literals

  3. Set: A collection of separate comma values within the pair of curly braces.

Example:

{11, 12, 13, 14}

Result

Python Variables, Constants and Literals

  4. Dictionary: It is a collection of separate comma key: value pairs within the pair of braces.

Example:

(1: 'a', 2: 'b', 3: 'c', 4: 'd')

Result

Python Variables, Constants and Literals

These are all about python literals and their types.

Character literal

It is also a type of string literal where single or double quotes surround a single character.

Size of string

Python determines the size of a string as the count of characters in the string; for example

size of string "xyz" is 3, and "HelloWorld" is 10.

Differences between Variables, Constants and Literal

Variable: It is a name of a location in memory that enables us to store a value for later use.

It is called variable because we can change the content whenever we want.

Example:

int i=10; where "i" is a variable.

Constant: It is like a variable. The only difference between constants and variable is that they cannot be changed once defined.

Example:

Const int i = 10;

Here "i" is a constant, and we cannot change the value \\ throughout the execution life cycle of a program.

Literals: Literals are values assigned to variables and constants.

Example: const int i = 10;

"10" is literal, and "i" here is a variable, and when we declare a "const" keyword and so, it becomes constant, and we cannot change its value for further program execution.

So, there are many types of variables, constants and literals. We all learnt it here, which is also helpful for python basics.



ADVERTISEMENT
ADVERTISEMENT