9 Basic Concepts of Python

9 basic concepts of Python

Python is highly demanding programming language in job market. You can use python in large and small scale projects. As a GIS developer, it will be great addition in you skills, if you get expertise in python programming skills.

1. STRING OPERATIONS

What is sting?

In [2]:

#String is collection of words as givern below.
"Umair Asghar"

Out[2]:

'Umair Asghar'

We can use single quotation marks too.In [3]:

'Umair Asghar'

Out[3]:

'Umair Asghar'

String can be space or digitsIn [4]:

'Umair 1 2 3 4 5 6 9'

Out[4]:

'Umair 1 2 3 4 5 6 9'

String can be special characters.

‘@#$%^&*()_’

How to print the string?In [8]:

print ('How to print the string')
How to print the string

We can bind or assign a string to another variable:In [26]:

name = 'Uamir Asgahr'
print(name)
#or simpel use name to print the statement.
name
Uamir Asgahr

Out[26]:

'Uamir Asgahr'

2. Indexing

It is helpful to think of a string as an ordered sequence. Each element in the sequence can be accessed using an index represented by the array of numbers:

In [10]:

# Print the first element in the string

print(name[0])
U

In [11]:

# we can print index 6

print(name[6])
A

In [14]:

print(name[11])
r

Negative Indexing

We can also use negative indexing with strings:In [15]:

print(name[-1])
r

In [17]:

print(name[-11])
a

Find the length of the string.

In [18]:

len("Umair Asgahr")

Out[18]:

12

3. Slicing

We can obtain multiple characters from a string using slicing, we can obtain the 0 to 4th and 8th to the 12th element:In [19]:

name [0:5]

Out[19]:

'Uamir'

In [20]:

name [6:12]

Out[20]:

'Asgahr'

4. Stride

We can also input a stride value as follows, with the ‘2’ indicating that we are selecting every second variable:

In [23]:

name[::3]

Out[23]:

'UiAa'

In [24]:

name[0:5:2]

Out[24]:

'Umr'

5. Concatenate Strings

We can concatenate or combine strings by using the addition symbols, and the result is a new string that is a combination of both:In [25]:

# Concatenate two strings

statement = name + "is the best"
statement

Out[25]:

'Uamir Asgahris the best'

To replicate values of a string we simply multiply the string by the number of times we would like to replicate it. In this case, the number is three. The result is a new string, and this new string consists of three copies of the original string:In [29]:

6*name

Out[29]:

'Uamir AsgahrUamir AsgahrUamir AsgahrUamir AsgahrUamir AsgahrUamir Asgahr'

You can create a new string by setting it to the original variable. Concatenated with a new string, the result is a new string that changes from Michael Jackson to “Michael Jackson is the best”.In [31]:

changestring = name + ' is the great man.'
changestring

Out[31]:

'Uamir Asgahr is the great man.'

6. Escape Sequences

Back slashes represent the beginning of escape sequences. Escape sequences represent strings that may be difficult to input. For example, back slash “n” represents a new line. The output is given by a new line after the back slash “n” is encountered:In [32]:

#line escape
print ('Umair Asghar is a \n Py developer')
Umair Asghar is a 
 Py developer

In [34]:

# tab escape
print ('Umair Asgahr is not a \t king py developer')
Umair Asgahr is not a 	 king py developer

In [35]:

#include backslash
print ('Umair Asgahr is including \\ in the statement.')
Umair Asgahr is including \ in the statement.

In [37]:

#how to show string as it is. Its raw string use r in start of string.
print (r'Umair Asghar is nothing but a  \ py developer')
Umair Asghar is nothing but a  \ py developer

7. String Operations

There are many string operation methods in Python that can be used to manipulate the data. We are going to use some basic string operations on the data.

Let’s try with the method upper; this method converts lower case characters to upper case characters:In [ ]:

 

In [38]:

# Convert all the characters in string to upper case

a = "Thriller is the sixth studio album"
print("before upper:", a)
b = a.upper()
print("After upper:", b)
before upper: Thriller is the sixth studio album
After upper: THRILLER IS THE SIXTH STUDIO ALBUM

Replace function

In [39]:

a = 'Umair Asghar is a great py developer'
b = a.replace('great','greatest')
b

Out[39]:

'Umair Asghar is a greatest py developer'

In [41]:

#find
name.find('UA')

Out[41]:

-1

In [43]:

# Find the substring in the string.

name.find('Umair')

Out[43]:

-1

In [44]:

# If cannot find the substring in the string

name.find('Jasdfasdasdf')

Out[44]:

-1

8. Lists in Python

Objectives

After completing this lab you will be able to:

Perform list operations in Python, including indexing, list manipulation and copy/clone list.

About the Dataset

Imagine you received album recommendations from your friends and compiled all of the recommandations into a table, with specific information about each album.

The table has one row for each movie and several columns:

  • artist – Name of the artist
  • album – Name of the album
  • released_year – Year the album was released
  • length_min_sec – Length of the album (hours,minutes,seconds)
  • genre – Genre of the album
  • music_recording_sales_millions – Music recording sales (millions in USD) on SONG://DATABASE
  • claimed_sales_millions – Album’s claimed sales (millions in USD) on SONG://DATABASE
  • date_released – Date on which the album was released
  • soundtrack – Indicates if the album is the movie soundtrack (Y) or (N)
  • rating_of_friends – Indicates the rating from your friends from 1 to 10

Imagine you received album recommendations from your friends and compiled all of the recommandations into a table, with specific information about each album.

The table has one row for each movie and several columns:

  • artist – Name of the artist
  • album – Name of the album
  • released_year – Year the album was released
  • length_min_sec – Length of the album (hours,minutes,seconds)
  • genre – Genre of the album
  • music_recording_sales_millions – Music recording sales (millions in USD) on SONG://DATABASE
  • claimed_sales_millions – Album’s claimed sales (millions in USD) on SONG://DATABASE
  • date_released – Date on which the album was released
  • soundtrack – Indicates if the album is the movie soundtrack (Y) or (N)
  • rating_of_friends – Indicates the rating from your friends from 1 to 10

The dataset can be seen below:

<table font-size:xx-small>Artist Album Released Length Genre Music recording sales (millions) Claimed sales (millions) Released Soundtrack Rating (friends) Michael Jackson Thriller 1982 00:42:19 Pop, rock, R&B 46 65 30-Nov-82 10.0 AC/DC Back in Black 1980 00:42:11 Hard rock 26.1 50 25-Jul-80 8.5 Pink Floyd The Dark Side of the Moon 1973 00:42:49 Progressive rock 24.2 45 01-Mar-73 9.5 Whitney Houston The Bodyguard 1992 00:57:44 Soundtrack/R&B, soul, pop 26.1 50 25-Jul-80 Y 7.0 Meat Loaf Bat Out of Hell 1977 00:46:33 Hard rock, progressive rock 20.6 43 21-Oct-77 7.0 Eagles Their Greatest Hits (1971-1975) 1976 00:43:08 Rock, soft rock, folk rock 32.2 42 17-Feb-76 9.5 Bee Gees Saturday Night Fever 1977 1:15:54 Disco 20.6 40 15-Nov-77 Y 9.0 Fleetwood Mac Rumours 1977 00:40:01 Soft rock 27.9 40 04-Feb-77 9.5 </table></font>

Lists

Indexing

We are going to take a look at lists in Python. A list is a sequenced collection of different objects such as integers, strings, and other lists as well. The address of each element within a list is called an index. An index is used to access and refer to items within a list.In [8]:

#create list
mylist = ['umair asghar','23','56.8']
mylist

Out[8]:

['umair asghar', '23', '56.8']

In [14]:

# Print the elements on each index

print('the same element using negative and positive indexing:\n Postive:',mylist[0],
'\n Negative:' , mylist[-3]  )
print('the same element using negative and positive indexing:\n Postive:',mylist[1],
'\n Negative:' , mylist[-2]  )
print('the same element using negative and positive indexing:\n Postive:',mylist[2],
'\n Negative:' , mylist[-1]  )
the same element using negative and positive indexing:
 Postive: umair asghar 
 Negative: umair asghar
the same element using negative and positive indexing:
 Postive: 23 
 Negative: 23
the same element using negative and positive indexing:
 Postive: 56.8 
 Negative: 56.8

List Content

Lists can contain strings, floats, and integers. As a result, we can nest other lists, and we can also nest tuples and other data structures. The same indexing conventions apply for nesting:In [21]:

# Sample List

newL = ["Umair Asghar", 26.1, 1985, [1, 2], ("N", 1)]
newL

Out[21]:

['Umair Asghar', 26.1, 1985, [1, 2], ('N', 1)]

9. List Operations

We can also perform slicing in lists. For example, if we want the last two elements, we use the following command:In [24]:

newL[3:5]

Out[24]:

[[1, 2], ('N', 1)]

method extend

In [33]:

# Use extend to add elements to list

List = ["Sting is here",45,2532.2]
List.extend(['newstring',235146])
List

Out[33]:

['Sting is here', 45, 2532.2, 'newstring', 235146]

Another similar method is append. If we apply append instead of extend, we add one element to the list:

In [34]:

List = ["Sting is here",45,2532.2]
List.append(['newstring',235146])
List

Out[34]:

['Sting is here', 45, 2532.2, ['newstring', 235146]]

Each time we apply a method, the list changes. If we apply extend we add two new elements to the list. Therefore, The List is then modified by adding two new elements

In [36]:

# Use extend to add elements to list

List = ["Sting is here",45,2532.2]
List.extend(['newstring',235146])
List

Out[36]:

['Sting is here', 45, 2532.2, 'newstring', 235146]

If we append the list [‘a’,’b’] we have one new element consisting of a nested list:

In [37]:

# Use append to add elements to list

List.append(['a','b'])
List

Out[37]:

['Sting is here', 45, 2532.2, 'newstring', 235146, ['a', 'b']]

As lists are mutable, we can change them. So, we can change the first element as follows:

In [38]:

# Change the element based on the index

A = ["disco", 10, 1.2]
print('Before change:', A)
A[0] = 'hard rock'
print('After change:', A)
Before change: ['disco', 10, 1.2]
After change: ['hard rock', 10, 1.2]

del command

In [39]:

# Delete the element based on the index

print('Before change:', A)
del(A[0])
print('After change:', A)
Before change: ['hard rock', 10, 1.2]
After change: [10, 1.2]

split

In [40]:

# Split the string, default is by space

'hard rock'.split()

Out[40]:

['hard', 'rock']
We can use the split function to separate strings on a specific character. We pass the character we would like to split on into the argument, which in this case is a comma. The result is a list, and each element corresponds to a set of characters that have been separated by a comma:

In [42]:

# Split the string by comma

'A,B,C,D'.split(',')

Out[42]:

['A', 'B', 'C', 'D']

Copy and Clone List

In [43]:

# Copy (copy by reference) the list A

A = ["hard rock", 10, 1.2]
B = A
print('A:', A)
print('B:', B)
A: ['hard rock', 10, 1.2]
B: ['hard rock', 10, 1.2]

In [44]:

<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/ListsVal.gif" width="1000" />
  File "<ipython-input-44-70c12ba31b0d>", line 1
    <img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%202/images/ListsVal.gif" width="1000" />
    ^
SyntaxError: invalid syntax

In [45]:

print('B[0]:', B[0])
A[0] = "hard rock"
print('B[0]:', B[0])
B[0]: hard rock
B[0]: hard rock

Leave a Comment