python 基础

本文通过一个简单的Python程序示例,介绍了如何使Python脚本能够直接执行,处理中文字符,使用注释,了解Python的变量声明限制,进行基本的输入输出操作,并展示了条件判断及循环的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 直接上代码

a@bogon:~/work/test$ cat hello.py

print("hello, world");

a@bogon:~/work/test$ python hello.py

hello, world

如果想要跟 shell 脚本一样可以./hello.py 运行

 

1 chmod a+x hello.py

diff --git a/hello.py b/hello.py

index b2c7db7..9219c4a 100755

--- a/hello.py

+++ b/hello.py

@@ -1,2 +1,4 @@

+#!/usr/bin/env python

 print("hello, world");

a@bogon:~/work/test$ ./hello.py

hello, world

 

支持中文

 


a@bogon:~/work/test$ cat hello.py

#!/usr/bin/env python

print("hello, world");

print("你好,中国")

 

直接编译,报错如下

 

a@bogon:~/work/test$ ./hello.py

  File "./hello.py", line 3

SyntaxError: Non-ASCII character '\xe4' in file ./hello.py on line 3, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

 

ASCII 码,不支持中文。需要有道Unicode UTF-8 (对Unicode编码的压缩和优化)

修改如下

#!/usr/bin/env python
# -*- coding: utf-8 -*-
print("hello, world");
print("你好,世界");

 
注释

单行注释  #

多行注释   """  备注是内容  """ 

 

模块

python 有很多模块

1 python 内部的

2 开源

3 程序员自己写的

 

 

pyc文件

pyc其实字节码

 

                    编译

         ------------------------>

代码                                     字节码        

        <-----------------------  

                    反编译

 

 

变量

 跟c语言类似

注意:以下关键字不能声明为变量

and  as  assert  break class continue  def del   elif else  except  exce  finally for from global if import in is 

lambda not or pass raise return try while with yield

 

 

输入

使用python 内部模块

name = raw_input("请输入你的名字:")

输入密码不可见

采用 外部模块

import getpass

pwd = getpass.getpass("请输入密码")

 

 

条件判断

if name == "haha" and pwd == "1" :

    print("欢迎 haha")

else:

    print("用户名或密码不对")

 

注意,if  else 后面的 “:” 号  还有缩进是4个空格

 

循环

    while 条件:

        循环体

break 退出当前循环

continue  退出当前循环,继续下一次循环

转载于:https://www.cnblogs.com/cjcai-blogs/p/9063509.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值