This commit is contained in:
clariguy
2024-06-20 17:12:25 +00:00
committed by GitHub

View File

@@ -2,13 +2,13 @@
* Python is an interpreted, high-level and general-purpose, dynamically typed programming language
* It is also Object oriented, modular oriented and a scripting language.
* It is seen as an object-oriented, modular scripting language.
* In Python, everything is considered as an Object.
* In Python, everything is considered as an object.
* A python file has an extension of .py
* Python follows Indentation to separate code blocks instead of flower brackets({}).
* Python follows indentation to separate code blocks instead of using flower/curly brackets ({}).
* We can run a python file by the following command in cmd(Windows) or shell(mac/linux).
@@ -138,11 +138,9 @@
thislist = ["apple", "banana", "cherry"]
```
- List items are ordered, changeable, and allow duplicate values.
- List items are ordered, changeable / mutable, and allow duplicate values. We can change, add, and remove items in a list after it has been created.
- List items are indexed, the first item has index `[0]`, the second item has index `[1]` etc.
- The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
- List items are zero-indexed. The first item has index `[0]`, the second item has index `[1]` etc.
- To determine how many items a list has, use the `len()` function.
@@ -150,17 +148,18 @@ thislist = ["apple", "banana", "cherry"]
```python
list1 = ["abc", 34, True, 40, "male"]
```
- It is also possible to use the list() constructor when creating a new list
- Lists can either be created as above or using the list() constructor as follows:
```python
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
```
- pop() function removes the last value in the given list by default.
- pop() function removes and returns the last value in the given list by default. Should a different index be added in the brackets, the element with that index will be removed and returned.
```python
thislist = ["apple", "banana", "cherry"]
print(thislist.pop()) # cherry
print(thislist.pop(0)) #apple
print(thislist.pop(0)) # apple
```
@@ -174,11 +173,11 @@ thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
```python
thistuple = ("apple", "banana", "cherry")
```
- Tuple items are ordered, unchangeable, and allow duplicate values.
- Tuple items are ordered, unchangeable / immutable, and allow duplicate values. We cannot change, add or remove items after the tuple has been created.
- Tuple items are indexed, the first item has index `[0]`, the second item has index `[1]` etc.
- When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.
- Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
- Since tuple are indexed, tuples can have items with the same value:
- Tuples allow duplicate values:
```python
@@ -187,18 +186,18 @@ thistuple = ("apple", "banana", "cherry", "apple", "cherry")
- To determine how many items a tuple has, use the `len()`function:
```python
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
print(len(thistuple)) # 3
```
- To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
- To create a tuple with only one item, you have to *add a comma after the item*, otherwise Python will not recognize it as a tuple.
```python
thistuple = ("apple",)
print(type(thistuple))
print(type(thistuple)) # tuple
# NOT a tuple
thistuple = ("apple")
print(type(thistuple))
print(type(thistuple)) # string
```
- It is also possible to use the tuple() constructor to make a tuple.
- It is also possible to use the tuple() constructor to make a tuple:
```python
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
@@ -206,24 +205,21 @@ print(thistuple)
```
### Set
- Set is a collection which is unordered and unindexed. No duplicate members.
- A set is a collection which is both unordered and unindexed.
- Set is a collection which is unordered and unindexed. There can be no duplicate members.
- Since sets are unordered and unindexed, the items in a set do not have a defined order. Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
- Duplicate values will be ignored.
```python
thisset = {"apple", "banana", "cherry"}
```
- Set items are unordered, unchangeable, and do not allow duplicate values.
- Unordered means that the items in a set do not have a defined order.
- Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
- Sets are unchangeable, meaning that we cannot change the items after the set has been created.
- Duplicate values will be ignored.
- To determine how many items a set has, use the `len()` method.
```python
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
print(len(thisset)) # 3
```
- Set items can be of any data type:
```python
set1 = {"apple", "banana", "cherry"}
@@ -231,25 +227,29 @@ set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"}
```
- It is also possible to use the `set()` constructor to make a set.
- It is also possible to use the `set()` constructor to make a set:
```python
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
```
- frozenset() is just an immutable version of Set. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.
```python
set1 = {"apple", "banana", "cherry"}
frzset=frozenset(set1)
print(frzset)
print(frzset) # {"apple", "banana", "cherry"}
```
### Dictionary
- Dictionary is a collection which is unordered and changeable. No duplicate members.
- Dictionary is a collection which is unordered and changeable. There can be no duplicate members.
- Dictionaries are used to store data values in key:value pairs.
- Dictionaries cannot have two items with the same key.
- Dictionaries are written with curly brackets, and have keys and values:
```python
thisdict = {
"brand": "Ford",
@@ -257,6 +257,7 @@ thisdict = {
"year": 1964
}
```
- Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
```python
thisdict = {
@@ -264,15 +265,17 @@ thisdict = {
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
print(thisdict["brand"]) # Ford
```
- Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
- Dictionaries cannot have two items with the same key.
- Dictionaries are changeable / mutable, meaning that we can change, add or remove items after the dictionary has been created.
- Duplicate values will overwrite existing values.
- To determine how many items a dictionary has, use the `len()` function.
-
```python
print(len(thisdict))
print(len(thisdict)) # 3
```
- The values in dictionary items can be of any data type
```python
thisdict = {
@@ -294,8 +297,8 @@ thisdict = {
x = car.pop("model")
print(x)# Mustang
print(car)#{'brand': 'Ford', 'year': 1964}
print(x) # Mustang
print(car) # {'brand': 'Ford', 'year': 1964}
```
@@ -304,12 +307,13 @@ thisdict = {
```python
if condition:
pass
pass # Code to execute if condition is true.
elif condition2:
pass
pass # Code to execute if condition2 is true.
else:
pass
pass # Code to execute if neither condition nor condition2 is true.
```
### Loops
Python has two primitive loop commands:
@@ -318,18 +322,58 @@ thisdict = {
#### While loop
- With the `while` loop we can execute a set of statements as long as a condition is true.
- Example: Print i as long as i is less than 6
```python
i = 1
while i < 6:
print(i)
i += 1
# Output: 1, 2, 3, 4, 5
```
- The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.
- With the `break` statement we can stop the loop even if the while condition is true
- With the continue statement we can stop the current iteration, and continue with the next.
- With the else statement we can run a block of code once when the condition no longer is true.
- The while loop requires relevant variables to be ready. In this example we need to define an indexing variable, i, which we set to 1. This has to be done before starting with the loop.
- With the `break` statement we can stop the loop even if the while condition is true.
- Example: Print i as long as i is less than 6
```python
i = 1
while True:
if i < 6:
print(i)
i += 1
else:
break
# Output: 1, 2, 3, 4, 5
```
- With the `continue` statement we can stop the current iteration, and continue with the next.
- Example: Print i as long as it is less than 6 and not equal to 3.
```python
i = 0
while i < 6:
i += 1
if i == 3:
continue
else:
print(i)
# Output: 1, 2, 4, 5
```
- With the `else` statement we can run a block of code once when the condition no longer is true.
```python
i = 1
while i < 6:
print(i)
i += 1
else:
print("The loop is finished")
# Output: 1, 2, 3, 4, 5, The loop is finished
```
#### For loop
- A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
@@ -340,16 +384,22 @@ while i < 6:
```python
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
print(x) # apple banana cherry
```
- The for loop does not require an indexing variable to set beforehand.
- To loop through a set of code a specified number of times, we can use the range() function.
- The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
- The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3).
- The else keyword in a for loop specifies a block of code to be executed when the loop is finished.
A nested loop is a loop inside a loop.
- The "inner loop" will be executed one time for each iteration of the "outer loop":
- To loop through a set of code a specified number of times, we can use the range() function.
- The range function returns a list of integers starting at zero or the starting value up to but not including the ending value, in increments of 1 unless otherwise defined:
```python
range(4) # [0, 1, 2, 3]
range(2, 4) # [2, 3]
range(1, 10, 2) # [1, 3, 5, 7, 9]
```
- The else keyword in a for loop specifies a block of code to be executed when the loop is finished.
- A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop":
```python
adj = ["red", "big", "tasty"]
@@ -359,6 +409,7 @@ for x in adj:
for y in fruits:
print(x, y)
```
- for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.
```python
@@ -377,6 +428,7 @@ def function_name():
function_name()
```
* A function must either return a value or have some content.
* We need not to specify the return type of the function.
* Functions by default return `None`
* We can return any datatype.