Sunday, June 9, 2019

More About Variables

Python is a strongly typed dynamic programming language. This means that when you create a variable in python it is assigned a type and can be used as that type. Because python is extremely flexible it has the ability, without any extra syntax, to change one type to another type.

Because typing is dynamic in python it does not check if the type is correct until the program runs. So if you for instance try to check the absolute value, which is a numeric operation, you will get a syntax error when the program runs but the program will run up until that point. This is a little bit of a double edge sword because on one hand your program has the flexibility to handle this situation and even have dynamic code that relies on it but on the other hand your program could be more stable if this was checked ahead of time.

This is an example of a type error when we try to get the absolute value of "Hello".

>>> abs("Hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
>>> 

Python understands types as classes:

<class 'int'>
<class 'float'>
<class 'bool'>
<class 'str'>

The simplest way to declare or create one of these variables is to use the correct literal syntax when assigning a variable. In the below example I create one of each type.

1
2
3
4
a = 1
b = 1.0
c = True
d = "Hello"

Python allows you to check the type ( class name) of these variables by using the type function. We consider this method built-in and available to use. You can create user-defined functions in python as well but it is not necessary to learn that at this point.

In the below example I can print out each of the above type names for each variable:

1
2
3
4
5
6
7
8
9
a = 1
b = 1.0
c = True
d = "Hello"

type(a)
type(b)
type(c)
type(d)

The output of the above example will be:

1
2
3
4
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'str'>

If you just want the name of the type you can use type(variable).__name__. This will just print out the name and not the extra syntax that you see above. This is very useful for some programs that need to ensure they are really getting an integer and not a string for instance.

Use the below example to get the variable types.

1
2
type(3.14).__name__
type("Hello").__name__
Notice I just pass values, called literals, into the function instead of first assigning them to a variable.

The above program will output:
'int'
'str'

You can learn more about built-in types on the below link:
https://docs.python.org/3.7/library/stdtypes.html

No comments:

Post a Comment

nonlocal keyword

The nonlocal keyword is used to allow an inner function to access variables defined in an outer function. Without using the nonlocal keywo...