SlideShare a Scribd company logo
1 of 68
Python Object and
Data Structure Basics
Basic Data Types
Datatypes
Name Type Description
Integers int Whole numbers, such as: 3 300 200
Floating point float Numbers with a decimal point: 2.3 4.6 100.0
Strings str Ordered sequence of characters: "hello" 'Sammy' "2000" "楽しい"
Lists list Ordered sequence of objects: [10,"hello",200.3]
Dictionaries dict Unordered Key:Value pairs: {"mykey" : "value" , "name" : "Frankie"}
Tuples tup Ordered immutable sequence of objects: (10,"hello",200.3)
Sets set Unordered collection of unique objects: {"a","b"}
Booleans bool Logical value indicating True or False
Numbers
Datatypes
● There are two main number types we will work
with:
○ Integers which are whole numbers.
○ Floating Point numbers which are numbers
with a decimal.
Python Arithmetic Operators
 Operator Description Example Evaluates To
 + Addition 7 + 3 10
 - Subtraction 7 - 3 4
 * Multiplication 7 * 3 21
 / Division (True) 7 / 3 2.3333333333333335
 // Division (Integer) 7 // 3 2
 % Modulus 7 % 3 1
Variable Assignments
Variables
● We use the = to assign values to a variable
● For example:
○ my_dogs = 2
Variables
● Rules for variable names
○ Names can not start with a number.
○ There can be no spaces in the name, use _
instead.
○ Can't use any of these symbols
:'",<>/?|()!@#$%^&*~-+
Variables
● Rules for variable names
○ It's considered best practice that names are
lowercase.
○ Avoid using words that have special meaning
in Python like "list" and "str"
Variables
● Python uses Dynamic Typing
● This means you can reassign variables to
different data types.
● This makes Python very flexible in assigning data
types, this is different than other languages that
are “Statically-Typed”
Variables
my_dogs = 2
my_dogs = [ “Sammy” , “Frankie” ]
Variables
my_dogs = 2
my_dogs = [ “Sammy” , “Frankie” ]
Variables
int my_dog = 1;
my_dog = “Sammy” ; //RESULTS IN ERROR
Variables
● Pros of Dynamic Typing:
○ Very easy to work with
○ Faster development time
● Cons of Dynamic Typing:
○ May result in bugs for unexpected data types!
○ You need to be aware of type()
Strings
STRINGS
● Strings are sequences of characters, using the
syntax of either single quotes or double quotes:
○ 'hello'
○ "Hello"
○ " I don't do that "
String Indexing
● Because strings are ordered sequences it
means we can using indexing and slicing to
grab sub-sections of the string.
● Indexing notation uses [ ] notation after the string
(or variable assigned the string).
● Indexing allows you to grab a single character
from the string...
String Indexing
● These actions use [ ] square brackets and a
number index to indicate positions of what you
wish to grab.
Character : h e l l o
Index : 0 1 2 3 4
STRINGS
● These actions use [ ] square brackets and a
number index to indicate positions of what you
wish to grab.
Character : h e l l o
Index : 0 1 2 3 4
Reverse Index: 0 -4 -3 -2 -1
Python print() Function
 The print() function prints the specified message to the screen, or other standard output device.
 Ex:
 print("Hello World")
 print (5 + 7)
Practice
 Which of the following are legitimate Python identifiers?
a) martinBradley b) C3P_OH c) Amy3 d) 3Right e) Print
 What is the output from the following fragment of Python code?
myVariable = 65
myVariable = 65.0
myVariable = “Sixty Five”
print(myVariable)
 how do you reference the last item in the list?
roster = ["Martin", "Susan", "Chaika", "Ted"]
String Slicing
● Slicing allows you to grab a subsection of multiple
characters, a “slice” of the string.
● This has the following syntax:
○ [start:stop:step]
● start is a numerical index for the slice start
● stop is the index you will go up to (but not include)
● step is the size of the “jump” you take.
String Slicing
mystring = "Hello World"
print(mystring[0])
print(mystring[3])
print(mystring[3:])
print(mystring[:3])
print(mystring[3:5])
print(mystring[::])
print(mystring[::2])
print(mystring[::4])
print(mystring[2:5:2])
print(mystring[::-1])
Output:
H
L
lo World
Hel
Lo
Hello World
HloWrd
Hor
Lo
dlroW olleH
String Properties
and Methods
Concatenation
 We can perform string concatenation Using + operator:
s1 = 'Apple'
s2 = 'Pie'
s3 = 'Sauce'
s4 = s1 + s2 + s3
print(s4)
Concatenation
 concatenation Using * operator:
letter = 'z'
print( letter * 10)
Output:
zzzzzzzzzz
Concatenation
Dynamic datatyping in concatenation:
print ( 2 + 3)
5
print (‘2’ + ‘3’)
23
String Methods
The upper() method returns a string where all characters are in upper case.
mystring = 'hello world'
print( mystring.upper())
HELLO WORLD
String Methods
The lower() method returns a string where all characters are lower case.
mystring = ‘HELLO WORLD'
print( mystring.lower())
hello world
String Methods
The split() method splits a string into a list.
mystring = ‘HELLO WORLD'
print( mystring.split())
[‘HELLO’, ‘WORLD’]
String Methods
Split on a specific character:
mystring = 'hello world'
print( mystring.split('o’))
['hell', ' w', 'rld']
String Formatting for Printing
● Often you will want to “inject” a variable into your
string for printing. For example:
○ my_name = “Jose”
○ print(“Hello ” + my_name)
● There are multiple ways to format strings for
printing variables in them.
● This is known as string interpolation.
String Formatting for Printing
● two methods for this:
○ .format() method ( classic)
○ f-strings (formatted string literals-new in
python 3)
String Formatting for Printing: .format()
The format() method formats the specified value(s) and insert
them inside the string's placeholder.)
{ }
String Formatting for Printing: .format()
Example:
name = 'Robert'
age = 51
print ("My name is {}, I'm {}".format(name, age))
Output: My name is Robert, I'm 51
String Formatting for Printing: .format()
Index on .format():
print ("Music scale is: {} {} {} ".format('Re', 'Do', 'Mi’))
Output: Music scale is: Re Do Mi
print ("Music scale is: {1} {0} {2} ".format('Re', 'Do', 'Mi’))
Output: Music scale is: Do Re Mi
Precision format in numbers
{value:width:precision f}
value= 20/300
print("the value is : {}".format(value))
value= 20/300
print("the value is : {x:1.3f}".format(x=value))
String Formatting for Printing: f-strings
name = 'Robert'
print ("My name is {}".format(name))
Output: My name is Robert
name = 'Robert'
print (f'My name is {name}’)
Output: My name is Robert
Precision format in numbers: f-strings
val = 12.3
print(f'{val:.2f}')
print(f'{val:.5f}’)
Output:
12.30
12.30000
LISTS
● Lists are ordered sequences that can hold a
variety of object types.
● They use [] brackets and commas to separate
objects in the list.
○ [1,2,3,4,5]
● Lists support indexing and slicing. Lists can be
nested and also have a variety of useful methods
that can be called off of them.
Lists
thislist = ["apple", "banana", "cherry"]
print(thislist)
Output: ['apple', 'banana', 'cherry’]
numbers = [1, 2, 5]
print(numbers)
Output: [1, 2, 5]
Lists
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output: 3
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Output: banana
Lists: .append method
The append() method adds an item at the end of the list.
numbers = [21, 34, 54, 12]
numbers.append(32)
Print(numbers)
Output: [21, 34, 54, 12, 32]
Lists: .sort method
The sort() method sorts the list ascending by default.
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)
Output: ['BMW', 'Ford', 'Volvo']
Lists: .reverse method
numbers = [2, 3, 5, 7]
numbers.reverse()
print(numbers)
Output: [7, 5, 3, 2]
Dictionaries
Dictionaries
● Dictionaries are unordered mappings for storing
objects. Previously we saw how lists store objects
in an ordered sequence, dictionaries use a key-
value pairing instead.
● This key-value pair allows users to quickly grab
objects without needing to know an index location.
Dictionaries
● Dictionaries use curly braces and colons to signify
the keys and their associated values.
{'key1':'value1','key2':'value2'}
● So when to choose a list and when to choose a
dictionary?
Dictionaries
thisdict = { "brand": "Ford",
"model": "Mustang",
"year": 1964}
print(thisdict)
Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Output: Ford
Dictionaries: Changing values
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["brand" ]="Cadillac"
print(thisdict["brand"]
Output: Cadillac
.keys & .values methods
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict.keys())
print(thisdict.values()
Output:
dict_keys(['brand', 'model', 'year'])
dict_values(['Ford', 'Mustang', 1964])
Dictionaries
● Dictionaries: Objects retrieved by key name.
Unordered and can not be sorted.
● Lists: Objects retrieved by location.
Ordered Sequence can be indexed or sliced.
Tuples
Tuples
Tuples are very similar to lists. However they have
one key difference - immutability.
Once an element is inside a tuple, it can not be
reassigned.
Tuples use parenthesis: (1,2,3)
Sets
Sets
Sets are unordered collections of unique elements.
Meaning there can only be one representative of the
same object.
Sets: .add method
thisset = {"apple", "banana", "cherry"}
print(thisset)
Output: {'banana', 'apple', 'cherry’}
thisset = {1,2,2,4}
print(thisset)
Sets
thisset = {"apple", "banana", "cherry"}
thisset.add(strawberry)
print(thisset)
Output: {'strawberry', 'banana', 'cherry', 'apple'}
Booleans
Boleans
Booleans are operators that allow you to convey
True or False statements.
Boooleans
print (1 > 2)
Output:
False
I/0: Input function
I/0: Input function
The input() function allows user input.
print('Enter your name:')
x = input()
print('Hello, ' + x)
I/0: Input function
x = input('Enter your name:')
print('Hello, ' + x)
Practice
1) Create a programs that asks for user input about base and height and calculates area of a square.
2) Do the same but to calculate volume of a cube.
3) Do the same but calculate area of a triangle.
Solutions
base = int(input('Enter base:’))
height =int(input('Enter height:’))
area = base * height
print(area)

More Related Content

Similar to 1-Object and Data Structures.pptx

Similar to 1-Object and Data Structures.pptx (20)

Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Data type2 c
Data type2 cData type2 c
Data type2 c
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)
 
UNIT 4 python.pptx
UNIT 4 python.pptxUNIT 4 python.pptx
UNIT 4 python.pptx
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
Python strings
Python stringsPython strings
Python strings
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
14 strings
14 strings14 strings
14 strings
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
 
Chapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdfChapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdf
 
Data type in c
Data type in cData type in c
Data type in c
 
Python crush course
Python crush coursePython crush course
Python crush course
 
Mysql Performance Optimization Indexing Algorithms and Data Structures
Mysql Performance Optimization Indexing Algorithms and Data StructuresMysql Performance Optimization Indexing Algorithms and Data Structures
Mysql Performance Optimization Indexing Algorithms and Data Structures
 
Unit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptx
 
Python
PythonPython
Python
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Arrays
ArraysArrays
Arrays
 
The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180
 
The Ring programming language version 1.6 book - Part 25 of 189
The Ring programming language version 1.6 book - Part 25 of 189The Ring programming language version 1.6 book - Part 25 of 189
The Ring programming language version 1.6 book - Part 25 of 189
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 

1-Object and Data Structures.pptx

  • 1. Python Object and Data Structure Basics
  • 3. Datatypes Name Type Description Integers int Whole numbers, such as: 3 300 200 Floating point float Numbers with a decimal point: 2.3 4.6 100.0 Strings str Ordered sequence of characters: "hello" 'Sammy' "2000" "楽しい" Lists list Ordered sequence of objects: [10,"hello",200.3] Dictionaries dict Unordered Key:Value pairs: {"mykey" : "value" , "name" : "Frankie"} Tuples tup Ordered immutable sequence of objects: (10,"hello",200.3) Sets set Unordered collection of unique objects: {"a","b"} Booleans bool Logical value indicating True or False
  • 5. Datatypes ● There are two main number types we will work with: ○ Integers which are whole numbers. ○ Floating Point numbers which are numbers with a decimal.
  • 6. Python Arithmetic Operators  Operator Description Example Evaluates To  + Addition 7 + 3 10  - Subtraction 7 - 3 4  * Multiplication 7 * 3 21  / Division (True) 7 / 3 2.3333333333333335  // Division (Integer) 7 // 3 2  % Modulus 7 % 3 1
  • 8. Variables ● We use the = to assign values to a variable ● For example: ○ my_dogs = 2
  • 9. Variables ● Rules for variable names ○ Names can not start with a number. ○ There can be no spaces in the name, use _ instead. ○ Can't use any of these symbols :'",<>/?|()!@#$%^&*~-+
  • 10. Variables ● Rules for variable names ○ It's considered best practice that names are lowercase. ○ Avoid using words that have special meaning in Python like "list" and "str"
  • 11. Variables ● Python uses Dynamic Typing ● This means you can reassign variables to different data types. ● This makes Python very flexible in assigning data types, this is different than other languages that are “Statically-Typed”
  • 12. Variables my_dogs = 2 my_dogs = [ “Sammy” , “Frankie” ]
  • 13. Variables my_dogs = 2 my_dogs = [ “Sammy” , “Frankie” ]
  • 14. Variables int my_dog = 1; my_dog = “Sammy” ; //RESULTS IN ERROR
  • 15. Variables ● Pros of Dynamic Typing: ○ Very easy to work with ○ Faster development time ● Cons of Dynamic Typing: ○ May result in bugs for unexpected data types! ○ You need to be aware of type()
  • 17. STRINGS ● Strings are sequences of characters, using the syntax of either single quotes or double quotes: ○ 'hello' ○ "Hello" ○ " I don't do that "
  • 18. String Indexing ● Because strings are ordered sequences it means we can using indexing and slicing to grab sub-sections of the string. ● Indexing notation uses [ ] notation after the string (or variable assigned the string). ● Indexing allows you to grab a single character from the string...
  • 19. String Indexing ● These actions use [ ] square brackets and a number index to indicate positions of what you wish to grab. Character : h e l l o Index : 0 1 2 3 4
  • 20. STRINGS ● These actions use [ ] square brackets and a number index to indicate positions of what you wish to grab. Character : h e l l o Index : 0 1 2 3 4 Reverse Index: 0 -4 -3 -2 -1
  • 21. Python print() Function  The print() function prints the specified message to the screen, or other standard output device.  Ex:  print("Hello World")  print (5 + 7)
  • 22. Practice  Which of the following are legitimate Python identifiers? a) martinBradley b) C3P_OH c) Amy3 d) 3Right e) Print  What is the output from the following fragment of Python code? myVariable = 65 myVariable = 65.0 myVariable = “Sixty Five” print(myVariable)  how do you reference the last item in the list? roster = ["Martin", "Susan", "Chaika", "Ted"]
  • 23. String Slicing ● Slicing allows you to grab a subsection of multiple characters, a “slice” of the string. ● This has the following syntax: ○ [start:stop:step] ● start is a numerical index for the slice start ● stop is the index you will go up to (but not include) ● step is the size of the “jump” you take.
  • 24. String Slicing mystring = "Hello World" print(mystring[0]) print(mystring[3]) print(mystring[3:]) print(mystring[:3]) print(mystring[3:5]) print(mystring[::]) print(mystring[::2]) print(mystring[::4]) print(mystring[2:5:2]) print(mystring[::-1]) Output: H L lo World Hel Lo Hello World HloWrd Hor Lo dlroW olleH
  • 26. Concatenation  We can perform string concatenation Using + operator: s1 = 'Apple' s2 = 'Pie' s3 = 'Sauce' s4 = s1 + s2 + s3 print(s4)
  • 27. Concatenation  concatenation Using * operator: letter = 'z' print( letter * 10) Output: zzzzzzzzzz
  • 28. Concatenation Dynamic datatyping in concatenation: print ( 2 + 3) 5 print (‘2’ + ‘3’) 23
  • 29. String Methods The upper() method returns a string where all characters are in upper case. mystring = 'hello world' print( mystring.upper()) HELLO WORLD
  • 30. String Methods The lower() method returns a string where all characters are lower case. mystring = ‘HELLO WORLD' print( mystring.lower()) hello world
  • 31. String Methods The split() method splits a string into a list. mystring = ‘HELLO WORLD' print( mystring.split()) [‘HELLO’, ‘WORLD’]
  • 32. String Methods Split on a specific character: mystring = 'hello world' print( mystring.split('o’)) ['hell', ' w', 'rld']
  • 33. String Formatting for Printing ● Often you will want to “inject” a variable into your string for printing. For example: ○ my_name = “Jose” ○ print(“Hello ” + my_name) ● There are multiple ways to format strings for printing variables in them. ● This is known as string interpolation.
  • 34. String Formatting for Printing ● two methods for this: ○ .format() method ( classic) ○ f-strings (formatted string literals-new in python 3)
  • 35. String Formatting for Printing: .format() The format() method formats the specified value(s) and insert them inside the string's placeholder.) { }
  • 36. String Formatting for Printing: .format() Example: name = 'Robert' age = 51 print ("My name is {}, I'm {}".format(name, age)) Output: My name is Robert, I'm 51
  • 37. String Formatting for Printing: .format() Index on .format(): print ("Music scale is: {} {} {} ".format('Re', 'Do', 'Mi’)) Output: Music scale is: Re Do Mi print ("Music scale is: {1} {0} {2} ".format('Re', 'Do', 'Mi’)) Output: Music scale is: Do Re Mi
  • 38. Precision format in numbers {value:width:precision f} value= 20/300 print("the value is : {}".format(value)) value= 20/300 print("the value is : {x:1.3f}".format(x=value))
  • 39. String Formatting for Printing: f-strings name = 'Robert' print ("My name is {}".format(name)) Output: My name is Robert name = 'Robert' print (f'My name is {name}’) Output: My name is Robert
  • 40. Precision format in numbers: f-strings val = 12.3 print(f'{val:.2f}') print(f'{val:.5f}’) Output: 12.30 12.30000
  • 41. LISTS ● Lists are ordered sequences that can hold a variety of object types. ● They use [] brackets and commas to separate objects in the list. ○ [1,2,3,4,5] ● Lists support indexing and slicing. Lists can be nested and also have a variety of useful methods that can be called off of them.
  • 42. Lists thislist = ["apple", "banana", "cherry"] print(thislist) Output: ['apple', 'banana', 'cherry’] numbers = [1, 2, 5] print(numbers) Output: [1, 2, 5]
  • 43. Lists thislist = ["apple", "banana", "cherry"] print(len(thislist)) Output: 3 thislist = ["apple", "banana", "cherry"] print(thislist[1]) Output: banana
  • 44. Lists: .append method The append() method adds an item at the end of the list. numbers = [21, 34, 54, 12] numbers.append(32) Print(numbers) Output: [21, 34, 54, 12, 32]
  • 45. Lists: .sort method The sort() method sorts the list ascending by default. cars = ['Ford', 'BMW', 'Volvo'] cars.sort() print(cars) Output: ['BMW', 'Ford', 'Volvo']
  • 46. Lists: .reverse method numbers = [2, 3, 5, 7] numbers.reverse() print(numbers) Output: [7, 5, 3, 2]
  • 48. Dictionaries ● Dictionaries are unordered mappings for storing objects. Previously we saw how lists store objects in an ordered sequence, dictionaries use a key- value pairing instead. ● This key-value pair allows users to quickly grab objects without needing to know an index location.
  • 49. Dictionaries ● Dictionaries use curly braces and colons to signify the keys and their associated values. {'key1':'value1','key2':'value2'} ● So when to choose a list and when to choose a dictionary?
  • 50. Dictionaries thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964} print(thisdict) Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
  • 51. Dictionaries thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict["brand"]) Output: Ford
  • 52. Dictionaries: Changing values thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["brand" ]="Cadillac" print(thisdict["brand"] Output: Cadillac
  • 53. .keys & .values methods thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict.keys()) print(thisdict.values() Output: dict_keys(['brand', 'model', 'year']) dict_values(['Ford', 'Mustang', 1964])
  • 54. Dictionaries ● Dictionaries: Objects retrieved by key name. Unordered and can not be sorted. ● Lists: Objects retrieved by location. Ordered Sequence can be indexed or sliced.
  • 56. Tuples Tuples are very similar to lists. However they have one key difference - immutability. Once an element is inside a tuple, it can not be reassigned. Tuples use parenthesis: (1,2,3)
  • 57. Sets
  • 58. Sets Sets are unordered collections of unique elements. Meaning there can only be one representative of the same object.
  • 59. Sets: .add method thisset = {"apple", "banana", "cherry"} print(thisset) Output: {'banana', 'apple', 'cherry’} thisset = {1,2,2,4} print(thisset)
  • 60. Sets thisset = {"apple", "banana", "cherry"} thisset.add(strawberry) print(thisset) Output: {'strawberry', 'banana', 'cherry', 'apple'}
  • 62. Boleans Booleans are operators that allow you to convey True or False statements.
  • 63. Boooleans print (1 > 2) Output: False
  • 65. I/0: Input function The input() function allows user input. print('Enter your name:') x = input() print('Hello, ' + x)
  • 66. I/0: Input function x = input('Enter your name:') print('Hello, ' + x)
  • 67. Practice 1) Create a programs that asks for user input about base and height and calculates area of a square. 2) Do the same but to calculate volume of a cube. 3) Do the same but calculate area of a triangle.
  • 68. Solutions base = int(input('Enter base:’)) height =int(input('Enter height:’)) area = base * height print(area)