top of page
top

Python 3a - Data Types

noun-calculation-2008032-FFFFFF.png

Data Types in Python

If you are a Computer Science student you need to know about the different data types that are used in programming.

  • ​String – A sequence of alphanumeric characters (e.g. “Hello!” or “Toy Story 4” or “Boeing 747”)

  • Integer – A whole number (e.g. 1470 or 0 or -34)

  • Float (also called Real) – A decimal number (e.g. -32.12 or 3.14)

  • Boolean – A logical operation (True or False)

  • Character – A single alphanumeric character (e.g. “a” or “6” or “?”) [Not used in Python as it would just be a string with a length of 1]

Converting to Another Data Type

Converting a variable from one data type to another is called casting.

Casting Commands

str(variable_name) converts a variable to a string.

int(variable_name) converts a variable to a integer.

float(variable_name) converts a variable to a float (decimal number).

An integer (or float) value may be cast into a string so that it can be used with + as part of a sentence to avoid spaces.

total = 45

print("You owe £" , total , "in total.")

print("You owe £" + str(total) , "in total.")

=

You owe £ 45 in total.

You owe £45 in total.

When dividing an integer the answer is automatically given as a decimal number (float), even if it is .0 (e.g. 10 / 2 would give 5.0).

Casting a float (also known as real) number into an integer using int() will remove the decimal.

total = 100/10

print("The answer is" , total)

print("The answer is" , int(total))

The answer is 10.0

The answer is 10

=

Data Types Task 1 (Time)

Write an input line with int to ask the current hour.

Write another input line with int to ask the current minute.

Write a print line with str() that outputs this as a clock time.

Example solution:

What is the hour? 12

What is the minute? 44

The time is 12:44

Data Types Task 2 (Decimal)

Write an input line with int to ask for any number.

Use float() in a print line to output number as a decimal.

Example solution:

Enter any number: 456

456.0

bottom of page