Python Data Types

Now it’s time to walk through basic data types that are provided by the language. We are going to focus on primitive built-in types and set sequence types aside as for now

Boolean

Boolean type is very simple, it can be either True or False

is_valid = True
skip_tests = False

It is commonly used in condition statements or as flags. There are some boolean logic operators to remember: not, and, or. Some examples:

a = True
b = not a
print(b) # prints False
print(a and b) # prints False
print(a or b) # prints True

More details on boolean operators could be found here.

String

Strings are used to hold text, you can use either single or double quotes to declare a string:

a = "new string "
b = 'another string'

There are plenty of cool things, that could be done with them, here let’s highlight some basic:

print(a + b) # prints: "new string another string"
print(a[0]) # prints first element of a: n
print(b[-1]) # prints last element of b: g
print(b[1]) # prints second element of b: n
print(len(b)) # prints length of the string: 14

Int and Float

Integer type is can hold whole numbers, while float can have a floating point. Some basic operations could be applied to them:

a = 10
b = 5
print(a + b) # 15
print(a - b) # 5
print(a * b) # 50
print(a / b) # 2
print(a % b) # 0 - remainder, 4 % 3 = 1
print(5 ** 2) # 25 - 5 power of 2
print(-a) # -10

More interesting is type conversion between int and float:

a = 2.5
b = 10
print(b/a) # 4.0, result is converted to float
print(a*b) # 25.0 - float as well
print(float(b)) # 10.0 - converts to float
c = '10.4' # string
d = float(c) # float, 10.4
print(int(a)) # 2 - int, numbers after point are just dropped
e = '6' # string
f = int(e) # int, 6

Follow-up questions, what is result:

  • not True and True
  • “Welcome”[3]
  • (10 * 5) % 4

One response to “Python Data Types”

  1. […] sequence and not included. By default the first element is 0 (similar to indexes of characters in a string. But you can use another versions of range function, e.g. range(5, 10) – sequence starts from […]

    Like

Leave a reply to Loops in Python – vokarud.blog Cancel reply