/ W3SCHOOLS

W3schools - Python_If / Loop

이 페이지는 다음에 대한 공부 기록입니다
Lecture에서 배웠던 내용을 복습하며 작성했습니다

찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요

If else

Python supports the usual logical conditions from mathematics

a = 33
b = 200
if b > a:
print(b is greater than a)
elif a == b:	# if the previous condition were not true, then try this condition
print(a and b are equal)
else:		# Catches anything which isn’t caught by the preceding conditions
print(a is greater than b)
# output “b is greater than a”

# short hand
print(b is greater than a) if b > a else print(a and b are equal) if a == b else print(a is greater than b)

pass

if can’t be empty, but if you for some reason have an if with no content, put in the pass to avoid getting an error

Loop

while

Can execute a set of statements as long as a condition is true

It requires relevant var to be ready

i = 1
while i < 6:
if i == 3:
continue	# Can stop the current iteration, and continue with the next
if i == 5:
break	# Can stop the loop even if the while condition is true
print(i, end= )
i += 1
# output 1 2 4
else:
print(blah blah)	# Can run a block of code once when the condition no longer is true

for

Is used for iterating over a sequence

Is less like the for in other programming langs, and works more like an iterator method as found in other OOP langs

With for loop we can execute a set of statements, once for each item in a list, string…

Doesn’t require an indexing var to set beforehand

Can use break, continue, else, pass keyword

friends = [Patrick, Squidward, Gary, Sandy]
for x in friends:
print(x, end=  )	# output “Patrick” “Squidward” “Gary” “Sandy”

range()

To loop through a set of code a specified number of times, we can use the range()

It returns a sequence of numbers, starting from 0 by default, and increments by 1 by default, and ends at a specified number

for x in range(6):
print(x, end= )	# output 0,1,2,3,4,5

# Can specify detail, parameter (starting value, end value, increment value)
for x in range(2, 10, 2)
print(x, end = )	# output 2,4,6,8