从零开始的python基础教程

news2024/9/23 1:25:44

一、Getting Started

在这里插入图片描述
如果使用的是mac或linux系统,需要输入 python3
比如运行 python3 app.py

可以直接在终端的>>>符号后执行python代码

print("*" * 10)

1、实现

在相关终端当运行“python”为CPython,这是python的默认实现
Jython -java
IronPython -C#
PyPy -用python的一部分编写的;Subset of python

二、Primitive Types

python中区分大小写,具有不同含义

布尔值始终以大写开头(FALSE也不可以)

is_published = False

pep8规则

1、Strings

三引号用来格式化长字符串

message = """
Hi John,

This is Mosh

Blah blah blah
"""
print(message)

效果:


Hi John,

This is Mosh

Blah blah blah


变量[头下标:尾下标](后面那个是开区间)

course = "Python Programming"
print(len(course))
print(course[0])
print(course[-1])
print(course[0:3])
print(course[0:])
print(course[:3])
print(course[:])

效果:

18
P
g
Pyt
Python Programming
Pyt
Python Programming

2、Escape Sequences

course = 'Python "Programming'
print(course)
Python "Programming
course = "Python \"Programming"
print(course)
Python "Programming

\' \" \\ \n

3、Formatted Strings

first = "Mosh"
last = "Hamedani"
# full = first + " " + last
full = f"{first} {len(last)}"
print(full)
Mosh 8

也可以{2 + 2}

4、String Methods

python中所有东西都是对象

upper函数返回一个新的字符串,因此原先的字符串没有被改变

course = "Python Programming"
course_capital = course.upper()
print(course_capital)
print(course)
PYTHON PROGRAMMING
Python Programming

同上,lower()title()(将所有单词!的第一个字符大写)

course = "python programming"
print(course.title())
Python Programming

strip()将开头和结尾的所有空格去除,因此分别有lstrip()rstrip()
find("pro")返回pro的下标,注意python大小写敏感。如果找不到返回-1
replace("p", "j")所有p换成j
print("Pro" in course)返回的是布尔值,“True”;同理还有not in

5、Numbers

python中有三种numbers(第三种是complex number)

x = 1
x = 1.1
x = 1 + 2j # a + bi
print(10 / 3)
print(10 // 3)
print(10 ** 3)
3.3333333333333335
3
100

6、Working with Numbers

import math

print(round(2.9))
print(abs(-2.9))

print(math.ceil(2.2))

7、Type Conversion

用户输入的永远是字符串!

x = input("x: ")
print(type(x))
y = int(x) + 1
print(f"x: {x}, y: {y}")

# int(x)
# float(x)
# bool(x)
# str(x)
x: 2
<class 'str'>
x: 2, y: 3

在这里插入图片描述

8、Quiz

fruit = "Apple"
print(fruit[1:-1])
ppl

三、Control Flow

1、Comparison Operators

10 == "10" # False

因为这两个类型不同,而且在计算机内存中存放在不同地方

"bag" > "apple" # True
"bag" == "BAG" # False
ord("b") # 98
ord("B") # 66

2、Conditional Statements

temperature = 35
if temperature > 30:
    print("It's warm")
    print("Drink Water")
elif temperature > 20:
    print("It's nice")
else:
    print("It's cold")
print("Done")

3、Ternary Operator

age = 22
message = "Eligible" if age >= 18 else "Not eligible"

4、Logical Operators

and or not

5、Short-circuit Evaluation

in Python logical operators are short circuit

6、Chaining Comparison Operators

age = 22
if 18 <= age < 65:
    print("Eligible")

7、For Loops

for number in range(3):
    print("Attemp", number)
Attemp 0
Attemp 1
Attemp 2

可以看出print自动换行,range(x)是[0, x - 1]

for number in range(3):
    print("Attemp", number + 1, (number + 1) * ".")
for number in range(1, 4):
    print("Attemp", number, number * ".")
Attemp 1 .
Attemp 2 ..
Attemp 3 ...
for number in range(1, 10, 2):
    print("Attemp", number, number * ".")
Attemp 1 .
Attemp 3 ...
Attemp 5 .....
Attemp 7 .......
Attemp 9 .........

8、For…Else

Note: The else block will NOT be executed if the loop is stopped by a break statement.

successful = False
for number in range(3):
    print("Attemp")
    if successful:
        print("Successful")
        break
else:
    print("Attempted 3 times and failed")
Attemp
Attemp
Attemp
Attempted 3 times and failed

如果将上述的successful值设置为True:

Attemp
Successful

9、Iterables

print(type(5))
print(type(range(5)))
<class 'int'>
<class 'range'>
# Iterable
for x in "Python":
    print(x)

for x in [1, 2, 3, 4]:
    print(x)

10、While Loops

number = 100
while number > 0:
    print(number)
    number //= 2
100
50
25
12
6
3
1

四、Functions

1、Arguments

def greet(first_name, last_name):
    print(f"Hi {first_name} {last_name}")
    print("Welcome aboard")

greet("Mosh", "Hamedani")

2、Types of Functions

def greet(name):
    print(f"Hi {name}")


def get_greeting(name):
    return f"Hi {name}"


message = get_greeting("Mosh")
file = open("content.txt", "w")
file.write(message)

open()返回一个file对象
然后调用file的write方法

3、Default Arguments

def increment(number, by=1):
    return number + by


print(increment(2, 5))
7

4、*args

函数中数量可变的arguments

*产生的是元组

def multiply(*numbers):
    print(numbers)


multiply(2, 3, 4, 5)
(2, 3, 4, 5)
def multiply(*numbers):
    total = 1
    for number in numbers:
        total *= number
    return total


print(multiply(2, 3, 4, 5))

5、**args

**产生的是字典

def save_user(**user):
    print(user)
    print(user["id"])


save_user(id=1, name="John", age=22)
{'id': 1, 'name': 'John', 'age': 22}
1

6、Scope

message = "a"


def greet(name):
    global message
    message = "b"


greet("Mosh")
print(message)
b

it will realize that in this function we want to use the global message variable, so it will not define a local variable in this function

五、Data Structures

0、Python Collections (Arrays)

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

1、Lists

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets []

List items are ordered, changeable, and allow duplicate(items with the same value) values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

numbers = [1, 2, 3, 4, 5]
numbers[0] # returns the first item
numbers[1] # returns the second item
numbers[-1] # returns the first item from the end
numbers[-2] # returns the second item from the end


print(len(numbers))


numbers.append(6) # adds 6 to the end
numbers.insert(0, 6) # adds 6 at index position of 0
numbers.remove(6) # removes 6
numbers.pop() # removes the last item
numbers.clear() # removes all the items
numbers.index(8) # returns the index of first occurrence of 8
numbers.sort() # sorts the list
numbers.reverse() # reverses the list
numbers.copy() # returns a copy of the list 

List items can be of any data type:
String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

list1 = ["abc", 34, True, 40, "male"]
mylist = ["apple", "banana", "cherry"]
print(type(mylist)) # <class 'list'>

It is also possible to use the list() constructor when creating a new list.

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/176945.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

大数据--spark

什么是SparkApache Spark 的架构基础是弹性分布式数据集 (RDD)&#xff0c;这是一种只读的多组数据项&#xff0c;分布在机器集群上&#xff0c;以容错方式维护。[2] Dataframe API 作为 RDD 之上的抽象发布&#xff0c;随后是 Dataset API。在 Spark 1.x 中&#xff0c;RDD 是…

39-剑指 Offer 41. 数据流中的中位数

题目 如何得到一个数据流中的中位数&#xff1f;如果从数据流中读出奇数个数值&#xff0c;那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值&#xff0c;那么中位数就是所有数值排序之后中间两个数的平均值。 例如&#xff0c; [2,3,4] 的中位…

50个常用的 Numpy 函数详解

目录 一、创建数组 1、Array 2、Linspace 3、Arange 4、Uniform 5、Random.randint 6、Random.random 7、Logspace 8、zeroes 9、ones 10、full 11、Identity 二、数组操作 12、min 13、max 14、unique 15、mean 16、medain 17、digitize 18、reshape 19、…

详解1247:河中跳房子(二分经典例题)

1247&#xff1a;河中跳房子【题目描述】每年奶牛们都要举办各种特殊版本的跳房子比赛&#xff0c;包括在河里从一个岩石跳到另一个岩石。这项激动人心的活动在一条长长的笔直河道中进行&#xff0c;在起点和离起点L远 (1 ≤ L≤ 1,000,000,000) 的终点处均有一个岩石。在起点和…

《Unity Shader 入门精要》第6章 Unity 中的基础光照

第6章 Unity 中的基础光照 6.1 我们是如何看到这个世界的 通常来说我们要模拟真实的光照环境来生成一张图像&#xff0c;需要考虑3种物理现象&#xff1a; 首先&#xff0c;光线从光源&#xff08;light source&#xff09;中被发射出来然后&#xff0c;光线和场景中的一些物…

JavaScript while 循环

文章目录JavaScript while 循环while 循环do/while 循环比较 for 和 while笔记列表JavaScript while 循环 只要指定条件为 true&#xff0c;循环就可以一直执行代码块。 while 循环 while 循环会在指定条件为真时循环执行代码块。 语法 while (条件) {需要执行的代码 }本例中…

Redis内部的阻塞式操作以及应对方法

Redis之所以被广泛应用&#xff0c;很重要的一个原因就是它支持高性能访问&#xff0c;也正因为这样&#xff0c;我们必须要重视所有可能影响Redis性能的因素&#xff0c;不仅要知道具体的机制&#xff0c;尽可能避免异常的情况出现&#xff0c;还要提前准备好应对异常的方案。…

MySQL进阶篇之索引2

02、索引 前四节内容&#xff1a;https://blog.csdn.net/kuaixiao0217/article/details/128753999 2.5、SQL性能分析 2.5.1、查看执行频次 1、SQL执行频率 MySQL客户端连接成功后&#xff0c;通过show [session|global] status命令可以提供服务器状态信息。 通过如下指令…

Computer architecture Cyber security Quantum computing交友

如果您也是computer architecture方向的博士硕士&#xff0c;希望交个朋友&#xff0c;欢迎后台私信。 当然&#xff0c;如果您也是 Cyber SecurityQuantum ComputingHigh Performance Computing 方向的博士硕士&#xff0c;想要交流&#xff0c;也可以私信。

学习记录669@项目管理之项目合同管理

有效合同原则 有效合同应具备以下特点: (1)签订合同的当事人应当具有相应的民事权利能力和民事行为能力。 (2)意思表示真实。 (3)不违反法律或社会公共利益 与有效合同相对应&#xff0c;需要避免无效合同。无效合同通常需具备下列任一情形: (1)一方以欺诈、胁迫的手段订立合…

【模拟CMOS集成电路】电路失调与CMRR—— 随机失调与系统失调分析(1)

电路失调与CMRR—— 随机失调与系统失调分析&#xff08;1&#xff09;前言1.1失调1.2失调电路模型1.2.1随机失调电路模型&#xff08;1&#xff09;电阻失配&#xff08;2&#xff09;跨导失配&#xff08;3&#xff09;电流镜的随机失调1.2.2系统失调前言 本文主要内容是失调…

深入剖析JVM垃圾收集器

文章目录前言1、新生代垃圾收集器1.1、Serial1.2、ParNew1.3、Parallel Scavenge2、老年代垃圾收集器2.1、Serial Old2.2、Parallel Old2.3、CMS&#xff08;Concurrent Mark Sweep&#xff09;3、全堆垃圾收集器3.1、Garbage First&#xff08;G1&#xff09;前言 参考资料&am…

ConfigurationProperties将配置绑定到bean的过程分析

概述 ConfigurationProperties是一个大家常用的注解。有一些系统配置&#xff0c;经常放在yml中&#xff0c;然后通过spring注入到bean中。 一般这些配置都是通过在spring生命周期的某一个环节&#xff0c;将属性注入进去的。 ConfigurationProperties就是利用了org.springf…

AC500 基于 Profinet 通讯连接变频器

硬件连接 使用 PM583-ETH 作为 Profinet 通讯的主站&#xff0c;ACS800 变频器 RETA-02 作为 Profinet 通讯的从站 2 ABB 变频器设置 以安装有 RETA-02 总线适配器的 ACS800 变频器为例&#xff0c;参照下表进行参数设定。详 细内容请参考变频器手册和 RETA-02 用户手册。表中…

Python 超强命令行解析工具 argparse !

在工作中&#xff0c;我们经常需要从命令行当中解析出指定的参数&#xff0c;而 Python 也提供了相应的标准库来做这件事情&#xff0c;比如 sys, optparse, getopt, argparse。这里面功能最强大的莫过于 argparse&#xff0c;下面就来看看它用法。import argparse# 使用 argpa…

计算机视觉OpenCv学习系列:第七部分、图像操作-3

第七部分、图像操作-3第一节、图像统计信息1.像素值统计2.函数支持说明3.代码练习与测试第二节、图像直方图1.图像直方图定义2.直方图函数3.代码练习与测试第三节、图像直方图均衡化1.直方图均衡化2.直方图均衡化函数3.代码练习与测试学习参考第一节、图像统计信息 1.像素值统…

零基础学JavaWeb开发(二十一)之 spring框架(4)

3、AOP详解 3.1、Aop常用术语 1.连接点&#xff08;Join point&#xff09;: 连接点表示应用执行过程中能够插入切面的一个点&#xff0c;这个点可以是方法的调用、异常的抛出。在 Spring AOP 中&#xff0c;连接点总是方法的调用。类中的哪些方法可以被增强&#xff0c;这些…

详解动态规划01背包问题--JavaScript实现

对其他动态规划问题感兴趣的&#xff0c;也可以查看详解动态规划最少硬币找零问题--JavaScript实现详解动态规划最长公共子序列--JavaScript实现一开始在接触动态规划的时候&#xff0c;可能会云里雾里&#xff0c;似乎能理解思路&#xff0c;但是又无法准确地表述或者把代码写…

车辆占用应急车道识别抓拍系统 opencv

车辆占用应急车道识别抓拍系统通过opencvpython人工智能识别技术&#xff0c;对高速公路应急车道进行不间断实时监测&#xff0c;当监测到应急车道上有车辆违规占用时&#xff0c;立即告警提醒后台人员及时处理避。OpenCV的全称是Open Source Computer Vision Library&#xff…

【18】C语言 | 数组详解

目录 1、数组的格式 2、下列有什么区别 3、维数组的使用 4、*p 和 int* p arr 的含义 5、二维数组&#xff1a;打印一个二维数组 6、二维数组在数组中的存储 7、数组作为函数参数 8、数组名是数组首元素的地址 1、数组的格式 数组是一组相同类型元素的集合。 数组的创…