Data types

Numbers

Python supports two types of numbers - Integers and floating point numbers

In [2]: myint = 6
myfloat = 6.0

print
(myint)
print
(myfloat)
Out[2]: 6
6.0

As seen above integers are whole numbers as known by students, there is effectively no limit to how long an integer value can be. While float numbers are decimal numbers as known in maths to student

Type Format Description
int a=10 Signed Integer
long a=345L (L) Long integers, they can also be represented in octal and hexadecimal
float a=45.67 (.) Floating point real values
complex a=3.14J (J) Contains integer in the range 0 to 255.

Strings

A string in Python is a sequence of characters. It is a derived data type. A character is simply a symbol. For example, the English language has 26 characters.

In [2]: str = "This is a string"

print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:1) # Prints string starting from 3rd character
print (str 2) # Prints string two times
print (str + "ADD THIS") # Prints concatenated string
Out[2]: This is a string T is is is a string This is a string This is a string This is a stringADD THIS

Python uses single quotes ' double quotes " and triple quotes """ to denote literal strings. Only the triple quoted strings """ also will automatically continue across the end of line statement.

In [2]: firstName = 'mannie'
last Name = "young"
message = """This shows a string that will span across multiple
lines Using newline characters and no spaces for the next lines.
The end of lines within this string also count as a newline when
printed"""

print (firstName)
print (lastName)
print (message)

Out[2]: mannie
young
This shows a string that will span across multiple lines Using newline characters and no spaces for the next lines.
The end of lines within this string also count as a newline when
printed

Python can use a special syntax to format multiple strings and numbers. We would cover the string formatter here briefly because it is seen often and it is important to recognize the syntax.

In [2]: print ("My name is (). I love to {}".format("Mannie", "code"))

Out[2]: My name is Mannie, I love to code

The {} are placeholders that are substituted by Mannie and code in the final string. This compact syntax is meant to keep the code more readable and compact. Python is currently transitioning to the format syntax above.

Deleting a string entirely is possible using the keyword del. So if we want to delete lastname we simply do del lastname

List

Lists are a very useful variable type in Python. A list can contain a series of values. List variables are declared by using brackets [ ] following the variable name. Yes Lists are exactly what you think they are: objects which are lists of other objects.

In [2]: home = []    # This is a blank list variable
names = ["Smith", "Ruth", "Rio") # list creates a list names.
marks = [90, 88, 87] # lists can have different data types.

So as seen above, we have created lists for home which is an empty list, names and marks! What can we do with it?

In [2]: print (len(names))
print (names[1])
print (marks[0:2])

Out[2]: 3
Ruth
[90, 88]

Above we used the len() function to can give us a number of objects in the list names. We also returned the value at index 1 of names, which is 'Ruth'. Note that The list index starts at zero. You can add items to a list, we use the append function. A function is a chunk of code that tells Python to do something. In this case, append adds an item to the end of a list.

In [2]: home = []    # This is a blank list variable
names = ["Smith", "Ruth", "Rio"] # list creates a list names.
marks = [90, 88, 87] # lists can have different data types.

We would try to add a new name Anthony to our list names.

In [2]: names.append('Anthony')

Now lets print out our list to see the changes.

In [2]: print(names)

Out[2]: ['Smith', 'Ruth', 'Rio', 'Anthony']

Now we can see that we now have Anthony included in the list names.

We can also remove a name from the list, and to do this we would use the del command (short for delete).

For example, to remove the third item in the names list, Rio, we would do this:

In [2]: del names [2]

Now lets print out our list to see the changes.

In [2]: print(names)

Out[2]: ['Smith', 'Ruth', 'Anthony']

Now we can see that Rio has been deleted from the list names.

Instructor should remind the scholars the positions start at zero, so names[2] actually refers to the third item in the list.

Tuples

Tuples are a group of values like a list and are manipulated in similar ways. But, tuples are fixed in size once they are assigned. 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.

In [2]: home_tuple = ()    # This is a blank tuple variable
names = ("Anthony","Abigail","Michael") #creates tuple of names
marks = (90, 88, 87) # tuples contain that integers.

So as seen above, we have created tuples for home which is an empty list, names and marks!

In [2]: print (len(home_tuple))
print (len(names))
print (names)
print ('3rd mark: ', marks[2])

Out[2]: 0
3
('Anthony', 'Abigail', 'Michael')
3rd mark: 93

Above we used the len() function to can give us a number of objects in the tuple home_tuple, notice the output is 0 since the tuple is empty. We also returned the value at index 2 of marks, which is 93. Note that The list index starts at zero.

Dictionary

In Python a dictionary is a collection of things, like lists and tuples. The difference between dictionaries and lists or tuples is that each item in a dictionary has a key and a corresponding value.

Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item has a key and the corresponding value expressed as a pair, key: value. While values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.

Now lets create a dictionary called student:

In [2]: student = {'Name': 'Ernie', 'Age': 16, 'Class': 'First'}

As seen above have created a dictionary student with the keys Name, Age and Class and also they have the values Ernie, 16 and First respectively.

In [2]: print(student['Name']) # displays name of the student
print (student['class']) # displays class of the student

Out[2]: Ernie
First

As seen above we have printed out the Name and Class from the dictionary. Now lets see how we can update the age from 16 to 18 and also add a new key called Address to the dictionary.

In [2]: student['Age'] = 18 # This updates the value for Age
student['Address'] = 'WestHills' # adds a new Key with the value

We have updated the Age and added the Address to our dictionary, now lets see the output.

In [2]: print(student)
print(student['Age'])
print(student['Address'])

Out[2]: {'Name':'Ernie','Age':18,'Class':'First','Address':'WestHills'}
18
WestHills

As seen above our dictionary now have the updated Age and also the new key Address

Instructor can also inform the scholars that dictionaries can also be deleted using the Key pop() 'Age' method to delete an item in the dictionary.

results matching ""

    No results matching ""