Skip to main content

Specify a Variable Type

Sometimes you need a variable to have a particular type, and casting is how you get it. Python is object-oriented, so classes define its data types, even the primitive ones.

That means casting comes down to calling constructor functions:

  • int() - makes an integer from an integer literal, from a float literal (dropping everything after the decimal point), or from a string literal, as long as the string holds a whole number
  • float() - makes a float from an integer or float literal, and also from a string literal, as long as the string holds an integer or a float
  • str() - makes a string from many data types, such as float literals, integer literals, and strings

Example

Integers:

Prompt
Write a Python program that uses the int() constructor to create integers from an integer literal, a float literal, and a string literal.
Output: complete Python program

Example

Floats:

Prompt
Write a Python program that uses the float() constructor to create floats from an integer, a float, and string literals.
Output: complete Python program

Example

Strings:

Prompt
Write a Python program that uses the str() constructor to create strings from a string, an integer, and a float.
Output: complete Python program