if
#!/usr/bin/python number=23 guess=int(input(‘Enter an interger:‘)) #input返回的结果是string类型,需要用int()转化为int类型 if guess == number: print(‘You guessed in.‘) elif guess < number: print(‘No, it is a little higher than that‘) else: print(‘No, it is a little lower than that‘) print(‘Done‘)
while
#!/usr/bin/python number = 23 while True: guess=int(input(‘Enter an integer:‘)) if guess==number: print(‘You guessed it‘) break elif guess<num: print(‘No, it is a little higher than that‘) else: print(‘No, it is a little lower than that‘) else:#else下的statements是在while的条件为假时执行的,但如果有break,它就不会执行了 print(‘The while loop is over‘) print(‘Done‘)
for
#!/usr/bin/python for i in range(1,5): print(i) else:#else下的statements是在for循环结束后执行的,但如果有break,它就不会执行了 print(‘The for loop is over‘)
range有三个参数,第三个参数在默认情况下为1,表示步长
range返回一个list,前闭后开,如:
range(1,5) 返回 [1,2,3,4]
range(1,5,2)返回 [1,3]
break和continue的用法与C++中一样
时间: 2024-10-06 10:38:41