程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python operators and if constructs

編輯:Python

Python運算符與if結構

一、昨日回顧

1、Review of the curriculum content of yesterday

2、Review homework yesterday

定義變量,c1 = ‘可樂’,c2 = ‘牛奶’,通過Python代碼把c1Content is adjusted for milk,c2Adjustment for coke.

# 1、定義兩個變量
c1 = '可樂'
c2 = '牛奶'
# 2、使用python將c1和c2的值進行交換(引入第三方變量,如temp)
# 第一步:首先把c2The milk in the cup into the temporarytemp杯子中
temp = c2
# 第二步:把c1中值賦值給c2這個變量(相當於把c1The coke intoc2中)
c2 = c1
# 第三步:把tempPour the milk in the glassc1種
c1 = temp
print(f'1The cup:{
c1}')
print(f'2The cup:{
c2}')

二、Python數據類型轉換

1、使用PythonRealize the supermarket cashier system

Python:

name = input('Please provide the name you want to buy goods:')
id = input('Please enter the number do you want to buy goods:')
price = input('Please input you want to purchase commodity prices:')
print(f'您購買了{
name},商品編號為{
id},商品價格為{
price},歡迎下次光臨!')

Of the program but can be done in accordance with the above procedure normal output,But the legacy of a very serious problem:這個價格priceVariables are unable to participate in math(Such as bought two oreo cookies,應該是18.5 * 2),原因在於input()Method returns all the results arestr字符串類型.

How to solve the above problem? 答:使用數據類型轉換

2、了解Python數據類型的轉換方法

函數說明int(x [,base ])將x轉換為一個整數float(x)將x轉換為一個浮點數complex(real [,imag ])創建一個復數,real為實部,imag為虛部str(x)將對象 x 轉換為字符串repr(x)將對象 x 轉換為表達式字符串eval(str)用來計算在字符串中的有效Python表達式,並返回一個對象tuple(s)將序列 s 轉換為一個元組list(s)將序列 s 轉換為一個列表chr(x)將一個整數轉換為一個Unicode字符ord(x)將一個字符轉換為它的ASCII整數值hex(x)將一個整數轉換為一個十六進制字符串oct(x)將一個整數轉換為一個八進制字符串bin(x)將一個整數轉換為一個二進制字符串

案例1:The user input lucky number,轉換為整型

num = input('請輸入您的幸運數字:')
print(type(num))
# 數據類型轉換,把str字符串類型轉換為int類型
print('-' * 20)
num = int(num)
print(type(num))

The above code can also be abbreviated to:

num = int(input('請輸入您的幸運數字:'))
print(type(num))

案例2:A variety of data type conversion

# 1、Integer turn floating-point type int => float
num1 = 10
print(float(num1))
print(type(float(num1)))
print('-' * 20)
# 2、Floating point types into integer float => int,浮點轉整型,The data will be lost after the decimal point!!!
num2 = 18.88
print(int(num2))
print('-' * 20)
# 3、Convert a string type to integer or floating point types
str1 = '20'
str2 = '10.88'
print(type(int(str1)))
print(type(float(str2)))

案例3:eval()方法的使用,Convert the number in the string to the original data type

price = input('Please enter your purchase prices of the goods:')
print(eval(price))
print(type(eval(price)))

str1 = ‘10’ 經過eval(str1) 轉換為int類型

str2 = ‘10.88’ 經過eval(str1) 轉換為float類型

3、總結

Data type conversion method were studied4個方法:

int() :轉整型

float() :Turn floating-point type

str() :轉字符串類型

eval() :Convert a string to the original data type

但是要特別注意:當floatFloating point types intoint整型時,The decimal point data will be lost,Keep in mind that this feature.

三、Python運算符

1、運算案例

需求:User manual input in the shape of a trapezoid base、下底以及高,能直接通過PythonPrint out the area of the trapezium is how much.

2、算術運算符

The so-called arithmetic operator is waiting in our daily life addition, subtraction, multiplication, and division.

運算符描述實例+加1 + 1 輸出結果為 2-減1 - 1 輸出結果為 0*乘2 * 2 輸出結果為 4/除10 / 2 輸出結果為 5//整除9 // 4 輸出結果為 2%取余(取模)9 % 4 輸出結果為 1**冪指數2 ** 4 輸出結果為 16,即2的4次方,2 * 2 * 2 * 2()小括號小括號用來提高運算優先級,即 (1 + 2) * 3 輸出結果為 9

案例1:了解一下算術運算符

num1 = 10
num2 = 2
# 四則運算 + - * /
print(f'加:{
num1 + num2}')
print(f'減:{
num1 - num2}')
print(f'乘:{
num1 * num2}')
print(f'除:{
num1 / num2}')

案例2:And other programming languages several arithmetic operators is not the same

num1 = 20
num2 = 6
num3 = 5
# 1、整除
print(f'整除:{
num1 // num2}')
# 2、求余數
print(f'余數:{
num1 % num2}')
# 3、冪指數
print(f'冪指數:{
num2 ** 3}')
# 4、圓括號
print(f'優先級:{
(num1 + num2) * num3}')

3、算術運算符案例:求梯形的面積

知識點:用戶輸入、Data type conversion and arithmetic operators

a = float(input('請輸入上底:'))
b = float(input('請輸入下底:'))
h = float(input('請輸入高:'))
s = (a + b) * h / 2
print(f'梯形的面積:{
s}')

4、賦值運算符

運算符描述實例=賦值將=右側的結果賦值給等號左側的變量

案例1:Put a value assigned to a variable

num = 10

案例2:Multiple variables simultaneously assignment operator

n = 5
f = 10.88
s = 'hello world'

簡寫為:

n, f, s = 5, 10.88, 'hello world'
print(n)
print(f)
print(s)

案例3:多個變量賦予相同的值

a = 10
b = 10

簡寫為:

a = b = 10

5、復合賦值運算符

復合賦值運算符 = 算術運算符 結合 賦值運算符

The calculation of compound assignment operator sequence = To perform arithmetic operators,執行完畢後,The results in the assigned to the variable on the left.

案例:綜合案例

i = 1
# Additive and assignment,先加1,Then assigned to the results on the left side of the variable
i += 1
print(f'更新後,i的值為:{
i}')
num1 = 9
# 取模並賦值,先求余數,And then the result variables assigned to the left
num1 %= 2
print(f'更新後,num1的值為:{
num1}')
num2 = 2
# The power and value assignment,First exponentiation index,Then assigned to the results on the left side of the variable
num2 **= 3
print(f'更新後,num2的值為:{
num2}')

6、比較運算符

特別注意:When we use comparison operators to compare two variables,其返回一個布爾類型的值.

案例:The size of the two Numbers to compare

num1 = 10
num2 = 20
print(num1 > num2) # False
print(num1 < num2) # True
print(num1 >= num2) # False
print(num1 <= num2) # True
print(num1 == num2) # False
print(num1 != num2) # True

7、練習題

練習題1:Prompt the user for the radius of the circle,根據公式S = πr2求圓的面積

r = float(input('Please input to calculate the radius of the circle:'))
PI = 3.14
s = PI * r ** 2
print(f'圓的面積為:{
s}')

練習題2:賦值運算 => 輸入身高,體重,求BMI = 體重(kg)/身高(m)的平方.

height = float(input('請輸入您的身高(m):'))
weight = float(input('請輸入您的體重(kg):'))
bmi = weight / height ** 2
print(f'您的BMI值為{
bmi}')

8、邏輯運算符(與或非)

not就是取反,只有一個表達式not 表達式,如果表達式為True,則notThen I returnFalse.反之,則返回True.

Tell a little story if you are the one:

① A girl who require higher,Asked the boy must have house and car

表達式1 and 表達式2
當表達式1為True且表達式2為True時,The entire expression returns the results asTrue
當表達式1或表達式2One of the expression is false,The entire expression returns the results asFalse
有房 and 有車 則 牽手成功
有房 and 沒車 則 Connecting rod failure
沒房 and 有車 則 Connecting rod failure

② A girl asked general,Ask the boys have a house or a car can be

表達式1 or 表達式2
當表達式1為True或表達式2為True時,The entire expression returns the results asTrue
當表達式1與表達式2都為False時,The entire expression will returnFalse
有房 or 有車 則 牽手成功
有房 or 沒車 則 牽手成功
沒房 or 有車 則 牽手成功
沒房 or 沒車 則 Connecting rod failure

案例:

a = 1
b = 2
c = 3
print((a > b) and (b > c)) # False
print((a > b) or (b > c)) # False
print((a < b) or (b > c)) # True
print(not (a > b)) # True

9、擴展:短路運算

print(3 and 4 and 5) # 5
print(5 and 6 or 7) # 6
4 > 3 and print('hello world') # 輸出hello world

在邏輯運算中,On both sides of logical operators are not pure expression.Data can also be a numeric type.

Python把0、空字符串和None看成 False,其他數值和非空字符串都看成 True,所以:

① 在計算 a and b 時,如果 a 是 False,則根據與運算法則,整個結果必定為 False,因此返回 a;如果 a 是 True,則整個計算結果必定取決與 b,因此返回 b.

print(3 and 4) # 4
print(0 and 1) # 0

② 在計算 a or b 時,如果 a 是 True,則根據或運算法則,整個計算結果必定為 True,因此返回 a;如果 a 是 False,則整個計算結果必定取決於 b,因此返回 b. 所以Python解釋器在做布爾運算時,只要能提前確定計算結果,它就不會往後算了,直接返回結果.

print(6 or 7) # 6
print(6 and 7 or 8) # 7

10、運算符的優先級

What is the operator priority?Actually we primary school had contact with the,Is in an expression,We first calculate the question of whom to.

先算乘除,後算加減,有括號的先算括號裡面的.

個人建議:

① 不要把一個表達式寫得過於復雜,如果一個表達式過於復雜,Try to split it to write

② Don't rely too much on the operator priority to control execution sequence of expression,這樣可讀性太差,應盡量使用( )來控制表達式的執行順序

四、if選擇判斷結構

1、ifSelect judge structure effect

在日常開發中,As long as there is need to judge the conditional statements are basically choose for structure.

應用場景:

如果年齡大於等於18歲,Can be normal access to the Internet.

If the upgrade test scores more than60分,You can upgrade smoothly employment class.

2、ifSelect judge structure basic grammar

Java:

if (條件判斷) {

Execute a piece of code...
}

但是Python中,Don't need to use so many complex symbol,Can be written directly condition judgment and perform a piece of code

Python:

if 條件判斷:
Execute a piece of code...
print()

案例代碼:

if True:
print('條件成立執行的代碼1')
print('條件成立執行的代碼2')
# 下方的代碼沒有縮進到if語句塊,所以和if條件無關
print('我是無論條件是否成立都要執行的代碼')

3、if選擇結構案例

需求:定義一個變量age = 18,Whether the variable is greater than or equal to18歲,如果滿足條件,Can the Internet.

案例1:Direct definition judgment,進行條件判斷

age = 18
if age >= 18:
print('滿足18Age requirements,可以正常上網')

案例2:On the Internet bar case update

age = int(input('請輸入您的年齡:'))
if age >= 18:
print('滿足18Age requirements,可以正常上網')

if選擇原理圖:Not to learn programming in addition to writing the code also,Also back to the drawing(流程圖)

4、if…else…結構

基本語法:

if 條件判斷:
當條件判斷為True時,The execution of this statement period
else:
當條件判斷為False時,The execution of this statement period

案例3:On the Internet bar case upgrade upgrade,引入else

age = int(input('請輸入您的年齡:'))
if age >= 18:
print('滿足18Age requirements,可以正常上網')
else:
print('不滿足18Age requirements,Home study hard,天天向上')

if…else…結構原理圖:

5、if…elif…elseMany conditions determine structure

如果條件1成立,則執行語句段1

如果條件2成立,則執行語句段2

當所有條件都不成立時,則執行elseThe contents of the statement period

if 條件判斷1:
If this condition isTrue,The execution of this statement period
elif 條件判斷2:
If this condition isTrue,The execution of this statement period
elif ...:
...
else:
If above all condition judgment does not meet the,The execution of this statement period

案例:

① 中國合法工作年齡為18-60歲,即如果年齡小於18的情況為童工,不合法;

② 如果年齡在18-60歲之間為合法工齡;

③ 大於60歲為法定退休年齡.

# 定義一個變量,Receive input from the user's age
age = int(input('請輸入您的年齡:'))
if age < 18:
print('Are you still a child,回去好好學習')
elif age >= 18 and age <=60:
print('合法工齡,可以正常工作')
elif age > 60:
print('You have already reached the retirement age,回家好好休息')
else:
print('信息輸入有誤,請重新輸入')

簡寫形式:

# 定義一個變量,Receive input from the user's age
age = int(input('請輸入您的年齡:'))
if age < 18:
print('Are you still a child,回去好好學習')
elif 18 <= age <= 60:
print('合法工齡,可以正常工作')
elif age > 60:
print('You have already reached the retirement age,回家好好休息')
else:
print('信息輸入有誤,請重新輸入')

ifMultiple condition judgment principle diagram:

6、if嵌套結構

基本語法:

if 外層條件判斷:
# 如果條件為True,Then perform the following statement
if 內層條件判斷:
# If the inner conditions forTrue,Then perform the following statement
else:
# 如果條件為False,Then perform the following statement

Nested structure seems complicated,But we should follow when writing a principle:To write the first outer judgment,All statements written after the completion of the,In the lining of the writing condition judgment structure.

案例:外層條件①,是否有錢,有錢可以上車.內層條件 ② Is there a vacant seat determine whether,如果有,則可以坐下.

""" 根據條件(是否有錢)Determine whether you can get on the bus money = 0 沒錢 money = 1 有錢 """
money = 1
seat = 0
if money == 1:
# 有錢,可以上車
print('有錢,可以上車')
# if嵌套(seat = 1On behalf of empty seats,seat = 0On behalf of no seats available on)
if seat == 1:
# 有座位,可以坐下
print('有座位,可以坐下')
else:
# 沒有座位,Can only stand to go home
print('沒有座位,Can only stand to go home')
else:
# 沒錢,Can only walk home
print('沒錢,Can only walk home')

五、綜合案例:石頭剪刀布

1、需求分析

Involved in the role of the game, there are two(玩家 與 電腦),The player manually punch,電腦隨機出拳,According to the stone scissors cloth judgment win.

玩家:player(Player manually enter stone、剪刀、布)

電腦:computer(隨機出拳)

It is very important to win or lose result,有三種情況:

① 玩家贏

* player:石頭 贏 computer:剪刀

* palyer:剪刀 贏 computer:布

* player:布 贏 computer:石頭

② 平局

只要player 與 computerPunch is equal,就代表平局

③ 電腦贏

如果不滿足以上兩個條件,則電腦獲勝!

The unknown knowledge:How to make the computer random punches => 隨機

2、代碼實現

確認:if…elif…else多條件分支結構

# 第一步:Prompted for input stone scissors cloth,0-代表石頭,1代表剪刀,2代表布
player = int(input('請輸入您的出拳0-代表石頭,1代表剪刀,2代表布:'))
# 第二步:電腦隨機出拳(後續解決)
computer = 1
# 第三步:According to the user and the computer punch judgment win
# 什麼情況,Players will win
# player==0且computer==1 或 palyer==1且computer==2 或 player==2且computer==0
if (player == 0 and computer == 1) or (player == 1 and computer == 2) or (player==2 and computer == 0):
print('玩家獲勝')
elif player == computer:
print('平局')
else:
print('電腦獲勝')

遺留問題:The computer can't random punches

3、隨機出拳

PythonLanguage is very strong,Powerful is its many modules(module),These modules have a lot of people have developed good code,We can import directly into our program can be used in the.

① import導入模塊

② 通過模塊.方法()調用相關功能

Random punch is random from0,1,2中選出一個數字

import random
# Call internal encapsulation method
computer = random.randint(0, 2)

Improved mora code:

import random
# 第一步:Prompted for input stone scissors cloth,0-代表石頭,1代表剪刀,2代表布
player = int(input('請輸入您的出拳0-代表石頭,1代表剪刀,2代表布:'))
# 第二步:電腦隨機出拳(後續解決)
computer = random.randint(0, 2)
print(computer)
# 第三步:According to the user and the computer punch judgment win
# 什麼情況,Players will win
# player==0且computer==1 或 palyer==1且computer==2 或 player==2且computer==0
if (player == 0 and computer == 1) or (player == 1 and computer == 2) or (player==2 and computer == 0):
print('玩家獲勝')
elif player == computer:
print('平局')
else:
print('電腦獲勝')

六、三目運算符

1、什麼是三目運算符

在PythonThe ternary operator is also called the ternary operator,其主要作用:就是用於簡化if…else…語句.

2、基本語法

if 條件判斷:
# 語句段1
else:
# 語句段2

Convert the ternary operator:

語句段1 if 條件判斷 else 語句段2

3、The ternary operator case

需求:輸入兩個數值,返回最大值

num1 = 10
num2 = 20
if num1 > num2:
print(f'最大值為{
num1}')
else:
print(f'最大值為{
num2}')

簡化:三目運算符

num1 = 10
num2 = 20
max = num1 if num1 > num2 else num2
print(f'最大值為{
max}')

yer0且computer1 或 palyer1且computer2 或 player2且computer0
if (player == 0 and computer == 1) or (player == 1 and computer == 2) or (player==2 and computer == 0):
print(‘玩家獲勝’)
elif player == computer:
print(‘平局’)
else:
print(‘電腦獲勝’)


# 六、三目運算符
## 1、什麼是三目運算符
在PythonThe ternary operator is also called the ternary operator,其主要作用:就是用於簡化if...else...語句.
## 2、基本語法
```python
if 條件判斷:
# 語句段1
else:
# 語句段2

Convert the ternary operator:

語句段1 if 條件判斷 else 語句段2

3、The ternary operator case

需求:輸入兩個數值,返回最大值

num1 = 10
num2 = 20
if num1 > num2:
print(f'最大值為{
num1}')
else:
print(f'最大值為{
num2}')

簡化:三目運算符

num1 = 10
num2 = 20
max = num1 if num1 > num2 else num2
print(f'最大值為{
max}')

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved