expression - value 1 if expression 1 else value 2
Operation rules : If the result of the expression is True, Result is value 1, Otherwise it's worth 2.
# Example :
#1
a=100
result=1 if a>100 else 0
print(result)
#2
a=100
a+=1 if a>10 else -1
print(a)
#3
a=100
a=a+1 if a>10 else a-1# The value can be an operator
print(a)
# Format :
while Conditional statements :
The loop body
Other code
First, judge whether the conditional statement is True, If so, execute the loop body ; Judge and execute after execution , Until the result of the conditional statement is False
# loop 5 Time
times=0
while times<5
print(' loop ')
n+=1
# Infinite loop
while True:
print(' loop ')
# Login system
acount={
"acount1":"123","acount2":"234","acount3":"345"}
while True:
name =input (' Please enter a user name :')
if name in acount:
break
else:
print(' The username does not exist ')
while True:
password = input (' Input password :')
if acount[name] == password:
print(' Get into ')
break
else:
print(' Wrong password ')
continue
usage : End the cycle
# Guess number games
import random# Import random modular
my_num = random.randint(1, 100)# Produce a 1 To 100( Closed interval ) The random number .
times = 1
while True:
print(f' Start the first {
times} Guess the number ')
you_num = input(" Please enter an integer (1-100):")
if you_num=='':
continue
you_num = int(you_num)
if not 0<you_num<=100:
continue
if my_num == you_num:
print(f' Congratulations on your guesses , The number is {
my_num}')
break
else:
if my_num > you_num:
print(' The number is small ')
else:
print(' The number is too big ')
times += 1
Complete cycle structure
complete for:
for Variable in Sequence :
The loop body
else:
Code segment
complete while:
while Conditional statements :
The loop body
else:
Code segment
About else:
# Determine whether the string is a stored numeric string
# Method 1
str='123456789ab123'
for x in str1:
if not '0' <= x <= '9':
print(str1, ' It's not a pure numeric string ')
break
else:
print(str1, ' Is a pure numeric string ')
# Method 2
str1 = '123456789ab123'
flag = True
for x in str1:
if not '0' <= x <= '9':
flag = False
break
if flag:
print(' Pure numeric string ')