Learn Conditional Statements with Practice Questions
1, use the while loop to output 1 2 3 4 5 6 8 9 10
n=1 while n<11: if n=7: pass else: print(n) n=n+1 print('----end----')
2, find the sum of all numbers from 1 to 100
n=1 sum=0 while n<101: sum=sum+n n=n+1 print sum
3, output all odd numbers within 1-100
n=1 while n<101: if n %2==0: pass else: print n n=n+1 print('---end---')
4, output all even numbers within 1-100
n=1 while n<101: if n %2==0: print n else: pass n=n+1 print('---end---')
5, find the sum of all numbers from 1-2+3-4+5....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
6, the variable name:
Can be alphanumeric underscore PS: Numbers cannot start, cannot be keywords, it is best not to duplicate the built-in things in Python
7, the conditional statement:
a.
n1 = input('>>>')
if "alex" == "wy":
n2 = input('>>>')
if n2 == "确认":
print('wy SB')
else:
print('wy DB')
else:
print('error')
注意:
n1 = "wy" 赋值
n1 == 'wy' 比较,
b.
if 条件1:
pass
elif 条件2: elif condition 3:
pass
pass
else:
pass
print('end')
c. Condition 1
and or
if n1 == "sy" or n2 == "sy!23":
print('OK')
else:
print('OK')
PS:
pass Refers to empty code, meaningless, only used to represent code blocks
8, basic data types:
string - n1 = "sy" n2 = 'root' n3 = """eric""" n4='''tony'''
number - age=21 weight = 64 fight = 5
addition, subtraction, multiplication and division etc:
String:
Addition:
n1 = "sy"
n2 = "sb"
n4 = "db"
n3 = n1 + n2 + n4
# "sysbdb"
Multiplication:
n1 = "sy"
n3 = n1 * 10
numbers:
n1 = 9
n2 = 2
n3 = n1 + n2
n3 = n1 - n2
n3 = n1 * n2
n3 = n1 / n2
n3 = n1 % n2
n3 = n1 ** n2
Problem:
11 12 13 ...
num = 12
n = num % 2
if n == 0:
print ('even')
else:
print('odd')
9.
Infinite loop
while 1==1:
print('ok')