---
# System prepended metadata

title: python v.s. C++
tags: [code]

---

# python v.s. C++
###### tags: `code`
:::danger
### 變數宣告
:::



:::info
* **C++**
*type: int(實數)  double、float(浮點數) char(字元)  bool(布林值)*
* **python**
*系統自動初步判斷，若有需求需自動轉型*
:::





:::spoiler **C++**
::: success
**<C++>**
```C++=
int x;
double y=0;
float z,z1;
char a,b,c;
bool k=true;
```
:::




:::spoiler **python**

:::info
```python=
x=150       #自動判別int (有時會判成char)
y=z=151.5   #float
T=True      #bool
A='a'       #char
```
**p.s. python 只有float 沒有double**




:::
---
:::danger
### 轉型
:::
:::info
相同的資料型別才能做運算
:::
:::warning
## **%格式化**
* **%d => int**
* **%f => float**
* **%x => 16進制**
* **%X => 16進制(大寫)**
* **%o => 8進制**
* **%s => 字串**
* **%e => 科學記號e輸出**
* **%E => 科學記號E輸出**
:::



:::spoiler **C++**
:::success
  **<C++>** 
 ```c++=
 int i='a';
 std::cout<<a<<std::endl;
 std::cout<<static_cast<int>(a)<<std::endl;
 ```
 * 四捨五入法
```C++=
//利用有效數字的方法達成
#include<iomanip>
double PI=3.141592653;
cout<<setprecision(5)<<PI<<endl;  取到5位
```
:::




:::spoiler  **python** 
:::info
**<python>**
```python=
i='a'
print(str(i))
```
* 備註:利用type()能確認變數的型別
---

	
```python=
i='a'
print(type(i))
```
>> <class 'str'>
---

	
	

* 轉型彙總
```python=
i=150
j=3.1415926
k='a'
print(int(j))          #浮點數 -> 整數 
print(float(i))        #整數   -> 浮點數
print(ord(j))          #字元   -> UNICODE
print(char(32))        #ASCII -> 字元
```
* float->int  ==**無條件捨去**==
---

	
* round()指令:
```python=
i=3.1515926
round(i,2)             #i四捨五入法到小數點後第2位
```
:::
---

:::danger
### 四則運算
:::
	
:::info
**特殊語法:**

**i+=2  => i=i+2**
**i-=2  => i=i-2**
		**...依此類推**
			
:::danger
* **%為取餘數的意思**
* **在C++語法中存在i ++，在python中，必須輸入i += 1**
:::	

	
:::spoiler **C++**
:::success
```c++=
int a=5;
int b=10;
int c=(a*b)*10;
cout<<c<<endl;
:::


:::spoiler **python**
:::info
```python=	
a=10
b=15
c = (a + b) / b
print(c)
```
:::
---

:::danger
### **IF 關係式**
:::
	
:::info
* ==**= 的觀念是把值丟入; ==是做比較喔~:bangbang:**==
:::warning
* **>    大於**
* **<    小於**
* **<=   小於/等於**
* **>=   大於/等於**
* **==   等於**   ==**非常重要:bangbang:**==
:::

:::spoiler **C++**
:::success
```C++=
int a=4;
int b=5;

if(a<b)
{
cout<<"1"<<endl;		 
}
else_if(a>b)
{
cout<<"2"<<endl;		
}
else
{
cout<<"equal"<<endl	
}
```
:::
:::spoiler **python**
:::info	
```python
a=4
b=5

if(a>b):
	print("1")
elif(a<b):
	print("2")
else:
	print("equal")	   
```
:::
---
:::danger
### 輸入及輸出		   
:::
:::info
* **C++中具有列印及==掃描==的觀念**
* **python 只具有寫入的元素**
:::
:::spoiler **C++**
:::success
```C++=
int a;			//宣告變數
cout<<"輸入變數=";   	//輸出詢問
cin>>a;		  	//輸入寫入
```		   		   

* **利用cin及cout達成==寫入==及==輸入==的功能**
* **:bangbang:cout是 ==<== ; cin是 ==>==**
:::

	
:::spoiler **python**
:::info
```python=		
i=input("輸入變數")
print(int(i))
```
:::
---
:::danger
### 邏輯運算子
:::
:::info
* **具有AND、OR、NOT**
:::
:::spoiler **C++**	
:::success
* AND => &&
* O R => ||
* NOT => !
```C++=
int a;	
if(a>5 ||b<=-20)
{
cout<<"hello world!"										
}
else_if(a<4 && a!=0)
{
cout<<"crying world?"		
}
else_if(a==0)
{
cout<<"歸剛ㄟ!"	
}
```	
:::

:::spoiler **python**
:::info
:bangbang: **python中沒有&&、||，要用英文輸入**
```python=
a=input("a=")
b=input("b=")
if(int(a)>5) or (int(b)<=-20):
	{
	print("hello world!")						
	}
elif(int(a)<4) and (int(a)!=0):
	{
	print("crying world?")		
	}
elif(int(a)==0):
	{
	print("歸剛ㄟ!")	
	}	
```
:::
---	
:::danger
### 運算元素(進階)	
:::
:::info
**次方運算**
:::
:::spoiler **C++**
:::success
```c++=
#include<cmath>

int i=5;
int y=pow(i,3);
int z=sqrt(i)
cout<<"y="<<y<<endl;
cout<<"z="<<z<<endl;
```
:::
:::spoiler **python**
:::info
```python=
i=5
print(i**3)
print(i**0.5)	
```
:::
---
:::info
**亂數**
:::
:::spoiler **C++**
:::success
```C++=	
#include<ctime>
srand(time(NULL));
int i=1+rand()%(10-1+1);
```
* :bangbang:==**下限+rand()%(上限-下限+1)**==
:::
:::spoiler **python**
:::info
```python=
import random
import string
i=random.randint(1,50)	
```	
* ==**rand(下限,上限)**==
:::	

---
	
:::danger
### 串列
:::
	
:::info
* **具有一個變數有很多值的功能**
:::
	
:::spoiler **C++**
:::success
```C++=
int i[5];		//宣告五格串列
int j=[2,3,4,5,6];	//設定變數內容
```
:::
:::spoiler **python**
:::info
* **串列性質辨別**
```python=
i=[2,3,2,4,5,7]
print("1~3筆資料",i[0:2])    #輸出多個數值
print("最後一筆資料",i[-1])   #最後一筆i[-1]
print("最後第二筆資料",i[-2]) #最後第二筆i[-2]
print("最大=",max(i[0:5]))   #最大的max(i[0:5])
print("最小=",min(i[0:5]))   #最大的min(i[0:5])
print("總和=",sum(i[0:5]))   #最大的sum(i[0:5])	
print("資料數",len(i))	      #資料數len(i)	
```
* **len(i)可用來判斷空串列**
---
* **更改串列**
```python=
i=[3,6,4,8,2]
i[3]=0
print("修改後",i)
```
---	
* **串列加法**
```python=
num1=[3,2,1]
num2=[1,2,3]
print(num1+num2)
#>>[3,2,1,1,2,3]
print(num1[1]+num2[1],num1[2]+num2[2],//
	//num1[3]+num2[3])
#>>3,3,3
```
---	
* **刪除串列**
```python=
num=[6,9,5,1,3,7,26,4]
del num[0]	
print("刪除第1項",num)
num1=[6,9,5,1,3,7,26,4]
del num1[0:2]	
print("刪除前2項",num1)
num2=[6,9,5,1,3,7]	
del num2[0:6:2] 
print("間格刪除",num2)  
			 #[start,end,step]
num3=[6,9,5,1,3,7]	
del num3 
```
---
* **打包**
```python=
a,b,*c=1,5,6,3,4,8
print(a,b,c)
a,*b,c=2,6,3,5,9,7,45
print(a,b,c)
```
**>>1 5 [6, 3, 4, 8]**
**>>2 [6, 3, 5, 9, 7] 45**
:::
---
:::danger
### 字串物件導向
:::
:::spoiler **python**
:::info
* **大小寫轉換**
```python=
x='ABC'
y='abc'
z='AbCd'
print(x.lower())	#全轉小寫
print(y.upper())	#全轉大寫
print(y.title())	#首字轉大寫
print(z.swapcase())	#大寫轉小寫;小寫轉大寫
```
---
* **刪除空白元素**
```python=
x=' abc'
y='abc '
z=' abc '
print(x.lstrip())
print(y.rstrip())
print(z.strip())
```
---
* **字串對齊**
```python=
string="abc"
print("/%s/" % string.center(10)) #10:長度空間(置中) 
print("/%s/" % string.ljust(10)) #10:長度空間(置左)
print("/%s/" % string.rjust(10)) #10:長度空間(置右)
print("/%s/" % string.zfill(10)) #10:長度空間(前方空缺補0)
```
---
* **字元增加(上篇章)**
```python=
car=[]
print(car)	#>>[]
car.append('Honda')
print(car)	#>>[Handa]	
car.append('Porche')
print(car)	#>>['Honda', 'Porche']	
car.insert(1,'Bugatti')	#插入
print(car)	#>>['Honda', 'Bugatti', 'Porche' ]	
```
* **(下篇)**
```python=	
car=['Honda','Porche','Nissan','Audi']
car2=['Bugatti','BMW','Maserati']
car.append(car2)
print(car)
print(car2)
```	
* **延接**
```python=
car=['Honda','Porche','Nissan','Audi']
car1=['Bugatti','BMW','Maserati']
car.extend(car1)
print(car)
```
---
* **刪除串列**
```python=
car=['Honda', 'Bugatti', 'Porche', 'Volvo']
car_pop=car.pop()
print(car_pop)			#刪除項:Volvo
print(car)			#刪除後的串列['Honda','Bugatti','Porche']
car_popp=car.pop(2)
print(car)			#['Honda','Bugatti']
expensive='Bugatti'
carpop = car.remove(expensive)	#['Honda']
print(car)
```
---
* **顛倒排序**
```python=
car=['Honda', 'Bugatti', 'Porche', 'Volvo']
car.reverse()	#顛倒動作
print(car)
```
---
* **排序**
```python=
car=['Honda', 'Bugatti', 'Porche', 'Volvo']
car.sort(reverse=True)	#字母大排到小
print(car)
Num=Num2=[1,5,9,4,3,7]
Num.sort(reverse=False)
Num2.sort(reverse=True)
print(Num,Num2)
```
---	
* **搜索**
```python=
car=['Honda', 'Bugatti', 'Porche', 'Volvo']
Num=[1,5,3,7,4,9,2,6,48,8]
search_str='Bugatti'
i=car.index(search_str)
search1_str=48
j=Num.index(search1_str)
print(f"{search_str},{i+1}")
print(f"{search1_str},{j+1}")
```
* ==**:bangbang:數字搜索記得不要加''**==
---
* **計數**
```python=
car=['Honda', 'Bugatti', 'Porche','Honda', 'Volvo']
search_str='Honda'
num=car.count(search_str)
print(f"{search_str},{num}")
```
---
* **串列內的串列**
```python=
num=[1,5,9,6,3,[6,7,3]]
print(num[5][2])
```
* **二維串列**
```python=
sc=[
  ['JAMES',60,80,99,0],
  ['PETER',90,50,66,0]
   ]
sc[0][4]=sum(sc[0][1:4])
sc[1][4]=sum(sc[1][1:4])
print(sc[0])
print(sc[1])
```
---
* **id位址**
```python=
num=[1,5,9,6,3,[6,7,3]]
print(id(num))
```
---	
* **字串切片**
```python=
string="ineedagirlfriend!"
print(string[0])
print(string[1:5])
print(string[5])
print(string[6:10])
print(string[10:16])
print(string[16])
```
:::
---
:::danger
### 迴圈(loop)
:::

:::success
* **for**
:::
:::spoiler **C++**
:::success
```C++=
int sum=0;
for(int i=0;i<=100;i++)
{
sum+=i;						
}
```
* **簡單的1加到100**
:::

:::spoiler **python**
:::info
* **串列輸出**
```python=
car=['Audi','Bugatti','Cadillac','Nissan']
for cars in car:
	print (cars)
```
---
```python=
sum=0
for i in range(1,101): #加到第100項(1,100+1)
    sum = sum + i
print(sum)
```
```python=
for i in range(10,101): #從10印到100
print(i)
```
* **:bangbang:記得加到第100項(1,100+1)**
:::	
---