Mastery09

Basic types and their use in Python

  • Numbers

Number data types store numeric values. Number objects are created when you assign a value to them. For example:

var1 = 1

var2 = 10

var3 = var1 + var2

print(var3)

Run code -> 11

  • String

Strings in Python are identified as a contiguous set of characters represented in the quotation marks.

str = ‘Hello World!’

print(str)

Run code-> Hello World!

  • List

Lists are the most versatile of Python’s compound data types. A list contains items separated by commas and enclosed within square brackets ([]). The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1.

list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]

print(list)

print(list[0])

Run code:

[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003]

abcd

  • Tuple

A tuple consists of a number of values separated by commas. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )

print(tuple)

print(tuple[0])

Run code:

(‘abcd’, 786, 2.23, ‘john’, 70.200000000000003)

abcd

  • Dictionary

They work like associative arrays or hashes found in Perl and consist of key-value pairs. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).

dict = {}

dict[‘one’] = “This is one”

dict[2] = “This is two”

print dict[‘one’]

print dict[2]

Run code:

This is one

This is two

 

1014 09

CC BY 4.0 Mastery09 by Joel Erles is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.