Study/Python

[Python] Repl.it - if/else/for문/print()

안다희 2019. 1. 16. 01:34
728x90

https://snakify.org/lessons/if_then_else_conditions/

 

- if/else

 

x = int(input())
if x > 0:
    print(x)
else:
    print(-x) 

 

- abs() : 절댓값

 

x = int(input())
print(abs(x)) // 절댓값. 
input : 10 / output : 10
input : -10 / output : 10

 

- bool

 

print(bool(-10))    # True
print(bool(0))      # False - zero is the only false number
print(bool(10))     # True


print(bool(''))     # False - empty string is the only false string
print(bool('abc'))  # True 

 

- or

 

a = int(input())
b = int(input())
if a % 10 == 0 or b % 10 == 0:
    print('YES')
else:
    print('NO') 

 

- and not

 

if a > 0 and not (b < 0): 

 

 

- elif

 

x = int(input())
y = int(input())
if x > 0 and y > 0:
    print("Quadrant I")
elif x > 0 and y < 0:
    print("Quadrant IV")
elif y > 0:
    print("Quadrant II")
else:
    print("Quadrant III") 

 

 

- 변수 위치

if else 안에서 처음 선언해도 if else 밖에서 그 변수 사용 가능!

 

- 윤년문제

 

a = int(input())


if a % 400 == 0: print("LEAP")
else: //오오
  if a % 4 == 0:
    if a % 100 == 0: print("COMMON")
    else: print("LEAP")
  else:
    print("COMMON") 

 

 

https://snakify.org/lessons/for_loop_range/

 

- for문

 

for character in 'hello':
    print(character)

//output 

h

o

 

for i in range(5, 8):
    print(i, i ** 2) 

//output

5 25

6 36

7 49

 

for i in range(3):
    print(i) 

0

1

2

 

for i in range(2 ** 2):
    print('Hello, world!') 

Hello, world!

Hello, world!

Hello, world!

Hello, world!

 

Range() can define an empty sequence, like range(-5) or range(7, 3). In this case the for-block won't be executed

for i in range(-5):
    print('Hello, world!')


for i in range(7, 3):
~~ 

none

 

range(start_value, end_value, step)

for i in range(10, 0, -2):
    print(i) 

10

8

6

4

2

// 0은 출력 안됨

 

- 그냥 print() : \n 개행

 

- 끝에 조건 달기

print(1, 2, 3)
print(4, 5, 6)
print(1, 2, 3, sep=', ', end='. ')
print(4, 5, 6, sep=', ', end='. ')
print()
print(1, 2, 3, sep='', end=' -- ')
print(4, 5, 6, sep=' * ', end='.') 

1 2 3

4 5 6

1, 2, 3. 4, 5, 6. 

123 -- 4 * 5 * 6.

 

 

- 예제

for i in range(a, b - 1, -1): //a = 8, b = 5
    print(i) 

위처럼 b - 1을 해줘야 8 7 6 5가 출력됨 (8, 4, -1) => 8 7 6 5 

출처: https://mingos-habitat.tistory.com/34 [밍고의서식지:티스토리]