next up previous
Next: Using the correct type Up: A Second Python Program: Previous: Explanation of the program

Python variable types

Variables are used to store and refer to data. The previous example has two "variables" of our own invention, namely, name and age. Python variables are case-sensitive and must always start with a letter or an underscore _, followed by letters, numbers or underscores. Be aware that Python reserves some names for its own use, so, for example, you can't use print or input as your variable name, because they are already names of built-in Python functions.

Variables come with types that help Python know how to manipulate them and calculate with them. When you first introduce a variable in Python, Python guesses its type from context. In the example above the function input returns the string of characters that it finds on the line you type, so name and age are automatically of type string. There are four common, basic variable types in Python

datatype example
string "Go Utes!"
integer 123456789
float 3.1415 or 0.31415e1
complex -0.141 + 0.141j
Strings are just a bunch of characters. A string constant is a bunch of characters surrounded by single or double quotes. For example, in this program "Enter your name" is a string constant.

Integers are whole numbers (no decimal points) and can carry a sign.

The float type stores the number in scientific notation with an exponent and mantissa. (In decimal notation the number $0.31415 \times
10^1$ has "exponent" 1 and "mantissa" 0.31415.) We also use the term "floating point" type. A floating point constant can be written with a decimal point and can include a power of 10 written after the letter e as in the example above.

A complex constant is written with j to indicate the imaginary part, as in the example above.


next up previous
Next: Using the correct type Up: A Second Python Program: Previous: Explanation of the program
Carleton DeTar 2017-08-10