python04 while循環、flag、break、continue


1 運算符

2 表達式和運算符

 

算數運算符:+-*/ //整除  %取余 **次方

比較運算符:>< >=  <= !=不等於 ==等於     #單個等於表示賦值

賦值運算符:=  += -= *=  /= //=整除等於 %=取余等於 **=次方等於


num+=2      num=num+2 #等價於
num-=2       num=num-2
num*=2        num=num*2
num/=2        num=num/2
num//=2       num=num//2
num%=2        num=num%2
num**=2        num=num**2

邏輯運算符:and  or  not      #沒有優先級,實際操作中用()來添加優先級。

條件1  and  條件2

條件1  or  條件2

短路原則:對於and,如果前面一個為假,那么這個and前后兩個條件組成的表達式的計算結果就一定為假,第二個條件就不會被計算。

                 對於or,如果前面一個為真,那么這個or前后兩個條件組成的表達式的計算結果就一定為真,第二個條件就不會被計算。

 

表達式與運算符:

什么是表達式?3+4*5就是表達式,這里的加號、乘號就是運算符,3、4、5就是操作數。三個數結果等於23.  3+4*5=23.  我們可以將計算結果保存在一個變量里,如number=3+4*所以 表達式即使操作數和運算符組成的一句代碼或者語句,表達式可以求值,可以放在“=”右邊,用來給變量賦值。.

 

 

 

找出三個數中的最大值:

a=input("number1:")
b=input("number2:")
c=input("number3:")

if int(a)>int(b):
if int(a)>int(c):
  print("a is the biggest")
else:
  print("c is the biggest")

else:
int(b)>int(a)
if int(b)>int(c):
  print("b is the biggest")
else:
  print("c is the biggest!")

#里面有太多int轉換,直接把它在定義的時候就轉換如下:

a=int(input("number1:"))
b=int(input("number2:"))
c=int(input("number3:"))
if a>b:
if a>c:
  print("a is the biggest")
else:
  print("c is the biggest")

else:
b>a
if b>c:
  print("b is the biggest")
else:
  print("c is the biggest!")

 

用while來實現循環。

age=66
#guess_age=int(input("your age: "))

 


while True:
guess_age=int(input("your age: "))
  if guess_age == age:
    print("yes")
    break #終止
  elif guess_age>age:
    print ("is bigger")
  else:
    print("is smaller")

print("end")

 


flag = True

while flag:
  guess_age=int(input("your age: "))
  if guess_age == age:
    print("yes")
    flag=False
  elif guess_age>age:
    print ("is bigger")
  else:
    print("is smaller")

print("end")

 

# continue(滿足條件就跳過)
num = 1
while num<=10:
  num += 1
  if num == 3:
    continue
  print(num)

輸出結果:

2
4
5
6
7
8
9
10
11

# continue
num = 1
while num<=10:
num += 1
if num == 3:
continue
print(num)

else:         #只有break中止的時候不執行
print("this is else statement")

輸出內容為:

2
4
5
6
7
8
9
10
11
this is else statement

 

# continue
num = 1
while num<=10:
  num += 1
  if num == 5:
    break
  print(num)

else:           #只有break中止的時候不執行
  print("this is else statement")

輸出結果為

2
3
4

while 條件:
....
else:
....

  

print("helloworld")
print("helloworld")
print("helloworld")

輸出結果為:

helloworld
helloworld
helloworld

print("helloworld",end="-")   # \n  \r\n \r
print("helloworld",end="-")
print("helloworld",end="-")

輸出結果為:

helloworld-helloworld-helloworld-

 

while條件1

  ......

  while 條件2  

  ......

 

num1=0
while num1<=5:
print(num1,end="-")
num2=0
while num2<=7:
print(num2,end="_")
num2+=1
print()
num1+=1

輸出結果為:

1-0_1_2_3_4_5_6_7_
2-0_1_2_3_4_5_6_7_
3-0_1_2_3_4_5_6_7_
4-0_1_2_3_4_5_6_7_
5-0_1_2_3_4_5_6_7_


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM