Pathon1 - 基础1
一、 Hello world程序
print("Hello World!")
执行命令: python hello.py ,输出
执行 python hello.py 时,明确的指出 hello.py 脚本由 python 解释器来执行。
如果想要类似于执行shell脚本一样执行python脚本,例: ./hello.py ,那么就需要在 hello.py 文件的头部指定解释器,如下:
#!/usr/bin/env python print "hello,world"
如此一来,执行: ./hello.py 即可。
ps:执行前需给予 hello.py 执行权限,chmod 755 hello.py
附:其它语言的hello world:
#include<stdio.h>
int main(void)
{
printf("Hello World!!\n");
return ;
}
C
#include <iostream>
using namespace std; int main()
{
cout << "Hello World";
return ;
}
C++
public class HelloWorld {
public static void main(String []args) {
System.out.println("Hello World!");
}
}
Java
<?php
echo 'Hello World!';
?>
PHP
#!/usr/bin/ruby
# -*- coding: UTF-8 -*- puts "Hello World!";
Ruby
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Go
program Hello;
begin
writeln ('Hello, world!')
end.
Pascal
#!/bin/bash
echo 'Hello World!'
Bash
# -*- coding: UTF- -*-
print 'Hello World!'
Python
#!/usr/bin/python
print("Hello, World!");
Python3
二、变量
变量定义的规则:
- 变量名只能是 字母、数字或下划线的任意组合
- 变量名的第一个字符不能是数字
- 以下关键字不能声明为变量名
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
常量用大写表示
单词之间用下划线隔开,例:gf_of_tan :tan的女朋友
三、字符编码
python解释器在加载 .py 文件中的代码时,会对内容进行编码(默认ascill),如果是如下代码的话:
#!/usr/bin/env python print "你好,世界"
报错:ascii码无法表示中文
改正:应该显示的告诉python解释器,用什么编码来执行源代码,即:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print "你好,世界"
四、注释
单行注视:# 被注释内容
多行注释:""" 被注释内容 """
五、用户交互
python2中 raw_input = python3中的input
python2中不要用input ,它接受什么格式就是什么格式(直接打name是变量,不是字符串,字符串要写成”name“)
# -*- coding: utf-8 -*-
username = "请输入用户名:"
print("My name is ",name) #逗号代表连接字符串
# -*- coding: utf-8 -*-
import getpass
passwd = getpass.getpass("请输入密码:")
print("密码:", passwd)
注意:getpass 在pyCharm中不能用,会卡住;在ipython中也不行; 只能在命令行中cd到py文件,然后python interaction.py 来执行

六、格式化输出
#格式化输出name, age, job
name = input("name:")
age = input("age:")
job = input('job:')
info = '''------info of ''' + name + ''' ----
Name:''' + name + '''
Age:''' + age + '''
Job:''' + job
print(info)
法1:用+连接 不推荐
name = input("name:")
age = int(input("age:")) #强转int
job = input('job:')
info = '''
------info of %s----
Name:%s
Age:%d
Job:%s
''' %(name, name, age, job)
法2: %s %d 格式化输出
info = '''
------info of {_name}----
Name:{_name}
Age:{_age}
Job:{_job}
'''.format(
_name = name,
_age = age,
_job = job
)
法3: { } 推荐
info = '''
------info of {0}----
Name:{0}
Age:{1}
Job:{2}
'''.format(name,age,job)
法4:{0}{1}...参数多的时候不推荐
七、 表达式 if ... else
场景一、用户登陆验证
name = input('请输入用户名:')
pwd = getpass.getpass('请输入密码:')
if name == "tan" and pwd == "":
print("欢迎,tan!")
else:
print("用户名和密码错误")
if ... else: ...
场景二、猜年龄
my_age = 12
user_input = int(input("input your guess num:"))
if user_input == my_age:
print("Congratulations, you got it !")
elif user_input < my_age:
print("Oops,think bigger!")
else:
print("think smaller!")
if... elif... else: ...
注: 外层变量,可以被内层代码使用
八、 while循环
有一种循环叫做while死循环:
count = 0
while True:
print("count:", count)
count += 1; #count=count+1 没有count++
while猜年龄:
myage = 20
count = 0
while True:
if count == 3:
break
guess_age = int(input("guess age:"))
if(guess_age == myage):
print("yes, you got it. ")
break;
elif(guess_age < myage):
print("think bigger! ")
else:
print("think smaller! ")
count += 1
if count == 3:
print("you have tried too many times.. fuck off..")
while中加入if 和 累计次数
在上面代码基础上有两处优化: while count<3: ... else: ...
myage = 20
count = 0
while count < 3:
guess_age = int(input("guess age:"))
if (guess_age == myage):
print("yes, you got it. ")
break;
elif (guess_age < myage):
print("think bigger! ")
else:
print("think smaller! ")
count += 1
else:
print("you have tried too many times.. fuck off..")
# while 循环正常走完,不会执行else. ...非正常走完(遇到break),才会执行else
九、for循环
最简单的循环10次
for i in range(10):
print("loop:", i)
输出 loop:0 - loop: 9
for猜年龄
for i in range(3):
guess_age = int(input("guess age:"))
if (guess_age == myage):
print("yes, you got it. ")
break;
elif (guess_age < myage):
print("think bigger! ")
else:
print("think smaller! ")
count += 1
else: # while 循环正常走完,不会执行else. ...非正常走完(遇到break),才会执行else
print("you have tried too many times.. fuck off..")
for i in range(3):
while count < 3:
guess_age = int(input("guess age:"))
if (guess_age == myage):
print("yes, you got it. ")
break;
elif (guess_age < myage):
print("think bigger! ")
else:
print("think smaller! ")
count += 1
if(count == 3):
continue_flag = input("do you want to keep guessing? ")
if continue_flag != 'n':
count = 0
添加一个是否keep guessing
需求一:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳入下一次循环
for i in range(10):
if i<5:
continue #不往下走了,直接进入下一次loop
print("loop:", i )
输出 loop:5 - loop: 9
需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出
for i in range(10):
if i>5:
break #不往下走了,直接跳出整个loop
print("loop:", i )
输出 loop:0 - loop: 5
需求三:输出偶数(或奇数)隔一个输出一个
for i in range(0,10,2): #前两个参数是范围,第三个参数是步长
print("loop:", i)
for双循环:
for i in range(10):
print("---------", i)
for j in range(10):
print(j)
Pathon1 - 基础1的更多相关文章
- java基础集合经典训练题
第一题:要求产生10个随机的字符串,每一个字符串互相不重复,每一个字符串中组成的字符(a-zA-Z0-9)也不相同,每个字符串长度为10; 分析:*1.看到这个题目,或许你脑海中会想到很多方法,比如判 ...
- node-webkit 环境搭建与基础demo
首先去github上面下载(地址),具体更具自己的系统,我的是windows,这里只给出windows的做法 下载windows x64版本 下载之后解压,得到以下东西 为了方便,我们直接在这个目录中 ...
- js学习笔记:webpack基础入门(一)
之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...
- Golang, 以17个简短代码片段,切底弄懂 channel 基础
(原创出处为本博客:http://www.cnblogs.com/linguanh/) 前序: 因为打算自己搞个基于Golang的IM服务器,所以复习了下之前一直没怎么使用的协程.管道等高并发编程知识 ...
- [C#] C# 基础回顾 - 匿名方法
C# 基础回顾 - 匿名方法 目录 简介 匿名方法的参数使用范围 委托示例 简介 在 C# 2.0 之前的版本中,我们创建委托的唯一形式 -- 命名方法. 而 C# 2.0 -- 引进了匿名方法,在 ...
- HTTPS 互联网世界的安全基础
近一年公司在努力推进全站的 HTTPS 化,作为负责应用系统的我们,在配合这个趋势的过程中,顺便也就想去搞清楚 HTTP 后面的这个 S 到底是个什么含义?有什么作用?带来了哪些影响?毕竟以前也就只是 ...
- Swift与C#的基础语法比较
背景: 这两天不小心看了一下Swift的基础语法,感觉既然看了,还是写一下笔记,留个痕迹~ 总体而言,感觉Swift是一种前后端多种语言混合的产物~~~ 做为一名.NET阵营人士,少少多多总喜欢通过对 ...
- .NetCore MVC中的路由(1)路由配置基础
.NetCore MVC中的路由(1)路由配置基础 0x00 路由在MVC中起到的作用 前段时间一直忙于别的事情,终于搞定了继续学习.NetCore.这次学习的主题是MVC中的路由.路由是所有MVC框 ...
- .NET基础拾遗(5)多线程开发基础
Index : (1)类型语法.内存管理和垃圾回收基础 (2)面向对象的实现和异常的处理基础 (3)字符串.集合与流 (4)委托.事件.反射与特性 (5)多线程开发基础 (6)ADO.NET与数据库开 ...
随机推荐
- C# 一般处理程序下载文件
using System; using System.Collections; using System.Data; using System.Linq; using System.Web; usin ...
- Listbox的操作,数据源变化时要及时更新listbox要先把数据源置空,在给数据源绑定数据
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- 【洛谷P1052【NOIP2005提高T2】】过河
题目描述 在河上有一座独木桥,一只青蛙想沿着独木桥从河的一侧跳到另一侧.在桥上有一些石子,青蛙很讨厌踩在这些石子上.由于桥的长度和青蛙一次跳过的距离都是正整数,我们可以把独木桥上青蛙可能到达的点看成数 ...
- 第16月第31天 mongo
1. 94 brew install mongodb 95 cd ~ 96 cd Desktop/web/ 97 ls 98 mkdir mongo 99 cd mongo/ 100 ...
- 基于theano的降噪自动编码器(Denoising Autoencoders--DA)
1.自动编码器 自动编码器首先通过下面的映射,把输入 $x\in[0,1]^{d}$映射到一个隐层 $y\in[0,1]^{d^{'}}$(编码器): $y=s(Wx+b)$ 其中 $s$ 是非线性的 ...
- MISC混杂设备 struct miscdevice /misc_register()/misc_deregister()【转】
本文转自:http://blog.csdn.net/angle_birds/article/details/8330407 在Linux系统中,存在一类字符设备,他们共享一个主设备号(10),但此设备 ...
- 基于TLS的EAP 认证方法
TLS: transport level security , 安全传输层协议,用于在两个通信应用程序之间提供保密性和数据完整性.该协议由两层组成: TLS 记录协议(TLS Record)和 TLS ...
- Android:Animation
Android 之 Animation 关于动画的实现,Android提供了Animation,在Android SDK介绍了2种Animation模式:1. Tween Animation:通过对场 ...
- 淘淘商城 本地仓库配置和仓库jar包下载
SVN服务器的搭建请查看该文:<Win7 x64 svn 服务器搭建> 1:仓库包存放位置: 2:setting.xml 文件配置信息 <?xml version="1.0 ...
- hdu2838树状数组解逆序
离散化和排序后的序号问题搞得我实在是头痛 不过树状数组解逆序和偏序一类问题真的好用 更新:hdu的数据弱的真实,我交上去错的代价也对了.. 下面的代码是错的 /* 每个点的贡献度=权值*在这个点之前的 ...