From 43baae470c8d7d48a1dfbed3f805948c1143f57e Mon Sep 17 00:00:00 2001
From: vand <vand@dtu.dk>
Date: Thu, 10 Jun 2021 19:34:24 +0000
Subject: [PATCH] Upload New File

---
 module4_looping.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 61 insertions(+)
 create mode 100644 module4_looping.py

diff --git a/module4_looping.py b/module4_looping.py
new file mode 100644
index 0000000..41dcc5c
--- /dev/null
+++ b/module4_looping.py
@@ -0,0 +1,61 @@
+#%% example -- can't change iterator during for loop, formatting display
+
+for i in range(10):
+    print(f'i is {i}, trying to change it to {3*i}')
+    i = 3*i # don't do this (trying to change an iterator in a for loop)
+    
+
+#%% example -- find largest number divisible with 7 and smaller than 100    
+i = 1
+while i*7<100:
+    i = i+1
+print(7*i) # this will be larger than 100 -- so condition from while does not hold
+
+#%% example -- vectorization
+
+import numpy as np
+test = np.array([3, 4, 8, 6, 5, 8, 3, 4, 7, 8, 8, 9, 4, 1, 3, 4, 6, 7, 9, 5, 3, 5, 7, 2, 5, 3])
+
+## I want to count how many times does 8 appear in test
+
+# One way of achieving this
+count = 0
+for t in test:
+    if t==8:
+        count += 1
+        
+# A better way of achieving this
+count = (test==8).sum()
+
+
+#%% I want to count how many times does each digit appear in test
+
+# One way of achieving this
+hist = np.zeros(10, dtype='int')
+for i in range(len(hist)):
+    hist[i] = (test==i).sum()
+
+# Another way of achieving this
+hist = np.zeros(10, dtype='int')
+for t in test:
+    hist[t] += hist[t]
+    
+ 
+#%% Avoid using break for better readability, if possible
+
+# Without break: readable code, easly to see when while loop stops
+i = 0
+while i<101: 
+    i = i+1
+    print(i, end= ' ')
+    
+    
+# With break: may be difficult to see when loop stops (especially in loops spanning many lines)
+i = 0
+while True:
+    i = i+1
+    print(i, end= ' ')
+    if i>100:
+        break
+
+
-- 
GitLab