Week 2 Python Fundamental
Week 2: Python Fundamental Part 1
In [35]:
Copied!
x = 'summer'
print(x)
x = 'summer'
print(x)
summer
In [1]:
Copied!
a = 3
type(3)
a = 3
type(3)
Out[1]:
int
2.2. float¶
In [42]:
Copied!
c = 6.3
type(c)
c = 6.3
type(c)
Out[42]:
float
2.3 Python Arithmetic Operators¶
The common mathematical operations can be completed by aritemetic operatos in Python
In [25]:
Copied!
3 + 5
3 + 5
Out[25]:
8
In [26]:
Copied!
8/4
8/4
Out[26]:
2.0
3. Strings¶
Strings in python are surrounded by either double quotation marks, or single quotation marks
In [32]:
Copied!
print("Hello")
print('Hello')
print("Hello")
print('Hello')
Hello Hello
In [28]:
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))
<class 'str'> 13
A number with quotation or without quotation is different
In [7]:
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))
<class 'int'> <class 'str'>
3.1 Slicing strings¶
In [60]:
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])
20 la
In [8]:
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])
Hello llo, Python! tho
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 [53]:
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)
LevelUp Level Up
3.3 Combine of string and number¶
In [9]:
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)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[9], line 2 1 age = 36 ----> 2 txt = "My name is John, I am " + age 3 print(txt) TypeError: can only concatenate str (not "int") to str
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 [1]:
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)
I have lived here for 5 years
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 [61]:
Copied!
print(5 > 3)
print(5 > 3)
True
- Most Values are True
In [64]:
Copied!
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
True True True
- Empty values are False
In [65]:
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(()))
False False False False False
5. List¶
In [13]:
Copied!
myclass = ['python', 'statistics', 'mapping', 'mapping']
print(myclass)
print(len(myclass))
myclass = ['python', 'statistics', 'mapping', 'mapping']
print(myclass)
print(len(myclass))
['python', 'statistics', 'mapping', 'mapping'] 4
In [ ]:
Copied!
mynote = ["python", 10, True, 'mapping', 23]
mynote = ["python", 10, True, 'mapping', 23]
5.1 Change list items¶
In [66]:
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 [36]:
Copied!
#### 5.2 Sort the list
fruits = ['apple', 'orange', 'blueberries', 'Mangoes']
fruits.sort(reverse=True)
print(fruits)
#### 5.2 Sort the list
fruits = ['apple', 'orange', 'blueberries', 'Mangoes']
fruits.sort(reverse=True)
print(fruits)
['orange', 'blueberries', 'apple', 'Mangoes']
In [33]:
Copied!
fruits.sort(reverse=True)
print(fruits)
fruits.sort(reverse=True)
print(fruits)
['orange', 'blueberries', 'apple', 'Mangoes']
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 [15]:
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)
clark {'name': 'clark', 'location': 'worcester', 'year': 1887}
6.1 Adding items¶
In [17]:
Copied!
university['room'] = 'BP310'
print(university)
university['room'] = 'BP310'
print(university)
{'name': 'clark', 'location': 'worcester', 'year': 1887, 'room': 'BP310'}
6.2 Methods for dictionaries¶
In [ ]:
Copied!
university = {
"name": "clark",
"location": "worcester",
"year": 1887
}
university = {
"name": "clark",
"location": "worcester",
"year": 1887
}
In [23]:
Copied!
### Get keys
key_un = university.keys()
key_un
### Get keys
key_un = university.keys()
key_un
Out[23]:
dict_keys(['name', 'location', 'year', 'room'])
In [42]:
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 [43]:
Copied!
print(university['description']['intro'])
print(university['description']['intro'])
Founded in 1887, Clark offers undergraduate and graduate programs with a focus on interdisciplinary studies, research opportunities, and community engagement
Exercise 5: Try methods for Dictionaries
- Use
values()
,items()
to get value and item from university