Pathon1 - 基础1

时间:2025-05-03 12:04:31

一、 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 来执行

Pathon1 -  基础1

六、格式化输出

#格式化输出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: ...

注:   外层变量,可以被内层代码使用

          内层变量,不应被外层代码使用
Python 中强制缩进,,  IndentationError: unexpected indent   缩进错误

八、 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)