Variables in python

If a software language is easy in terms of declaring variables, then consider that half of the time and efforts are saved. Python is one of the easiest and convenient languages for declaring variables.”

Topics: ,

If a software language is easy in terms of declaring variables, then consider that half of the time and effort are saved. Python is one of the easiest and most convenient languages for declaring variables. We will dive deep into the variables of Python, their rules of declaration, and basic information about variables.

Basic Data Types

  • Integers
  • Floating-Point numbers
  • Strings
  • Complex number
  • Boolean Type

1. Declaring variables and assigning variables

  • Many Languages like c++, Java and c need us to declare a variable before using it.
  • Python does not require the declaration of variables to a certain data type. Just assigning a variable is enough to declare it.
  • To assign a Variable, we simply need to use the = operator.
Python
Python
Python
# Declare string 
name='john doe'
name
Output
'john doe'
Python
Python
Python
Python
# Declaring integer
num=5
num
Output
5
Python
Python
Python
Python
# Declaring Float
pi=3.14
pi
Output
3.14
Python

2. Variable names

What to consider before naming variables?

Rule 1: Variable names must not start with numbers.

Python
Python
Python
 # declare variable five
 five=5
 print(five)
Output
5
Python
Python
Python
Python
# declare variable f5
f5=5
print(f5)
Output
5
Python

Rule 2: Variable names must not include these special symbols.

, < > / + @ – ‘ “” : ? # % ^ & * ~ | \ !

Python
Python
Python
# using special symbol & in variable.
jacknjill='hill'
# using special symbol @ in variable.
johndoemail='johndoe@gmail.com'

print(jacknjill)
print(johndoemail)
Output
hill
johndoe@gmail.com
Python

Rule 3: Names cannot contain spaces; use _ instead.

Python
Python
Python
# avoid using special symbol @ in variable.
john_doe_at_age=20
# use _ instead of blank spaces.
john_doe_age=20

print(john_doe_at_age)
print(john_doe_age)
Output
20
20
Python

Rule 4: Variable names must not contain Python’s keywords.

Python
Python
Python
# Don't use a keyword for a variable.
if=5
Output
  File "<ipython-input-9-5719a260f2d6>", line 2
    if=5
      ^
SyntaxError: invalid syntax
Python

3. Multiple assignments

  • Python allows the assignment of multiple variables at the same time.
Python
Python
Python
# Assign multiple variables the same value at once.
d=e=f=110
print(d)
print(e)
print(f)
Output
110
110
110
Python

4. Type Casting

  • Python allows typecasting.
  • Typecasting is a way to change the datatype of a variable.
Python
Python
Python
pi=3.14 # Store value of pie in pi
print(pi)
Output

3.14
Python
Python
Python
Python
# print type of pi
type(pi)
Output

float
Python

Let’s change pi’s datatype to an integer with int().

Python
Python
Python
# type cast pi into integer
int(pi)
Output
3
Python

Let’s convert a number stored in string format to an integer with int().

Python
Python
Python
# store string in alphabets
alphabets='6798'
print(alphabets)
print(type(alphabets))


# typecast alphabets into integer.
int(alphabets)
Output
6798
<class 'str'>
6798
Python

5. Python variable types

  • Local
  • Global

Local Variable

Let’s explain the local variable with a simple function.

Python
Python
Python
# element1 is global variable.
# element2 is local variables in the chemist function.
element1 = "methane"
def chemist():
  element2 = "ethane"
  element2 = element2 + element1
  
  
  print(element2)


chemist()
Output
ethanemethane
Python

As you see above, the variable element1 is declared above the scope of chemist(), so it is available to all child
scopes in it.

Element2 is declared in the chemist() function, so it is exclusive to the chemist() and its child scopes only.

Python
Python
Python
print(element1)
Output
methane
Python

If you try to access local variables outside their scope, this error will occur, but element 1 is accessed in the function despite being in a different scope. Because it was accessed within its sub-scope. You can access the variables from the parent scopes.

Global variable

There is a way to access the local scope variables outside the scope. If we declare the local variables as global with a global keyword.

Python
Python
Python
# element1 is global variable.
# element2 is local variables in the chemist function.
element1 = "methane"
def chemist():
  global element2
  element2 = "ethane"
  
  element2 = element1 +  element2
  
  
  return element2

chemist()
print(element2)
Output
methaneethane
Python
Python
Python
Python
# accessing element2 has been made global
print(element2)


# access the local variable through chemist() function.
print(chemist())
Output
methaneethane

methaneethane
Python

As you can see above, if you declare a variable with the global keyword, it becomes accessible in all scopes. Be careful with using global; it may create discrepancies in the security of working systems.

6. Delete a variable

You can delete a variable in Python by using the ‘del' keyword.

Syntax: del variable_name

Python
Python
Python
#store value of pie
pie=3.146
print(pie)
Output
3.146
Python
Python
Python
Python
# delete pie 
del pie
%who pie
Output
No variables match your requested type.
Python

In the above code, we used %who pie to find the deleted variable.

How useful was this post?

Click on a star to rate it!

  • ANCOVA: Analysis of Covariance with python

    ANCOVA is an extension of ANOVA (Analysis of Variance) that combines blocks of regression analysis and ANOVA. Which makes it Analysis of Covariance.

  • Learn Python The Fun Way

    What if we learn topics in a desirable way!! What if we learn to write Python codes from gamers data !!

  • Meet the most efficient and intelligent AI assistant : NotebookLM

    Start using NotebookLM today and embark on a smarter, more efficient learning journey!

  • Break the ice

    This can be a super guide for you to start and excel in your data science career.

  • Tourism Trend Prediction

    After tourism was established as a motivator of local economies (country, state), many governments stepped up to the plate.

  • Sentiment Analysis Polarity Detection using pos tag

    Sentiment analysis can determine the polarity of sentiments from given sentences. We can classify them into certain categories.

  • For loop with Dictionary

    Traverse a dictionary with for loop Accessing keys and values in dictionary. Use Dict.values() and Dict.keys() to generate keys and values as iterable. Nested Dictionaries with for loop Access Nested values of Nested Dictionaries How useful was this post? Click on a star to rate it! Submit Rating

  • For Loops with python

    For loop is one of the most useful methods to reuse a code for repetitive execution.

  • Metrics and terminologies of digital analytics

    These all metrics are revolving around visits and hits which we are getting on websites. Single page visits, Bounce, Cart Additions, Bounce Rate, Exit rate,

  • Hypothesis Testing

    Hypothesis testing is a statistical method for determining whether or not a given hypothesis is true. A hypothesis can be any assumption based on data.

  • A/B testing

    A/B tests are randomly controlled experiments. In A/B testing, you get user response on various versions of the product, and users are split within multiple versions of the product to figure out the “winner” of the version.

  • For Loop With Tuples

    This article covers ‘for’ loops and how they are used with tuples. Even if the tuples are immutable, the accessibility of the tuples is similar to that of the list.

  • Multivariate ANOVA (MANOVA) with python

    MANOVA is an update of ANOVA, where we use a minimum of two dependent variables.

  • Two-Way ANOVA

    You only need to understand two or three concepts if you have read the one-way ANOVA article. We use two factors instead of one in a two-way ANOVA.

Instagram
WhatsApp
error: Content is protected !!