Python conditional and circular statements

Python conditional statements and loop statements

Tip: the following is the main content of this article. The following cases are for reference. Some cases come from the Internet and the copyright belongs to the original author.

1, Conditional statement

1.if

Syntax:

if boolean_expression:
    statement(s)

If Boolean_ If expression (Boolean expression) returns True, the statement of the if block is executed. Otherwise, the statement is not executed, and the program continues to execute the statement (if any) after the if statement.

Example 1: conditional statement (Boolean expression) is True

a = 2
b = 5

if a<b:
	print(a, 'Is less than', b)

Example 2: conditional statement (Boolean expression) is False

a = 2
b = 5

if a<b:
	print(a, 'Is less than', b) # 2 is less than 5

The condition provided in the if statement evaluates to false, so the statement in the if block will not be executed.

Example 3: a conditional statement (Boolean expression) has multiple conditions

Use logical operators (and, or, not) to connect multiple conditions and create composite conditions.

a = 2
b = 5
c = 4

if a<b and a<c:
	print(a, 'Is less than', b, 'and', c) # 2 is less than 5 and 4

Example 4: Boolean expression evaluates to a number

If the expression in the if statement evaluates to a number, the statement is executed if the number is non-zero. Zero is considered false and non-zero (positive or negative) is considered true.

a = 2

if a:
	print(a, 'is not zero') # 2 is not zero.

Example 5: if conditional statement block contains multiple statements

a = 2

if a:
	print(a, 'is not zero')
	print('And this is another statement')
	print('Yet another statement')

Output:

2 is not zero
And this is another statement
Yet another statement

Example 6: nested if

a = 2

if a!=0:
	print(a, 'is not zero.')
	if a>0:
		print(a, 'is positive.')
	if a<0:
		print(a, 'is negative.')

2.if else

Syntax:

if boolean_expression:
    statement(s)
else:
    statement(s)

Example 1: condition is True

a = 2
b = 4

if a<b: # 2 < 4 returns True, so the if block is executed
	print(a, 'is less than', b)
else:
	print(a, 'is not less than', b)

Example 2: condition is False

a = 5
b = 4

if a<b: # 5 < 4 returns False, so else block is executed
	print(a, 'is less than', b)
else:
	print(a, 'is not less than', b)

Example 3: nested if else

a = 2
b = 4
c = 5

if a<b:
	print(a, 'is less than', b)
	if c<b:
		print(c, 'is less than', b)
	else:
		print(c, 'is not less than', b)
else:
	print(a, 'is not less than', b)

3.elif

Syntax:

if boolean_expression_1:
	statement(s)
elif boolean_expression_2:
	statement(s)
elif boolean_expression_3:
	statement(s)
else
	statement(s)

Example 1: if elif else

a = 2
b = 4

if a<b:
	print(a, 'is less than', b)
elif a>b:
	print(a, 'is greater than', b)
else:
	print(a, 'equals', b)

Example 2: if elif elif else: with multiple elif blocks

a = 2

if a<0:
	print(a, 'is negative')
elif a==0:
	print('its a 0')
elif a>0 and a<5:
	print(a, 'is in (0,5)')
else:
	print(a, 'equals or greater than 5')

4.if and

Example 1: if conditional expression with and operator

a = 5
b = 2

# Nested if
if a==5:
	if b>0:
		print('a is 5 and',b,'is greater than zero.')
		
# Alternatively, combine multiple conditions into one expression
if a==5 and b>0:
	print('a is 5 and',b,'is greater than zero.')

Example 2: if else conditional expression with and operator

a = 3
b = 2

if a==5 and b>0:# If the condition holds, execute here
	print('a is 5 and',b,'is greater than zero.')
else:# If the condition does not hold, execute here
	print('a is not 5 or',b,'is not greater than zero.')

Example 3: elif conditional expression with and operator

a = 8

if a<0:
	print('a is less than zero.')
elif a>0 and a<8:
	print('a is in (0,8)')
elif a>7 and a<15:
	print('a is in (7,15)')

5.if or

Example 1: if conditional expression with or operator

today = 'Saturday'

if today=='Sunday' or today=='Saturday':
	print('Today is off. Rest at home.')

Example 2: if else conditional expression with or operator

today = 'Wednesday'

if today=='Sunday' or today=='Saturday':
	print('Today is off. Rest at home.')
else:
	print('Go to work.')

Example 3: elif conditional expression with or operator

today = 'Sunday'

if today=='Monday':
	print('Your weekend is over. Go to work.')
elif today=='Sunday' or today=='Saturday':
	print('Today is off.')
else:
	print('Go to work.')

6.if not

Syntax:

if not value:
    statement(s)
  • value is bool type:
If value yes bool Type, then NOT Acts as a negative operator.
If value by False,be not value Will be True,also if-block The statement in will execute.
If value by True,be not value Will be False,also if-block Statements in will not be executed.
  • value is string type:
If value yes string Type, then if-block The statements in will be string Execute when empty.
  • value is list type:
If value yes list Type, then if-block The statements in will be list Execute when empty.
The same interpretation applies to values of other collection data types: dict,set and tuple. 

Example 1: not - bool

a = False

if not a:
	print('a is false.')

Example 2: not - string

string_1 = ''

if not string_1:
    print('String is empty.')
else:
    print(string_1)

Example 3: not - list

a = []

if not a:
    print('List is empty.')
else:
    print(a)

Example 4: not - dict

a = dict({})

if not a:
    print('Dictionary is empty.')
else:
    print(a)

Example 5: not - set

a = set({})

if not a:
    print('Set is empty.')
else:
    print(a)

Example 6: not - tuple

a = tuple()

if not a:
    print('Tuple is empty.')
else:
    print(a)

7. Ternary operator

https://blog.csdn.net/weixin_40458518/article/details/120477844

2, Circular statement

It is often used for loop iteration of (range, list, tuple, dictionary, set, string) sequences and sets.

1.for loop

Syntax:

for item in iterable:
    statement(s)

1.1 for loop of range

for i in range(25,29):
	print(i)

1.2 for loop of string

mystring = 'python.org'

for x in mystring:
	print(x)

1.3 for loop of list

mylist = ['python', 'programming', 'examples', 'programs']

for x in mylist:
	print(x)

1.4 for loop of tuple

mytuple = ('python', 'programming', 'examples', 'programs')

for x in mytuple:
	print(x)

1.5 for loop of Dict

mydictionary = {'name':'python', 'category':'programming', 'topic':'examples'}

for x in mydictionary:
	print(x, ':', mydictionary[x])

1.6 for loop of set

myset = {'python', 'programming', 'examples'}

for x in myset:
	print(x)

2.while loop

Syntax:

while condition:
    statement(s)

Example 1: while loop printing 1 to N

n = 4
i = 1
while i <= n:
	print(i)
	i+=1

3.break: interrupt

----------------------------- for-break -----------------------------

Example 1: in the for loop, break completely interrupts the program

for x in range(2, 10):
    if(x==7):
        break
    print(x)

Example 2: in the for loop, break completely interrupts the program, and the subsequent else statement block is not executed, which is invalid code.

for x in range(1, 11) :
    if x == 4:
        break # The program is completely interrupted, and the subsequent else statement block is not executed, which is invalid code.
    print(x)
else:
	print('else Code in does not execute/invalid')

Example 3: list as a for loop object

myList = [1, 5, 4, 9, 7, 2]

for x in myList :
    if x == 9:
        break
    print(x)

----------------------------- while-break -----------------------------

Example 1: in the while loop, break completely interrupts the program

a = 4
i = 0
while i<a:
	print(i)
	i+=1
	if i>1:
		break

Example 2: in the while loop, break completely interrupts the program, and the subsequent else statement block is not executed, which is invalid code.

i = 1
while i <= 10 :
    if i == 4 :
        break # The program is completely interrupted, and the subsequent else statement block is not executed, which is invalid code.
    print(i)
    i += 1
else:
	print('else Code in does not execute/invalid')

4.continue: skip

----------------------------- for-continue -----------------------------

Example 1: in the for loop, skip the loop

for x in range(2, 10):
    if(x==7):
        continue
    print(x)

Example 2: in the for loop, skip the loop

for x in range(1, 11) :
    if x%3 == 0 :
        continue # The else statement block after the for loop is not affected
    print(x)
else:
	print('This line of code is in for Execute before the end of the cycle')

----------------------------- while-continue -----------------------------

Example 1: in a while loop, skip the loop

a = 4

i = 0
while i<a:
	if i==2:
		i+=1 # If the conditional variable increment is not added in the while loop, the loop will die and the program will run continuously
		continue
	print(i)
	i+=1

Example 2: in a while loop, skip the loop

i = 1
while i <= 10 :
    if i == 4 or i==7 :
        i += 1
        continue
    print(i)
    i += 1

5.else: for loop or while loop, the code block executed before exiting

5.1 for-else

Example 1: use else statement block after for loop

for x in range(2, 6):
    print(x)
else:
    print('Out of for loop')

Example 2: break will completely interrupt the program. The else statement block is invalid and will not be executed

for x in range(1, 11) :
    if x == 4:
        break # The program is completely interrupted, and the subsequent else statement block is not executed, which is invalid code.
    print(x)
else:
	print('else Code in does not execute/invalid')

5.2 while-else

While else syntax:

while condition:
    statement(s)
else:
    statement(s)

Example 1: use else statement block after while loop

i = 0
while i < 5:
    print(i)
    i += 1
else:
    print('Printing task is done.')

Example 2: use else statement block to close file handle after while loop

f = open("sample.txt", "r")
while True:
    line = f.readline()
    if not line:
        break
    print(line.strip())
else:
    f.close

6. Nested loop

6.1 for nesting

for x in range(5):
    for y in range(6):
        print(x, end=' ')
    print()

6.2 while nesting

flag = True
while flag: # Layer 1 (outer) while loop
    username = input("enter one user name:")
    password = input("Please enter the user password:")

    if username == 'admin' and password == '123':
        while flag: # Second layer (inner layer) while loop
            command = input("Enter the to perform linux Code command:")
            if command.lower() == 'q':
                flag = False # Change the change and control the while loop of the first layer (outer layer) and the second layer (inner layer) at the same time
            print("Executing command:%s"%command)
            
    else:
        print('User name or password input error')

Keywords: Python Pycharm

Added by HhAaZzEeYy on Sun, 26 Sep 2021 02:21:08 +0300