各语言通用入门编程

42 篇文章 0 订阅
37 篇文章 0 订阅

欢迎关注微信公众号“Python小灶,和我一起每天学习Python新知识”
在这里插入图片描述

说明

各语言通用入门编程,欢迎大家补充。语言是相通的,尤其是基础语法:输入输出、判断、循环等等;

希望大家能通过这份清单快速的了解一门其它语言的基础语法,也可以用自己常用的语言和其它的语言做一个直观的对比。

不断改进,不断补充。

打印"Hello, World"

C
#include <stdio.h>
 
int main()
{
    printf("Hello, World! \n");
    return 0;
}
Python
print("Hello, World!")
Java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World");
    }
}
js
alert("Hello World");
console.log("Hello World");

注释

C
// 单行注释
/*多
行
注
释*/

Python
# 单行注释
"""这
是
多
行
"""
Java
// 单行注释
/*多
行
注
释*/
js
//单行注释
/*
    多行注释
    多行注释
    多行注释
*/

基本输入输出

C
#include <stdio.h>
 
int main()
{
    int n = 0;
    scanf("%d", &n); // 遇到空格停止输入
    printf("n:%d", n);
    return 0;
}
Python
n = input()
print(n)
Java
import java.util.Scanner; 

public class HelloWorld {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println(in.nextLine());;
    }
}
js

None

基本数据类型

C
// 基本类型:
// 它们是算术类型,包括两种类型:整数类型和浮点类型。
// 整数(int, char, short, long)  
int a;
printf("%d",...)
scanf("%d",...)
// 浮点型
double b;  // 双精度double用lf,单精度float用f
printf("%f",...)
scanf("%lf",...)
// 字符 单引号
char c;
printf("%c",...)
scanf("%c",...)

// 枚举类型:
// 它们也是算术类型,被用来定义在程序中只能赋予其一定的离散整数值的变量
    
// void 类型:
// 类型说明符 void 表明没有可用的值。
    
//派生类型:
//它们包括:指针类型、数组类型、结构类型、共用体类型和函数类型。   
// 地址
printf("%p",...) 
Python
# Number(数字)
## 支持 int、float、bool、complex(复数)。

# String(字符串)
## Python中的字符串用单引号 ' 或双引号 " 括起来,同时使用反斜杠 \ 转义特殊字符。

# List(列表)
## List(列表) 是 Python 中使用最频繁的数据类型。
## 列表可以完成大多数集合类的数据结构实现。列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列## 表(所谓嵌套)。

# Tuple(元组)
## 元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号 () 里,元素之间用逗号隔开。

# Set(集合)
## 集合(set)是由一个或数个形态各异的大小整体组成的,构成集合的事物或对象称作元素或是成员。

# Dictionary(字典)
## 字典是一种映射类型,字典用 { } 标识,它是一个无序的 键(key) : 值(value) 的集合。
Java
// 内置数据类型
// 六种数字类型(四个整数型,两个浮点型),一种字符类型,还有一种布尔型。
public class Test {
    static boolean bool;
    static byte by;
    static char ch;
    static double d;
    static float f;
    static int i;
    static long l;
    static short sh;
    static String str;
 
    public static void main(String[] args) {
        System.out.println("Bool :" + bool);
        System.out.println("Byte :" + by);
        System.out.println("Character:" + ch);
        System.out.println("Double :" + d);
        System.out.println("Float :" + f);
        System.out.println("Integer :" + i);
        System.out.println("Long :" + l);
        System.out.println("Short :" + sh);
        System.out.println("String :" + str);
    }
}

// 引用数据类型
// 在Java中,引用类型的变量非常类似于C/C++的指针。
js
// javascript常用变量类型: 
// Numbers, String, Boolean,    Object: Array, Undefined, Null
const name   = 'John'; // String
const age    = 22;     // Numbers
const rating = 4.5;    // Numbers, 没有浮点类型,只是数字
const isCool = true;   // Boolean
const x      = null;   // Object
let z        = [1,2,3];  //Object
const y      = undefined; // undefined
/* let和const的
	共同点是:1、不可重复声明 2、都是代码块作用域
    不同点是:const是常量,定义赋值后,不可改变
    var与let、const特性完全相反 */
console.log('typeof name:', typeof name);
console.log('typeof isCool:', typeof isCool);
console.log('typeof x:', typeof x); // typeof并不能显示原始的数据类型null,而是显示Object
console.log('typeof y:', typeof y);
console.log('typeof z:', typeof z);
console.log('x:', x); 
console.log('y:', y); 
console.log('z:', z); 
console.log('z[0]:', z[0]);
console.log('zzzzz', z['1']);
z = [6,7,'8'];
console.log('z:', z);

//字符串 String-----------------------------------------------------------------------------------------------
console.log('----------------String------------------')
console.log('My name is ' + name,' and I am ' + age);
console.log(`My name is ${name} and I am ${age}`);
console.log('name.length:', name.length); // 属性没有括号,方法才有括号
let name_m = 'hello world';
console.log('name_m.toLocaleUpperCase():', name_m.toLocaleUpperCase()); // 转换为大写,方法需要括号
console.log('name_m.substring(0,5).toLocaleUpperCase():', name_m.substring(0,5).toLocaleUpperCase());//注意不包含第五个
const name_s = 'hello world';
console.log("name_s.split(' '):", name_s.split(' '));

//数组 Arrays -----------------------------------------------------------------------------------------------
console.log('----------------Arrays------------------')
const f = ['apples', 'oranges', 'pears'];
console.log('f[1]:', f[1]);
f[3] = 'grapes'; 		// const 定义的数组可以添加元素!坑爹!
f.push('egg');   		// 在最尾部添加
f.unshift('ihave');     // 在最头部添加,注意不能f='grapes'或f=['grapes']
console.log('f:', f);
f.pop();    		    // 去掉最尾一个
console.log('f:', f);
console.log('Array.isArray(f):', Array.isArray(f))
console.log("f.indexOf('grapes'):", f.indexOf('grapes'))
console.log("f.indexOf('egg'):", f.indexOf('egg')) // 值是-1,有点意思

//对象类型-----------------------------------------------------------------------------------------------
//在编程中,对象是现实生活中的模型的一种代码结构————官方原话
console.log('----------------Object------------------')
const person = 
{
    firstName : 'John',
    lastName  : 'Doe',
    age       : 30,
    hobbies   : ['music', 'movies', 'sports'],
    address   : 
    {
        street: '50 main st',
        city  : 'Boston',
        state : 'MA'
    }
}	// 函数声明无需分号,类也是如此,其它地方都需要分号,注意!
console.log('person:', person);
console.log("person['firstName']:", person['firstName'])
console.log('person.hobbies[0]:', person.hobbies[0]);
console.log('person.address.city:', person.address.city);
// const { firstName, lastName, address:{ city }} = person;
const 
{
    firstName, 
    lastName, 
    address:
        { city }
} = person;	// 这样写是抓出person里面的某属性
console.log('firstName:', firstName);
console.log('city:', city)
person.email = 'john@gmail.com';
console.log('person.email:', person.email)
const todos = 
[
    {
        id          : 1,
        text        : 'Take out trash',
        isCompleted : true
    },
    {
        id          : 2,
        text        : 'Meeting with boss',
        isCompleted : true
    },
    {
        id          : 3,
        text        : 'Dentist appt',
        isCompleted : false
    },
];
console.log('todos:', todos);
console.log('todos[1].id:', todos[1].id);
const todoJSON = JSON.stringify(todos);//转换JSON格式
console.log(todoJSON)

判断

C
#include <stdio.h>

if ( <判断条件> ) {
    <执行语句>;
} else if (<判断条件>) {
    <执行语句>;
} else {
    <执行语句>;
}
Python
if <判断条件><执行语句>
elif <判断条件><执行语句>
else:
    <执行语句>
Java
public class Test {
 
   public static void main(String args[]){
        if ( <判断条件> ) {
            <执行语句>;
        } else if (<判断条件>) {
            <执行语句>;
        } else {
            <执行语句>;
        }
   }
}
js
// if语句-------------------------------------------
let x = 10;
if(x == 10)
{
    console.log('x is 10');
}

if(x == '10') // ==不管类型,只管值
{
    console.log('x is 10');
}

if(x === '10') // ===需要判断类型与值都一样才行
{
    console.log('x is 10');
}
//if    else if    esle--------------------------------------------------
x = 20;
if(x === 10) 
{
    console.log('x is 10');
}else if(x > 10)
{
    console.log('x is greater than 10');
}else
{
    console.log('x is less than 10')
}

循环

C
#include <stdio.h>

// 循环1
while (<循环条件>){
    <循环体语句>	;
}

// 循环2
do {
    <循环体语句>;
}while(<循环条件>)// 循环3
for (int i=0; i<5; i++){
	<循环体语句>;
}

//switch-case 遇到break停止
switch (控制表达式) {
case 常量1:
	语句;
case 常量2:
	语句;
	break;
case 常量3:
	语句;
...
default:
	语句;
}

// 终止循环或 switch 语句,程序流将继续执行紧接着循环或 switch 的下一条语句。

// 	告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。
Python
# 循环1
while True:
    print("Hello, Python")
    
# 循环2
for <variable> in <sequence>:
    <statements>
else:
    <statements>
# eg:    
for i in range(10):
# for i in ['a', 'b', 'c']:
    print(i)
    
# 另外,在 Python 中没有 do..while 循环。

# break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。

# continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
Java
// 循环1
while (<循环条件>){
    <循环体语句>	;
}

// 循环2
do {
    <循环体语句>;
}while(<循环条件>)// 循环3
for (int i=0; i<5; i++){
	<循环体语句>;
}

// 循环4:增强for循环
for(声明语句 : 表达式)
{
   <循环体语句>;
}
// eg:
public class Test {
   public static void main(String args[]){
      int [] numbers = {10, 20, 30, 40, 50};
 
      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] names ={"James", "Larry", "Tom", "Lacy"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}

//switch-case 遇到break停止
switch (控制表达式) {
case 常量1:
	语句;
case 常量2:
	语句;
	break;
case 常量3:
	语句;
...
default:
	语句;
}

// 终止循环或 switch 语句,程序流将继续执行紧接着循环或 switch 的下一条语句。

// 	告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。
js
// For语句-------------------------------------------
for(let i=0; i<=6; i++)
{
    console.log(`For Loop Number:${i}`);
}

// while语句-------------------------------------------
let i = 0;
while(i<=6)
{
    console.log(`While Loop Number:${i}`);
    i++;
}

// For应用---------------------------------------------
const todos = 
[
    {
        id          : 1,
        text        : 'Take out trash',
        isCompleted : true
    },
    {
        id          : 2,
        text        : 'Meeting with boss',
        isCompleted : true
    },
    {
        id          : 3,
        text        : 'Dentist appt',
        isCompleted : false
    },
];
for(let i=0; i<todos.length; i++)
{
    console.log('todos[i].text:', todos[i].text);
}
for(let t of todos)
{
    console.log('t.id:',t.id);
}
// forEach, map, filter--------------------------------------------
// forEach
todos.forEach   //也可以写成箭头函数
(
    function(t) // 这是回调函数
    {
        console.log('t.text:', t.text);
    }
);
// map
const t = todos.map   //map返回一个数组
(
    function(t)
    {
        // console.log('t.text:', t.text);
        return t.id === 1;
        // return t.id;
    }
);
console.log('t:', t);
// filter 过滤器
const tCompleted = todos.filter  //Completed 完整的
(
    function(t)
    {
        return t.isCompleted === true; // === 相当于python的 ==
    }
);
console.log('tCompleted:', tCompleted)
// map和filter的区别:前者是返回数组,后者是返回符合条件的数组

const tttCompleted = todos.filter   
(
    function(t)
    {
        return t.isCompleted === true;
    }
).map(function(t){return t.text;})
console.log('tttCompleted:', tttCompleted)


// switch语句-------------------------------------------
const color = 'green';

switch (color) 
{
    case 'red':
        console.log('color is red');
        break;
    case 'blue':
        console.log('color is blue');
        break;
    default:
        console.log('color is NOT red or blue');
        break;
}

逻辑、三元

js
// 逻辑运算演示---------------------------------------------------
// false 是 undefined, 0, "", null, false 
// true  是 除了上面的,都是true

// ----------- || 或    演示 -----------
const xx = 11;
if(xx<6 || xx>10) // ||某一个是true,结果为true
{
    console.log('逻辑‘或’:成立')
}else
{ console.log('逻辑‘或’:不成立') }


// ----------- && 与    演示 -----------
const yy = 11;
if(yy>1 && yy<10) // &&需要两个条件都是true,结果才是true
{
    console.log('逻辑‘与’:成立')
}else
{ console.log('逻辑‘与’:不成立') }


// 三元操作符 --------------
const xxx = 9;
const color = xxx > 10 ? 'red' : 'blue'; 
//如果问号后面条件为真,设置color为red,冒号代表else
console.log('xxx color :', color)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值