Lesson 3: Basic Data Types: string / int / float / bool

Here are some of the basic built-in data types in Python:

  • str - strings
  • int - whole numbers without any decimal point
  • float - numbers with decimal points or in exponential form
  • bool - truth values True or False
  • NoneType - represents the null value - None

In this lesson, we will discuss them one by one. In the next lesson, we will talk about complex data types for storing more than one value.


1. Strings

Strings are defined by using single '' or double "" quotes.

phone = '(123) 456-789'
name = "John Smith"

In general, using single or double quotes is a personal preference, but just stay consistent within your projects.

single_quotes = 'allows embedded "double" quotes'
double_quotes = "allows embedded 'single' quotes"

1.1. Cast to String

The str() method can cast the value to a string. This is important if you concatenate numbers with strings. Python would prevent that with an error, so you need to do this:

code = str(4655) # Result: '4655'

1.2. String Characters: Index and Iteration

Technically, strings are sequences of characters and can be accessed via index or iterated in a loop.

name = "Peter"
 
print(name[0]) # P
print(name[2]) # t
 
for x in name: # We will talk about loops in a later lesson
print(x)

Output:

P
t
P
e
t
e
r

1.3. String Formatting and Concatenation

Strings can be concatenated using the plus + symbol.

Python

name = 'John'
notifications = 1000
 
print('Hi ' + name + '! You have ' + str(notifications) + ' notifications!')

PHP

$name = 'John';
$notifications = 1000;
 
echo 'Hi ' . $name . '! You have ' . $notifications . ' notifications!';

Manually concatenating strings is often not so convenient.

A more convenient option is to use f-strings, also known as string interpolation. Add the literal prefix f before the string and variable names inside within curly braces.

Python

name = 'John'
notifications = 1000
 
print(f'Hi {name}! You have {notifications} notifications!')

PHP

$name = 'John';
$notifications = 1000;
 
echo "Hi {$name}! You have {$notifications} notifications!";

A notable difference is that in PHP, you are forced to use double quotes for this to work. Python doesn't care about that.

You can also use Python expressions between curly braces {}.

import random # we will talk about importing libraries in a later lesson
 
name = 'John'
 
print(f'Hi {name}! You have {random.randint(100, 199)} notifications!')

You can't use expressions like this in PHP.

1.4. String methods

String length

To get the length of a string, you can use the len() method.

Python

print(len('my awesome program')) # Result: 18

PHP

echo strlen('my awesome program'); // 18

Split string

Under the hood, all data types in Python are Objects and have methods to call directly on them. One example can be the split() method to convert a string into a list by delimiter.

Python

'my awesome program'.split(' ')
 
# ['my', 'awesome', 'program']

In PHP, you must use the built-in explode() function and pass a string.

PHP

explode(' ', 'my awesome program');
 
// ['my', 'awesome', 'program']

Join list to string

String also can be used as a delimiter to join list values into a string using the join() method.

Python

' '.join(['my', 'awesome', 'program']) # Result: 'my awesome program'

You must use the implode() function in PHP.

PHP

implode(' ', ['my', 'awesome', 'program']);
 
// my awesome program

Repeating strings

You can repeat strings by using the multiplication symbol *.

print('-=' * 30)
 
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Other manipulations

There are more methods to manipulate strings, and you check them on Official Python Documentation

print('THIS SHOULD BE LOWERCASE'.lower())
 
print('i can\'t hear you'.upper())

2. Integers and Floats

Integers are defined without decimals. If there's a decimal point, it automatically will be float.

a = 5 # int
 
# float
b = 1.
c = .4
d = 3.6

Values can be cast with int() and float() methods.

z = int('4')
e = float('1.33')

Again, let's compare some differences in how Python and PHP treat numbers.

2.1. Precision

In Python, integers have unlimited precision.

a = 54331946743588295621511121046550819699332
 
print(2 ** 1000) # 2 to the power of 1000
 
# 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

With PHP, you won't be able to do that. The 64-bit system integer range is from -9223372036854775808 to 9223372036854775807. Going over this limit would give you float with exponent. Trying to cast it to int would give you technically garbage.

echo PHP_INT_MAX + 1
 
// 9.2233720368548E+18
 
echo (int) (PHP_INT_MAX + 1)
 
// -9223372036854775808
 
echo (int) (2 ** 1000)
 
// 0

When dealing with floats using Python, information about the precision and representation of floating point numbers depends on the machine that your program is running and can be checked in sys.float_info.

import sys
 
print(sys.float_info)
max=1.7976931348623157e+308
max_exp=1024
max_10_exp=308
min=2.2250738585072014e-308
min_exp=-1021
min_10_exp=-307
dig=15
mant_dig=53
epsilon=2.220446049250313e-16
radix=2
rounds=1

2.2. Exponentiation

In Python and PHP, exponentiation is a double asterisk symbol **.

Python:

print(2 ** 3)

PHP:

echo 2 ** 3;

If you come across from another language, this might be new to you, as caret ^ is a bitwise xor operator.

y = x ^ p # bitwise xor
y = x ** p # exponentiation

An alternative method would be to use the math.pow() function.

import math
 
print(math.pow(9, 3))

The math.pow() method is a bit slower but always uses float semantics and ensures the float value is returned.

When dealing with simple functions, like quadratic functions, product x * x is faster than exponentiation x ** 2 performance-wise.

2.3. Division

In Python, the / and // operators are used for division but behave differently.

  • Division (/): performs floating point division:
result = 7 / 3
 
print(result) # Output: 2.3333333333333335
  • Floor Division (//): always returns the largest integer that is less than or equal to the division result.
result = 7 // 3
 
print(result) # Output: 2
  • divmod(): built-in function that returns a tuple with the result of floor division and modulo. It is more efficient than doing calculations manually twice.
print((7 // 3, 7 % 3)) # Output: (2, 1)
 
print(divmod(7, 3)) # Output: (2, 1)

3. Booleans

Booleans represent truth values. The bool type must be True or False. They are case-sensitive, unlike in PHP. So you need to use True and not true.

a = True
 
b = true
# NameError: name 'true' is not defined. Did you mean: 'True'?

The built-in function bool() converts any value to a boolean if that value can be interpreted.

Empty value None, zero numeric types 0, 0.0, empty sequences and collections '', (), [], {}, range(0) will be interpreted as False.


4. Null values

Python doesn't have a null value like you're used to in PHP or other languages. Instead, it has a None constant of NoneType type.


So, these are the main basic types of variables. In the next lesson, we will talk about the complex types of variables for storing more than a single value.


Zhipeng Zou avatar

'my awesome string'.split(' ') should be 'my awesome program'.split(' ')

πŸ‘ 1
Povilas avatar

Fixed! Thank you for the proof-reading :)

Oliver Kurmis avatar

It is worth mentioning that PHP's strlen() function is counting the number of bytes in a string and not the number of characters: echo strlen('空手'); // 6

Python counts the number of characters: print(len('空手')) # 2

πŸ‘ 2
Povilas avatar

Good notice, thanks!