Week 2 Python Fundamental
Week 2: Python Fundamental Part 1
In [ ]:
Copied!
x = 'summer'
print(x)
x = 'summer'
print(x)
In [ ]:
Copied!
a = 3
type(3)
a = 3
type(3)
2.2. float¶
In [ ]:
Copied!
c = 6.3
type(c)
c = 6.3
type(c)
2.3 Python Arithmetic Operators¶
The common mathematical operations can be completed by aritemetic operatos in Python
In [ ]:
Copied!
3 + 5
3 + 5
In [ ]:
Copied!
8/4
8/4
3. Strings¶
Strings in python are surrounded by either double quotation marks, or single quotation marks
In [ ]:
Copied!
print("Hello")
print('Hello')
print("Hello")
print('Hello')
In [ ]:
Copied!
strs_ex = "It's an apple"
print(type(strs_ex))
print(len(strs_ex))
strs_ex = "It's an apple"
print(type(strs_ex))
print(len(strs_ex))
A number with quotation or without quotation is different
In [ ]:
Copied!
num = 3
str_3 = '3'
print(type(num))
print(type(str_3))
num = 3
str_3 = '3'
print(type(num))
print(type(str_3))
3.1 Slicing strings¶
In [ ]:
Copied!
# Slicing: Return a range of characters by using the slice syntax
x = "Clark is pretty good"
print(len(x))
print(x[1:3])
# Slicing: Return a range of characters by using the slice syntax
x = "Clark is pretty good"
print(len(x))
print(x[1:3])
In [ ]:
Copied!
# Slice from the start
b = "Hello, Python!"
print(b[:5])
# Slice to the end
print(b[2:])
# Negative indexing
print(b[-5:-2])
# Slice from the start
b = "Hello, Python!"
print(b[:5])
# Slice to the end
print(b[2:])
# Negative indexing
print(b[-5:-2])
Exercise 1: Get the characters from string
1. Get the character that index is 0 in x = "Clark is pretty good"3.2 String Concatenation¶
In [ ]:
Copied!
a = "Level"
b = "Up"
c = a + b
print(c)
d = a + ' ' + b
print(d)
a = "Level"
b = "Up"
c = a + b
print(c)
d = a + ' ' + b
print(d)
3.3 Combine of string and number¶
In [ ]:
Copied!
age = 36
txt = "My name is John, I am " + age
print(txt)
age = 36
txt = "My name is John, I am " + age
print(txt)
Exercise 2: Type conversion
- We have used built-in function like
print()
andtype()
to do task, this time we usestr()
to convert a value to string - Use
str()
function to remove the error
In [ ]:
Copied!
# F-Strings
age = 5
txt = f"I have lived here for {age} years"
print(txt)
# F-Strings
age = 5
txt = f"I have lived here for {age} years"
print(txt)
3.4 Methods for String¶
A method is a special type of function, it allow you to do different things with different objects.
We can use methods through dot notation: variable.method()
In [ ]:
Copied!
names = "Clark"
u_names = names.upper()
print(u_names)
names = "Clark"
u_names = names.upper()
print(u_names)
Exercise 3: Try methods for String
- get lowercase of string names = "Clark' use
lower()
💡 Tip: Guidelines for Variables¶
- Python is case-sensitive (
apple
andApple
are two separate variables). - Use meaningful variable names (e.g.
university
is clearer thana_string
). Ideally, you code and variable names should be meaningful. - Avoid using variable names that conflict with existing python functions or keywords (e.g.,
print
,type
).
4. Boolean¶
- The expression in Python is True and False
In [ ]:
Copied!
print(5 > 3)
print(5 > 3)
- Most Values are True
In [ ]:
Copied!
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
- Empty values are False
In [ ]:
Copied!
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
5. List¶
In [ ]:
Copied!
myclass = ['python', 'statistics', 'mapping', 'mapping']
print(myclass)
print(len(myclass))
myclass = ['python', 'statistics', 'mapping', 'mapping']
print(myclass)
print(len(myclass))
In [18]:
Copied!
mynote = ["python", 10, True, 'mapping', 23]
mynote = ["python", 10, True, 'mapping', 23]
5.1 Change list items¶
In [19]:
Copied!
grocery_shops = ["Whole Foods", "Trader Joe's", "Stop & stop", "Kroger"]
grocery_shops[1] = "Wegmans"
grocery_shops = ["Whole Foods", "Trader Joe's", "Stop & stop", "Kroger"]
grocery_shops[1] = "Wegmans"
In [ ]:
Copied!
#### 5.2 Sort the list
fruits = ['apple', 'orange', 'blueberries', 'Mangoes']
fruits.sort(reverse=False)
print(fruits)
#### 5.2 Sort the list
fruits = ['apple', 'orange', 'blueberries', 'Mangoes']
fruits.sort(reverse=False)
print(fruits)
- If you want to sort the list ignoring case sensitivity, you can use the key=str.lower argument:
Exercise 4: Try method for list
- Append kroger to list grocery_shops = ["Whole Foods", "Trader Joe's"] use
append()
6 Dictionaries¶
- Dictionaries store data value in key:value pairs
- Access value using the key
- Dictionaries cannot have two items with the same key:
In [ ]:
Copied!
university = {
"name": "clark",
"location": 'MA',
"location": "worcester",
"year": 1887,
'major': ['GIS', 'sociology', 'computer science']
}
print(university['name'])
print(university['major'])
print(university)
university = {
"name": "clark",
"location": 'MA',
"location": "worcester",
"year": 1887,
'major': ['GIS', 'sociology', 'computer science']
}
print(university['name'])
print(university['major'])
print(university)
Exercise 5: Key in Dictionary
🤔 Try what will happen if we have two items with the same key?6.1 Adding items¶
In [ ]:
Copied!
university['room'] = 'BP310'
print(university)
university['room'] = 'BP310'
print(university)
6.2 Methods for dictionaries¶
In [ ]:
Copied!
university = {
"name": "clark",
"location": "worcester",
"year": 1887
}
university = {
"name": "clark",
"location": "worcester",
"year": 1887
}
In [ ]:
Copied!
### Get keys
key_un = university.keys()
key_un
### Get keys
key_un = university.keys()
key_un
In [1]:
Copied!
### Dictionaries in Dictionaries
university = {
"name": "clark",
"location": "worcester",
"year": 1887,
"description": {'student':3827, 'intro':'''Founded in 1887, Clark offers undergraduate and graduate
programs with a focus on interdisciplinary studies,
research opportunities, and community engagement'''}}
### Dictionaries in Dictionaries
university = {
"name": "clark",
"location": "worcester",
"year": 1887,
"description": {'student':3827, 'intro':'''Founded in 1887, Clark offers undergraduate and graduate
programs with a focus on interdisciplinary studies,
research opportunities, and community engagement'''}}
In [ ]:
Copied!
print(university['description']['intro'])
print(university['description']['intro'])
Exercise 5: Try methods for Dictionaries
- Use
values()
,items()
to get value and item from university