Last time: We talked about if-else. I forgot to tell you about the in-line if-else:
x = 0 if True else 1
print(x)
x = 0 if True else 1
print(x)
Very clever way to repeat actions. Syntax:
`while CONDITION FOR DOING THE NEXT ITERATION OF THE LOOP: STUFF THAT WILL BE REPEATED IN EVERY ITERATION
x = 0
while x<10:
print(x)
x = x + 1
Shortcut: Instead of writing x = x + 1
, we can write x += 1
. So cool.
# Let's use the cool shortcut while doing something a little more nice
# sum of first 100 numbers:
x = 1
total = 0
while x<=100:
total += x
x = x + 1
print(total)
What you need to do is to read the code and run it yourself, step by step, in your head and/or paper.
The condition must be True
for the loop to run the first time
# there will be no output from this
while False:
print("This line will never print")
If the condition is always true, then you get an infinite loop!
# DON'T RUN (or be ready to press stop)
x = 0
while x == 0:
print("All work and no play makes Jack a dull boy.")
Indentation is important to see what is in the loop:
# Don't run this or be ready to press stop. Why does it do an infinite loop?
x = 0
while x<10:
print(x)
x = x + 1
The unindented part is not within the loop, so x is never icreased during the loop. So x<10
is always True, and the loop never ends.
We want to write a function called isprime
that checks if a number is prime. Returns True if number is prime, False otherwise.
Again, either try to write it yourself, or look through the code and run it in your head/on-paper.
def isprime(n):
if n <= 1:
return False
d = 2
while d<n:
if n % d == 0:
return False
d += 1
return True
isprime(5)
isprime(7)
isprime(57) # it's 3x19
Can we make this more efficient? Yes, we don't need to check all the way up to n-1
, we could actually check up to $\sqrt{n}$ because if there is a factor larger than $\sqrt{n}$, then there is also a factor smaller than $\sqrt{n}$, namely $\frac{n}{\sqrt{n}}$.
def isprime(n):
if n <= 1:
return False
d = 2
while d*d<=n: # so clever!!!
if n % d == 0:
return False
d += 1
return True
//
as division(a,b)
. Make sure you are doing the negative number examples correctly. math.pi
. (by the way, this comes from the Taylor expansion of arctan)