CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

08 April, 2022

Python Variables

 Programing Coderfunda     April 08, 2022     Python     No comments   

Python Variables

Variable is a name that is used to refer to memory location. Python variable is also known as an identifier and used to hold value.

In Python, we don't need to specify the type of variable because Python is a infer language and smart enough to get variable type.

Variable names can be a group of both the letters and digits, but they have to begin with a letter or an underscore.

It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two different variables.

Identifier Naming

Variables are the example of identifiers. An Identifier is used to identify the literals used in the program. The rules to name an identifier are given below.

  • The first character of the variable must be an alphabet or underscore ( _ ).
  • All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore, or digit (0-9).
  • Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
  • Identifier name must not be similar to any keyword defined in the language.
  • Identifier names are case sensitive; for example, my name, and MyName is not the same.
  • Examples of valid identifiers: a123, _n, n_9, etc.
  • Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values

Python does not bind us to declare a variable before using it in the application. It allows us to create a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the variable, that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Object References

It is necessary to understand how the Python interpreter works when we declare a variable. The process of treating variables is somewhat different from many other programming languages.

Python is the highly object-oriented programming language; that's why every data item belongs to a specific type of class. Consider the following example.

  1. print("John")  

Output:

John

The Python object creates an integer object and displays it to the console. In the above print statement, we have created a string object. Let's check the type of it using the Python built-in type() function.

  1. type("John")  

Output:

<class 'str'>

In Python, variables are a symbolic name that is a reference or pointer to an object. The variables are used to denote objects by that name.

Let's understand the following example

  1. a = 50   

Python Variables

In the above image, the variable a refers to an integer object.

Suppose we assign the integer value 50 to a new variable b.

a = 50

b = a


Python Variables

The variable b refers to the same object that a points to because Python does not create another object.

Let's assign the new value to b. Now both variables will refer to the different objects.

a = 50

b =100


Python Variables

Python manages memory efficiently if we assign the same variable to two different values.

Object Identity

In Python, every created object identifies uniquely in Python. Python provides the guaranteed that no two objects will have the same identifier. The built-in id() function, is used to identify the object identifier. Consider the following example.

  1. a = 50  
  2. b = a  
  3. print(id(a))  
  4. print(id(b))  
  5. # Reassigned variable a  
  6. a = 500  
  7. print(id(a))  

Output:

140734982691168
140734982691168
2822056960944

We assigned the b = a, a and b both point to the same object. When we checked by the id() function it returned the same number. We reassign a to 500; then it referred to the new object identifier.

Variable Names

We have already discussed how to declare the valid variable. Variable names can be any length can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore character(_). Consider the following example of valid variables names.

  1. name = "Devansh"  
  2. age = 20  
  3. marks = 80.50  
  4.   
  5. print(name)  
  6. print(age)  
  7. print(marks)  

Output:

Devansh
20
80.5

Consider the following valid variables name.

  1. name = "A"  
  2. Name = "B"  
  3. naMe = "C"  
  4. NAME = "D"  
  5. n_a_m_e = "E"  
  6. _name = "F"  
  7. name_ = "G"  
  8. _name_ = "H"  
  9. na56me = "I"  
  10.   
  11. print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)  

Output:

A B C D E D E F G F I

In the above example, we have declared a few valid variable names such as name, _name_ , etc. But it is not recommended because when we try to read code, it may create confusion. The variable name should be descriptive to make code more readable.

The multi-word keywords can be created by the following method.

  • Camel Case - In the camel case, each word or abbreviation in the middle of begins with a capital letter. There is no intervention of whitespace. For example - nameOfStudent, valueOfVaraible, etc.
  • Pascal Case - It is the same as the Camel Case, but here the first word is also capital. For example - NameOfStudent, etc.
  • Snake Case - In the snake case, Words are separated by the underscore. For example - name_of_student, etc.

Multiple Assignment

Python allows us to assign a value to multiple variables in a single statement, which is also known as multiple assignments.

We can apply multiple assignments in two ways, either by assigning a single value to multiple variables or assigning multiple values to multiple variables. Consider the following example.

1. Assigning single value to multiple variables

Eg:

  1. x=y=z=50    
  2. print(x)    
  3. print(y)    
  4. print(z)    

Output:

50  
50  
50  

2. Assigning multiple values to multiple variables:

Eg:

  1. a,b,c=5,10,15    
  2. print a    
  3. print b    
  4. print c    

Output:

5  
10  
15  

The values will be assigned in the order in which variables appear.

Python Variable Types

There are two types of variables in Python - Local variable and Global variable. Let's understand the following variables.

Local Variable

Local variables are the variables that declared inside the function and have scope within the function. Let's understand the following example.

Example -

  1. # Declaring a function  
  2. def add():  
  3.     # Defining local variables. They has scope only within a function  
  4.     a = 20  
  5.     b = 30  
  6.     c = a + b  
  7.     print("The sum is:", c)  
  8.   
  9. # Calling a function  
  10. add()  

Output:

The sum is: 50

Explanation:

In the above code, we declared a function named add() and assigned a few variables within the function. These variables will be referred to as the local variables which have scope only inside the function. If we try to use them outside the function, we get a following error.

  1. add()  
  2. # Accessing local variable outside the function   
  3. print(a)  

Output:

The sum is: 50
    print(a)
NameError: name 'a' is not defined

We tried to use local variable outside their scope; it threw the NameError.

Global Variables

Global variables can be used throughout the program, and its scope is in the entire program. We can use global variables inside or outside the function.

A variable declared outside the function is the global variable by default. Python provides the global keyword to use global variable inside the function. If we don't use the global keyword, the function treats it as a local variable. Let's understand the following example.

Example -

  1. # Declare a variable and initialize it  
  2. x = 101  
  3.   
  4. # Global variable in function  
  5. def mainFunction():  
  6.     # printing a global variable  
  7.     global x  
  8.     print(x)  
  9.     # modifying a global variable  
  10.     x = 'Welcome To Javatpoint'  
  11.     print(x)  
  12.   
  13. mainFunction()  
  14. print(x)  

Output:

101
Welcome To Javatpoint
Welcome To Javatpoint

Explanation:

In the above code, we declare a global variable x and assign a value to it. Next, we defined a function and accessed the declared variable using the global keyword inside the function. Now we can modify its value. Then, we assigned a new string value to the variable x.

Now, we called the function and proceeded to print x. It printed the as newly assigned value of x.

Delete a variable

We can delete the variable using the del keyword. The syntax is given below.

Syntax -

  1. del <variable_name>  

In the following example, we create a variable x and assign value to it. We deleted variable x, and print it, we get the error "variable x is not defined". The variable x will no longer use in future.

Example -

  1. # Assigning a value to x  
  2. x = 6  
  3. print(x)  
  4. # deleting a variable.   
  5. del x  
  6. print(x)  

Output:

6
Traceback (most recent call last):
  File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in 
    print(x)
NameError: name 'x' is not defined

Maximum Possible Value of an Integer in Python

Unlike the other programming languages, Python doesn't have long int or float data types. It treats all integer values as an int data type. Here, the question arises. What is the maximum possible value can hold by the variable in Python? Consider the following example.

Example -

  1. # A Python program to display that we can store  
  2. # large numbers in Python  
  3.   
  4. a = 10000000000000000000000000000000000000000000  
  5. a = a + 1  
  6. print(type(a))  
  7. print (a)  

Output:

<class 'int'>
10000000000000000000000000000000000000000001

As we can see in the above example, we assigned a large integer value to variable x and checked its type. It printed class <int> not long int. Hence, there is no limitation number by bits and we can expand to the limit of our memory.

Python doesn't have any special data type to store larger numbers.

Print Single and Multiple Variables in Python

We can print multiple variables within the single print statement. Below are the example of single and multiple printing values.

Example - 1 (Printing Single Variable)

  1. # printing single value   
  2. a = 5  
  3. print(a)  
  4. print((a))  

Output:

5
5

Example - 2 (Printing Multiple Variables)

  1. a = 5  
  2. b = 6  
  3. # printing multiple variables  
  4. print(a,b)  
  5. # separate the variables by the comma  
  6. Print(1, 2, 3, 4, 5, 6, 7, 8)   

Output:

5 6
1 2 3 4 5 6 7 8

Basic Fundamentals:

This section contains the fundamentals of Python, such as:

i)Tokens and their types.

ii) Comments

a)Tokens:

  • The tokens can be defined as a punctuator mark, reserved words, and each word in a statement.
  • The token is the smallest unit inside the given program.

There are following tokens in Python:

  • Keywords.
  • Identifiers.
  • Literals.
  • Operators.

We will discuss above the tokens in detail next tutorials.


  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Python DictionaryPython DictionaryPython Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python, which can simulate… Read More
  • Python SetPython SetA Python set is the collection of the unordere items. Each element in the set must be unique, and immutable, and the sets remove the duplica… Read More
  • Python List Vs TuplePython List Vs TupleIn this tutorial, we will learn the important difference between the list and tuples and how both are playing a significant role i… Read More
  • Python TuplePython TuplePython Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists since the value of the items stored … Read More
  • Python StringPython StringTill now, we have discussed numbers as the standard data types in Python. In this section of the tutorial, we will discuss the most popul… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Spring boot app (error: method getFirst()) failed to run at local machine, but can run on server
    The Spring boot app can run on the online server. Now, we want to replicate the same app at the local machine but the Spring boot jar file f...
  • Log activity in a Laravel app with Spatie/Laravel-Activitylog
      Requirements This package needs PHP 8.1+ and Laravel 9.0 or higher. The latest version of this package needs PHP 8.2+ and Laravel 8 or hig...
  • Laravel auth login with phone or email
          <?php     Laravel auth login with phone or email     <? php     namespace App \ Http \ Controllers \ Auth ;         use ...
  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh
    I had follow these steps to install an configure firebase to my cordova project for cloud messaging. https://medium.com/@felipepucinelli/how...
  • Vue3 :style backgroundImage not working with require
    I'm trying to migrate a Vue 2 project to Vue 3. In Vue 2 I used v-bind style as follow: In Vue 3 this doesn't work... I tried a...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Auto-translate Application Strings with Laratext - 5/16/2025
  • Simplify Factory Associations with Laravel's UseFactory Attribute - 5/13/2025
  • Improved Installation and Frontend Hooks in Laravel Echo 2.1 - 5/15/2025
  • Filter Model Attributes with Laravel's New except() Method - 5/13/2025
  • Arr::from() Method in Laravel 12.14 - 5/14/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda