Python for Artificial Intelligence Beginner 12 minutes

Variables and Data Types

How Python stores values, and the basic types: numbers, strings and Booleans.

Your progress in the track0%

Variables

We create a variable by assigning a value to a name:

age = 21          # int
height = 1.72     # float
name = "Ali"      # str
is_student = True # bool
result = None     # NoneType

The name must start with a letter or an underscore, and descriptive lower-case names with underscores (snake_case) are preferred.

Basic types

TypeExampleUsage
int42Integers
float3.14Floating-point numbers
str"text"Strings
boolTrueBooleans
NoneTypeNoneAbsence of a value

Finding the type and converting

type(3.0)        # <class 'float'>
int("42") + 1    # 43
float("2.5")     # 2.5
str(10) + "%"    # '10%'

Trying to add a string and a number directly, such as "5" + 1 causes the error TypeError, because Python does not convert types implicitly in this case.

Strings

Strings in Python 3 are Unicode, so they support Arabic directly. Useful operations include:

s = "Machine Learning"
len(s)          # 16
s.lower()       # 'machine learning'
s[0:7]          # 'Machine'
f"Text length {len(s)}"   # an f-string to embed values

A note on floating-point numbers

Floating-point numbers are stored with an approximate binary representation, so the result of 0.1 + 0.2 is 0.30000000000000004. When comparing, use math.isclose instead of direct equality.

Lesson terms

Dynamic typing
Determining a variable's type at run time from the value assigned to it, without declaring the type in advance.
Variable
A name that refers to a value stored in memory, and can be rebound to another value.

Abstract

A variable in Python is a name that refers to an object in memory, and its type is determined dynamically from the value. The basic types are int, float, str, bool and NoneType; the type can be found with the type function and converted with functions such as int, float and str.

Review questions

  1. What is the type of the value 3.0?

    float.

  2. What is the result of int("42") + 1?

    43, because the string was converted to an integer before the addition.

Sources and references

  1. Built-in Types — Python documentation
  2. An Informal Introduction to Python

Complete the lesson