python中if判斷語句

2021-09-14 07:38:21 字數 2636 閱讀 1025

if的用法

「」"if 要判斷的條件:

條件成立的時候,要做的事情

…else:

條件不成立的時候,要做的事情

…「」"

1.定義乙個變數

age = 16

2.判斷年齡是否滿18歲

age = 16

if age>=18:

print('成年',age)

else:

print('未成年',age)

「」"

if 要判斷的條件:

條件成立的時候,要做的事情

…elif 要判斷的條件:

…elif 要判斷的條件:

…else:

條件不成立的時候,要做的事情

…「」"

score=input('score')

if 90 <= score < 100:

grade = 'a'

elif 80 <= score < 90:

grade = 'b'

else:

grade = 'c'

print(grade)

value = input('value: ')

if value=='':

print('error')

value = input('value: ')

if not value:

print('請輸入合法的值')

匯入python第三方模組

>>> import random

>>> random.randint(12,20) #返回[12,20]之間的整數

12>>> random.randint(12,20)

12>>> random.randint(12,20)

19>>> random.randint(12,20)

20>>> random.randint(12,20)

20>>> random.randint(12,20)

13>>> random.randint(25,20) #下限必須小於上限

traceback (most recent call last):

file "", line 1, in file "/usr/local/python3.6/lib/python3.6/random.py", line 221, in randint

return self.randrange(a, b+1)

file "/usr/local/python3.6/lib/python3.6/random.py", line 199, in randrange

raise valueerror("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))

valueerror: empty range for randrange() (25,21, -4)

import random

player = int(input('請輸入要出的拳 --石頭(1)/剪刀(2)/布(3):'))

computer = random.randint(1, 3)

print('玩家選擇的是%d,電腦選擇的是%d' %(player,computer))

if ((player == 1 and computer == 2)

or (player == 2 and computer == 3)

or (player == 3 and computer == 1)):

print('玩家勝')

elif player == computer:

print('平局')

else:

print('玩家輸')

邏輯運算符號

「」"and

條件1 and 條件2

兩個條件同時滿足,就返回true

只要有乙個條件不滿足,就返回false

or條件1 or 條件2

兩個條件只要有乙個滿足,就返回true

兩個條件都不滿足的時候,就返回false

「」"

a=34

b=89

if a>=60 or b>=60:

print('合格')

else:

print('come on')

if 練習

判斷閏年?

使用者輸入年份year, 判斷是否為閏年?

2.隨機選擇乙個三位以內的數字作為答案。使用者輸入乙個數字,程式會提示大了或是小了,直到使用者猜中

import random

running=true

computer=random.randint(1,100)

print(computer)

while running:

num = int(input('請輸入乙個數'))

if num>computer:

print('輸入的數字過大')

elif numprint('輸入的數字過小')

else:

print('輸入正確')

running=false

Python 判斷語句

1 復合條件判斷 如果乙個人的年齡大於等於60歲,且為男性,則為老先生 age float input 請輸入年齡 gender input 請輸入性別 if age 60 and gender male print 老先生 else print 不是老先生 也可以這麼寫 age float inp...

Python判斷語句

python中只有一種判斷語句,就是if.else.其中有三種常用的形式 1 只有if,沒有else if 判斷條件 執行語句 2 有if又有else if 判斷條件 執行語句 else 執行語句 3 既有if,又有elif,又有else if 判斷條件 執行語句 elif 判斷條件 執行語句 el...

Python中的if判斷語句

if語句是用來進行判斷的,其使用格式如下 if 要判斷的條件 條件成立時,要做的事情 案例 age 30 print if判斷開始 if age 18 print 我已經成年了 print if判斷結束 執行結果 if判斷開始 我已經成年了 if判斷結束 案例 age 16 print if判斷開始...