Conditional statements and while loops

1. Conditional statement if...else

1. if basic statement

Examples:

If a person is older than or equal to 18, output Adult, otherwise output Not Adult

#!/usr/bin/env python
# -*- coding:utf8 -*-
age_of_man = 20
if age_of_man >= 18:
    print("adult")
else:
    print("Not an adult")

2. if supports nesting

if condition 1:

Indented Code Blocks

elif condition 2:

Indented Code Blocks

elif condition 3:

Indented Code Blocks

  ......

  else:  

Indented Code Blocks

 

Excellent if score >=90, good if score >=80 and <90, qualified if score >=60 and <80, and unqualified if other

#!/usr/bin/env python
# -*- coding:utf8 -*-
score = input(">>: ")
score = int(score)
if score >= 90:
    print("excellent")
elif score >= 80:
    print("good")
elif score >=60:
    print("qualified")
else:
    print("Unqualified")

 

 

2. while Cycle

while condition:    
    #Circulator
 
    #If the condition is true, then the loop body executes, and after execution, it loops again to re-judge the condition.
    #If the condition is false, the loop does not execute and the loop terminates

 

#Print 0 to 10
#!/usr/bin/env python
# -*- coding:utf8 -*-
count=0
while count <= 10:
    print(count)
    count+=1

 

 

Dead cycle

#!/usr/bin/env python
# -*- coding:utf8 -*-
while 1 == 1:
    print("ok")

 

 

Practice

1. Use the while loop to output 1 2 3 4 6 7 8 9 10

#Method One

count = 1
while count < 11:
    if count == 5:
        pass
    else:
        print(count)
    count = count + 1

#Method 2

n = 0
while n < 11:
    if n == 5:
        n = n + 1
        continue
    print(n)
    n = n + 1

 

2. Output of odd numbers within 100

count = 1
while count < 101:
    temp = count % 2
    if temp == 0:
        pass
    else:
        print(count)
    count = count + 1

3. Sum 1 to 100 numbers

n = 1
s = 0
while n <101:
    s = s + n
    n = n + 1
print(s)

4. Seek 1-2+3-4+5-6...+99

n = 1
s = 0
while n < 100:
    temp = n % 2
    if temp == 0:
        s = s - n
    else:
        s = s + n
    n = n + 1
print(s)

5. User logon (three retries)

count = 0
while count < 3:
    user = input('>>>')
    pwd = input('>>>')
    if user == 'reese' and pwd == '123':
        print('Welcome to login')
        break
    else:
        print('ERROR Incorrect username or password')
    count = count + 1

Tags: Python

Posted on Sat, 25 Apr 2020 09:56:58 -0700 by JMulligan