Types of Things in Python

From OpenCircuits
Jump to navigation Jump to search

What are Types

Almost from the beginning in programming you should have seen two different things in Python: text ( ex: "Hello World" ) and numbers ( ex: 4 ). You may or may not have seen that these 2 types of things cannot be added together. That makes sense, they are sort of apples and oranges. Numbers are actually more complicated because 4 and 4., for example, are not not quiet of the same type one is an integer one is a float. They can be added because that too makes sense, the answer will be 8. also a float. The types of things is an important Python Topics, and an important concepts in every programming language (see Overview of Programming).

So how do you tell what type something is? There is a function called type( xyz ) which will tell you what type of thing xyz is. Some examples.

what_type_1     = 4
what_type_2     = 4.
what_type_3     = 4 + 0j

print  "what_type_1", type( what_type_1 )
print  "what_type_2", type( what_type_2 )
print  "what_type_3", type( what_type_3 )

Types and Classes

Another lens to look at types is that of classes for types really are classes. What do I mean? In Python you can create new types which are called classes. A class is a software object which can be created and assigned to a variable. I will not go into the reasons why this is so great for programming ( it is part of Object Oriented Programming, you can gooogle it ) but will briefly show you how. It is a bit like defining a function. Note that you can more or less skim this code, there will be lots more on classes later.

Convert Object to String!

Almost any object can be converted to a string. This is done with the str() function. This can let you log information to a file, or print the object. Sometimes the string is useful ( it usually is for lists ) and sometimes not so much. Nice to know however.

Examples:

Printing Objects

Pretty much any object can be printed. This may or may not be useful. Python first changes it to a string and then prints the string, see above.