search
HomeBackend DevelopmentPython Tutorial在类Unix系统上开始Python3编程入门

假设有个python脚本script.py,不管哪种Unix平台,都可以在命令行上通过解释器执行:

$ python script.py

Unix平台还可以在不明确指定python解释器的情况下,自动执行python解释器,这需要在python脚本的第一行添加如下shell魔术字符串:

#!/usr/bin/python

在#!之后写上python解释器的完整路径,通常在/usr/bin或/usr/local/bin目录下。还有一种方法是使用env这个命令,位于/bin或/usr/bin中,它会帮你在系统搜索路径中找到python解释器,python脚本的第一行就可以修改如下:

#!/usr/bin/env python

这样,执行python脚本时,就不必显式地调用python解释器了,只需要键入脚本的文件名即可:

$ script.py

在 Python 3 中接触的第一个很大的差异就是缩进是作为语法的一部分,这和C++等其他语言确实很不一样,所以要小心咯
缩进要使用4个空格(这不是必须的,但你最好这么做),缩进表示一个代码块的开始,非缩进表示一个代码的结束。没有明确的大括号、中括号、或者关键字。这意味着空白很重要,而且必须要是一致的。第一个没有缩进的行标记了代码块,意思是指函数,if 语句、 for 循环、 while 循环等等的结束。
不过这样的规定也使得 Python 程序写出来会更加美观,便于阅读,吐槽是没有用的,接受吧...o(╯□╰)o
Python 思想:
“一切都是对象!”
输入很简单

x = input("Please input x:") 
Please input x: 

在代码最后加上

input("Press Enter") 

就可以让程序运行完后停一下

输出的 print 函数总结:
1. 字符串和数值类型
可以直接输出

>>> print(1) 
1 
>>> print("Hello World") 
Hello World 

 

2.变量
无论什么类型,数值,布尔,列表,字典...都可以直接输出

>>> x = 12 
>>> print(x) 
12 
>>> s = 'Hello' 
>>> print(s) 
Hello 
>>> L = [1,2,'a'] 
>>> print(L) 
[1, 2, 'a'] 
>>> t = (1,2,'a') 
>>> print(t) 
(1, 2, 'a') 
>>> d = {'a':1, 'b':2} 
>>> print(d) 
{'a': 1, 'b': 2} 

3.格式化输出
类似于C中的 printf

>>> s 
'Hello' 
>>> x = len(s) 
>>> print("The length of %s is %d" % (s,x)) 
The length of Hello is 5 

看看《Python基础编程》中对格式化输出的总结:
(1). %字符:标记转换说明符的开始

(2). 转换标志:-表示左对齐;+表示在转换值之前要加上正负号;“”(空白字符)表示正数之前保留空格;0表示转换值若位数不够则用0填充

(3). 最小字段宽度:转换后的字符串至少应该具有该值指定的宽度。如果是*,则宽度会从值元组中读出。

(4). 点(.)后跟精度值:如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度。如果是*,那么精度将从元组中读出

(5).字符串格式化转换类型

转换类型          含义
d,i                 带符号的十进制整数
o                   不带符号的八进制
u                   不带符号的十进制
x                    不带符号的十六进制(小写)
X                   不带符号的十六进制(大写)
e                   科学计数法表示的浮点数(小写)
E                   科学计数法表示的浮点数(大写)
f,F                 十进制浮点数
g                   如果指数大于-4或者小于精度值则和e相同,其他情况和f相同
G                  如果指数大于-4或者小于精度值则和E相同,其他情况和F相同
C                  单字符(接受整数或者单字符字符串)
r                    字符串(使用repr转换任意python对象)
s                   字符串(使用str转换任意python对象)

>>> pi = 3.141592653 
>>> print('%10.3f' % pi) #字段宽10,精度3 
  3.142 
>>> print("pi = %.*f" % (3,pi)) #用*从后面的元组中读取字段宽度或精度 
pi = 3.142 
>>> print('%010.3f' % pi) #用0填充空白 
000003.142 
>>> print('%-10.3f' % pi) #左对齐 
3.142  
>>> print('%+f' % pi) #显示正负号 
+3.141593 


4.如何让 print 不换行
在Python中总是默认换行的

>>> for x in range(0,10): 
 print(x) 



0 
1 
2 
3 
4 
5 
6 
7 
8 
9 

如果想要不换行,之前的 2.x 版本可以这样 print x, 在末尾加上 ,
但在 3.x 中这样不起任何作用
要想换行你应该写成 print(x,end = '' )
>>> for x in range(0,10): 
 print (x,end = '') 



0123456789 


拼接字符串:
>>> "Hello""World" 
'HelloWorld' 
>>> x = "Hello" 
>>> y = "world" 
>>> xy 
Traceback (most recent call last): 
 File "<pyshell#10>", line 1, in <module> 
 xy 
NameError: name 'xy' is not defined 
>>> x+y 
'Helloworld' 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor