Ten minutes of python introductory conditions and loop file operations

 Source code download

1.Conditions _

Python supports common logical conditions from mathematics:

  • equal:a == b
  • not equal to:a != b
  • Less than:a < b
  • Less than or equal to:a <= b
  • more than the:a > b
  • greater or equal to:a >= b

These conditions can be used in a variety of ways, the most common being "if statements" and loops.

if statement uses  if keywords
x = 'abcd'
if x == 'abc' :
    print('x 的值和abc 相等')
else:
    print('x和 abc不相等')

#输出:x和 abc不相等
indentation

Python relies on indentation, using spaces to define ranges in code. Other programming languages ​​often use curly braces for this purpose.

#缩进
#没有缩进的 If 语句(会引发错误):
a = 66
b = 200
if b > a:
print("b is greater than a") # 会报错
Elif

elif The keyword is Python's way of saying "if the previous condition was not true, then try this condition."

#elif 关键字是 python 对“如果之前的条件不正确,那么试试这个条件”的表达方式。
a = 66
b = 66
if b > a:
  print("b 大于 a")
elif a == b:
  print("b 等于 a")

Else

The else keyword captures anything not captured by the previous condition.

#else 关键字捕获未被之前的条件捕获的任何内容
a = 200
b = 66
if b > a:
  print("b大于a")
elif a == b:
  print("a 等于 b")
else:
  print("b 小于 a")
 AbbreviationIf...Else

If you only have two statements to execute, one for if and one for else, you can put them all on the same line:


#如果只有两条语句要执行,一条用于 if,另一条用于 else,则可以将它们全部放在同一行:
a = 200
b = 66
print("A") if a > b else print("B")
#输出:A
And

and A keyword is a logical operator used to combine conditional statements:

#and 关键字是一个逻辑运算符,用于组合条件语句:
a = 200
b = 66
c = 500
if a > b and c > a:
  print("a大于b与c大于a")
pass statement

The if statement cannot be empty, but if for some reason you write an empty if statement, use a pass statement to avoid errors.

#if 语句不能为空,但是如果您处于某种原因写了无内容的 if 语句,请使用 pass 语句来避免错误。
a = 66
b = 200

if b > a:
  pass

2. Loop

while loop

If we use  while a loop, we can execute a set of statements as long as the condition is true.

#如果使用 while 循环,只要条件为真,我们就可以执行一组语句。
i = 1
#只要 i 小于 7,打印 i:
while i < 7:
  print(i)
  i += 1
break statement

If we use  break a statement, we can stop the loop even if the while condition is true:

#如果使用 break 语句,即使 while 条件为真,我们也可以停止循环:
i = 1
while i < 7:
  print(i)
  #在 i 等于 3 时退出循环:
  if i == 3:
    break
  i += 1
 continue statement

If using  continue statement we can stop the current iteration and continue with the next one:

#如果使用 continue 语句,我们可以停止当前的迭代,并继续下一个:
i = 0
while i < 7:
  i += 1
  #如果 i 等于 3,则继续下一个迭代:
  if i == 3:
    continue
  print(i)
else statement

By using the else statement, we can run the block of code once when the condition no longer holds:

#通过使用 else 语句,当条件不再成立时,我们可以运行一次代码块:
i = 1
while i < 6:
  print(i)
  i += 1
#条件为假时打印一条消息:
else:
  print("i 大于 6")

 For loop

for Loops are used to iterate over a sequence (i.e. list, tuple, dictionary, set or string).

This is less similar to keywords in other programming languages  for ​​and more like iterator methods in other object-oriented programming languages.

#打印 fruits 列表中的每种水果:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
Loop through string 

Even strings are iterable objects that contain a sequence of characters:


#循环遍历字符串
for x in "banana":
  print(x)
break statement

By using  break the statement we can stop the loop before it loops through all items:

#通过使用 break 语句,我们可以在循环遍历所有项目之前停止循环:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break
range() function

To loop a set of code a specified number of times, we can use  range() a function,

range() The function returns a sequence of numbers, starting at 0 by default, incrementing by 1 (by default), and ending with the specified number.

#range() 函数返回一个数字序列,默认情况下从 0 开始,并递增 1(默认地),并以指定的数字结束
for x in range(10):
  print(x)
 Else in For loop

Keywords in a for loop  else specify the block of code to be executed at the end of the loop: 


#for 循环中的 else 关键字指定循环结束时要执行的代码块
for x in range(10):
  print(x)
else:
  print("结束")

2. Files, input and output, exceptions

file reading

The key to working with files in Python are  open() functions.

open() The function takes two parameters: filename and mode.

There are four different ways (modes) of opening files:

  • "r" - Read - Default value. Open the file for reading, and report an error if the file does not exist.
  • "a" - Append - Opens the file for appending, or creates the file if it does not exist.
  • "w" - Write - Opens the file for writing, or creates the file if it does not exist.
  • "x" - Create - Creates the specified file, returning an error if the file exists.

Additionally, you can specify whether the file should be processed as binary or text mode.

  • "t" - text - Default value. Text mode.
  • "b" -binary - Binary mode (e.g. image).
file reading

Suppose we have the following files, located in the same folder as Python:

demo.txt

hello world!

To open a file, use the built-in  open() functions.

open() The function returns a file object, which has a  read() method for reading the contents of the file:

#文件读取
f = open("demo.txt", "r")
print(f.read())
#输出:hello world!
 Read Chinese:
#读取中文
f = open("chinese.txt", "r", encoding='utf-8')
print(f.read())
#输出:你好呀!
Read only part of the file 
#默认情况下,read() 方法返回整个文本,但您也可以指定要返回的字符数:
f = open("demo.txt", "r")
print(f.read(5))
#输出:hello
read line

You can use  readline() the method to return a row:

#您可以使用 readline() 方法返回一行:
f = open("demo.txt", "r")
print(f.readline())
#输出:hello world!
Iterate through the file line by line
#逐行遍历文件
f = open("demo.txt", "r")
for x in f:
  print(x)
close file
#关闭文件
f = open("demo.txt", "r")
print(f.readline())
f.close()

file writing

To write to an existing file, you must  open() add parameters to the function:

  • "a" -Append- will append to the end of the file
  • "w" - Write - will overwrite any existing content
append write
#文件追加
f = open("demo2.txt", "a")
f.write(" append dog!")
f.close()

# 追加后,打开并读取该文件:
f = open("demo2.txt", "r")
print(f.read())
#输出:hello world! xiaomingappend dog! append dog!
 Cover content
#覆盖
f = open("demo3.txt", "w")
f.write("I have deleted the content!")
f.close()

# 写入后,打开并读取该文件:
f = open("demo3.txt", "r")
print(f.read())
#输出:I have deleted the content!
Create new file

To create a new file in Python, use  open() the method with one of the following parameters:

  • "x" - create - will create a file and return an error if the file exists
  • "a" - Append - If the specified file does not exist, a file will be created
  • "w" - write - If the specified file does not exist, a file will be created

#创建名为 "myfile.txt" 的文件:
f = open("myfile.txt", "x")

 If it does not exist, create a new file

#如果不存在,则创建新文件:
f = open("myfile.txt", "w")

If this document is not detailed enough, you can refer to learn python in ten minutes_bilibili_bilibili​

Guess you like

Origin blog.csdn.net/kan_Feng/article/details/131898416