Python Basic – A Basic Guide to Python Type Conversion and Variable

Home /

Table of Contents

Type conversion

Datatype 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 string datatypes. The functions to convert to this type are – int (), float (), str () respectively.

Conversion to Integer

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

   >>> int("3810")
   3810
   >>> int(3.810)
   3

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

   >>> int("38abc10")
   Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   ValueError: invalid literal for int() with base 10: '38abc10'

Conversion to float

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

   >>> float("38.10") #String to float
   38.1
   >>> float(3) #Integer to float
   3.0

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.

   >>> str(3810)
   '3810'
   >>> print("Float = " + str(3.8) + " Integer = " + str(10))
   Float = 3.8 Integer = 10
   >>> print(f"Summation of 3 and 8 = {3+8}")
   Summation of 3 and 8 = 11

Python Variable

Variables are like small boxes made in computer memory in which anything can be stored. When we declare a variable, the computer assigns that variable memory. The memory address of each variable is unique. If the program needs it, the value can be stored in that variable or named memory location. The value of that location can be accessed and utilized using that name when needed.

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

Assignment

   >>> first_variable = 38
   >>> print(first_variable)
   38
   >>> print(first_variable + 10)
   48
   >>> print(first_variable)
   38
   >>> print(first_variable - 10)
   28

In the example above, 38 (an integer number) is first stored in a variable whose name is first_variable. In the next line, that first_variable has been sent as an argument for the print() function. And we already know that when something is sent as an argument to a print function, it gets printed. So, the number first_variable (i.e. 38) is printed on the screen. Similar work has been done in the print(first_variable + 10) line. Here, the statement print(first_variable – 10) is executed, because the value of first_variable is 38 and 10 is added to it and the number 48 is sent as the argument of the print function which is printed on the screen.

We have also been able to print the last print statement with the value of first_variable i.e. 38 with the name of the variable. That is to say, a variable stores its value throughout the whole program.

Re-assignment

   >>> second_variable = 3810
   >>> print(second_variable)
   3810
   >>> second_variable = 183
   >>> print(second_variable)
   183
   >>> second_variable = "EnableGeek"
   >>> print(second_variable)
   EnableGeek

Here an integer is first assigned as the value of second_variable and its value is found by printing in general. But in the next line, another integer is stored in the same variable second_variable and it is also accessed through the next print function and printed on the screen. This is called a value re-assignment. That is, new values ​​can be stored multiple times in a variable, and the last stored value is stored in that variable (the previous value is deleted).

There are no specific data types for variables in Python. So in the same variable, first a number and then a string are stored in it. Note that the first time we assign a value to a variable, that variable is initialized. Later we will be able to work on that variable again with different values or the previous values.

Rules of Naming Variables

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 written in this way:

first variable = 38 
# [ It should be first_variable = 38]

The first letter must be an alphabetic letter (uppercase or lowercase) or underscore ( _ ).

For example, This can be written as a variable

enablegeek
a
b 
_variable 

but this cannot be written in that way.

1geek
@gmail 
3abc
%number 

Letter, underscore, and number can be used later except for the first letter.

Example: 

variable1
first_variable
most_rated_course_python
  • Although an underscore can be used at the beginning of a variable, Python’s convention is to always start the variable’s name with a lowercase letter.
  • Python Case Sensitive means a = 4 and A = 4 are not the same variables.
  • Python has some reserved keywords, that cannot be used. Such as:

Reserved keywords

Reserved words, also known as keywords, are used in Python to provide a specific meaning or functionality to the language. They are used to perform specific operations or to define specific constructs within the language.

For example, the if keyword is used to create an if statement, which allows you to control the flow of your program based on certain conditions. The keyword is used to create a for loop, which allows you to iterate over a sequence of items.

The class keyword is used to define a new class, which is a blueprint for creating objects. The import keyword is used to import modules or packages, allowing you to use the functionality of other code in your own program.

Reserved words are also used to define the structure of the language, such as def to define a function and as to create an alias for a module.

   >>> help("keywords")
 
   Here is a list of the Python keywords. Enter any keyword to get 
   more help.
 
   False               class               from                or
   None                continue            global              pass
   True                def                 if                  raise
   and                 del                 import              return
   as                  elif                in                  try
   assert              else                is                  while
   async               except              lambda              with
   await               finally             nonlocal            yield
   break               for                 not                
 
   >>>

This is the restriction on identifier names. The Python language reserves a small set of keywords that designate special language functionality. No object can have the same name as a reserved word.

   >>> third_variable = 38
   >>> print(third_variable)
   38
   >>> third variable = 38  #No space allowed
   File "<stdin>", line 1
       third variable = 38
           ^
   SyntaxError: invalid syntax
   >>> global = 22  #This is a reserved keyword
   File "<stdin>", line 1
   global = 22
       ^
   SyntaxError: invalid syntax

The use of reserved words helps to make the code more readable and easier to understand, as the intended meaning and functionality of the code are clear from the keywords used. They also help to prevent naming conflicts and make the code more consistent.

In summary, the use of reserved words in Python provides a specific meaning or functionality to the language, makes the code more readable and easy to understand, prevents naming conflicts, and makes the code more consistent.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article