if

Since there are no brackets like in Java, indentation is very important in the if statement. 

In the example below, you must convert the string type 'n' to an integer

n = input('Insert an integer.')
print(type(n))             
n = int(n)                 

if n>=0 :
    print(n, 'is a positive number.')

if n<0:
    print(n, 'is a negative number.')

if ~ else with try~ except

try:
    n = int(input('Insert an integer.'))
    
    if n >= 0:
        print(n, 'is a positive number.')
    else:
        print(n, 'is a negative number.')
    
except:
    print('Please insert numbers only.')

if ~ elif ~ else

In Java, there is else if, whereas in Python it is elif. 

s = int(input('Insert your score.'))

if s >= 90:
    print('A')
elif s >= 80:
    print('B')
elif s >= 70:
    print('C')
elif s >= 60:
    print('C')
else:
    print('F')

 

Loops: for / while 

There is no do ~ while statement in Python. Usually for loops are used a lot.

for loop

for loops are many times used with range() built-in function.

Please refer to my last post if you want to know more about the range() function.

링크

Example1

for i in range(10):             # 0 ~ 9
    print(i+1, 'Cofee and Tea')

for i in range(1, 11):          # 1 ~ 10
    print(i, 'Love in Life')
    
for i in range(1, 11, 1):       # 1 ~ 10   
    print(i, 'Happy days')

Example2 

for i in range(1, 10, 2):
    print(i, end=' ')                   # 1 3 5 7 9
print()

for i in range(1, 10):                  # 1 ~ 9
    print(i, end=' ')                   # 1 2 3 4 5 6 7 8 9
print()

for i in range(10):                     # 0 ~ 9
    print(i, end=' ')                   # 0 1 2 3 4 5 6 7 8 9
print()

for i in range(10, 1, -1):
    print(i, end=' ')                   # 10 9 8 7 6 5 4 3 2

Example3

sum = 0
for i in range(1, 11):              #  1 ~ 10
    sum = sum + i                   # sum += i
    print('1~',i,'=',sum)

print('sum=', sum)

Example4

# Sum of odd numbers
odd = 0
for i in range(1, 101, 2):
    odd += i
print(odd)

# sum of even numbers
even = 0
for i in range(0, 101, 2):
    even += i
print(even);

Example5

It is the same result as Example4, but it is a simpler way with just one for loop. 

odd = even = 0
for i in range(1, 101):                 # 1 ~ 100
    if i%2 == 0:                        # Even 
        even += i
    else:                               # Odd
        odd += i
print('1~100 sum of odd numbers:', odd)
print('1~100 sum of even numbers:', even)

Example6

#Multiplication table with a format() function.

dan = int(input('Insert a number between 1 and 9.'))

print('[',dan,'Table ]')
for i in range(1, 10):              # 1 ~ 9
    # print(dan, '*', i, '=', dan * i)
    print('{0} * {1} = {2}'.format(dan, i, dan*i))

Example7 

for loop with list

# List
list = ['China', 'Canada', 'Egypt', 'South Korea', 'France']
print(type(list))              # <class 'list'>
print(list)                    # ['China', 'Canada', 'Egypt', 'South Korea', 'France']
print(list[0])                 # China

for i in list:
    print(i, end=' ')           # China Canada Egypt South Korea France
print()

for loop with tuple

#Tuple
t = ('red','orange','yellow','green','blue','navy','purple')
print(type(t))                  # <class 'tuple'>
print(t)                        # ('red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple')
print(t[0])                     # red

for i in t:
    print(i, end=' ')           # red orange yellow green blue navy purple
print()

for loop with dictionary

# Dictionary : { 'key' : 'value' }
dic = {'Apple' : 'http://www.apple.com',
       'Google' : 'http://www.google.com',
       'Naver' : 'http://www.naver.com'}

print(type(dic))                # <class 'dict'>
print(dic)                      # {'Apple': 'http://www.apple.com', 'Google': 'http://www.google.com', '네이버': 'http://www.naver.com'}
print(dic['Apple'])             # http://www.apple.com

for k, v in dic.items():
    print(k,':', v)

while loop

while loop is very similar to Java.

Example1 

i = 1                          
while i <= 10 :                
    print(i,'I love Python')           
    i += 1

Example2

i=1; odd=even=0                
while i <= 100:                # Condition
    if i%2 == 0:                # Even numbers
        even += i
    else:                       # Odd numbers
        odd += i
    i += 1                      

print('1~100 sum of odd numbers:',  odd)
print('1~100 sum of even numbers:',  even)

Example3

Multiplication table with format function.

dan = int(input('Insert a number between 1 to 9'))

i = 1                                  
while  i <= 9:                          
    # print(dan, '*', i, '=', dan*i)
    print('{0} * {1} = {2}'.format(dan, i, dan*i))
    i += 1

Example4

Multiplication table

dan=2                                     
while dan <= 9:                             
    print('[',dan,'Table ]')
    i = 1
    while i <= 9:                           
        print(dan, '*', i, '=', dan*i)
        i += 1                              
    dan += 1                              
    print()

break and continue

Infinite loop 

i=1
while True:

    print(i, 'Infinite loop')
    i += 1

Infinite loop with break

i=1
while True:

    print(i, 'Infinite loop')
    if i == 100: break
    i += 1

for, if, and break

for i in range(1, 1001):            # 1 ~ 1000
    print(i,'Print')

    if i==100:
        print('Loop Escaped')
        break

continue

continue is for going back to the loop. 

Example1 

for i in range(1, 11):              # 1 ~ 10

    if i==5:
        continue
    print(i, 'Print')

Example2 

If it is not divided into 5, it skips printing.

for i in range(1, 101):             # 1 ~ 100

    if i%5 != 0:                    
        continue
    print(i)

'Python' 카테고리의 다른 글

Python) try: except:  (0) 2022.11.14
Python) list  (0) 2022.11.08
Python) Dictionary  (0) 2022.11.04
Python) Tuple / Set  (0) 2022.11.03
Python) Datatypes - Str  (0) 2022.11.03

+ Recent posts