Python learning- Loops and Iteration Strings Reading Files
Python小白的学习之路 Day3
- 还有一个月要参加美赛了,进度所以会提一些,留时间去学其他的
- Loops and Iteration (Chapter 5)
- Strings (Chapter 6)
- Reading Files (Chapter 7)
Loops and Iteration (Chapter 5)
Repeated Steps
- Loops (repeated steps) have iteration variables that change each time through a loop. Often these iteration variables go through a sequence of numbers.
Example:
n = 5
while n > 0 :print(n)n = n – 1
print('Blastoff!')
print(n)
Breaking Out of a Loop
- The break statement ends the current loop and jumps to the statement immediately following the loop
while True:line = input('> ')if line == 'done' :breakprint(line)
print('Done!')
Finishing an Iteration with continue
- The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration
Indefinite Loops
- While loops are called “indefinite loops” because they keep going until a logical condition becomes False
Definite Loops
- Definite loops (for loops) have explicit iteration variables that change each time through a loop. These iteration variables move through the sequence or set.
Example:
for i in [5, 4, 3, 2, 1] :print(i)
print('Blastoff!')
Finding the Largest Value
largest_so_far = -1
print('Before', largest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] :if the_num > largest_so_far :largest_so_far = the_numprint(largest_so_far, the_num)print('After', largest_so_far)
Counting in a Loop
- To count how many times we execute a loop, we introduce a counter variable that starts at 0 and we add one to it each time through the loop.
Summing in a Loop
- To add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop.
Filtering in a Loop
- We use an if statement in the loop to catch / filter the values we are looking for.
print('Before')
for value in [9, 41, 12, 3, 74, 15] :if value > 20:print('Large number',value)
print('After')
Search Using a Boolean Variable
- If we just want to search and know if a value was found, we use a variable that starts at False and is set to True as soon as we find what we are looking for.
Finding the Smallest Value
- We still have a variable that is the smallest so far. The first time through the loop smallest is None, so we take the first value to be the smallest.
smallest = None
print('Before')
for value in [9, 41, 12, 3, 74, 15] :if smallest is None : smallest = valueelif value < smallest : smallest = valueprint(smallest, value)
print('After', smallest)
The is and is not Operators
- Similar to, but stronger than ==
- Match both type and value
- is not also is a logical operator
推荐在Boolean和None type时使用,integer,float等可能会出现问题
Strings (Chapter 6)
String Data Type
- A string is a sequence of characters
- A string literal uses quotes ‘Hello’ or “Hello”
- For strings, + means “concatenate”
Looking Inside Strings
- We can get at any single character in a string using an index specified in square brackets
- The index value must be an integer and starts at zero
Strings are immutable
>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment
- The reason for the error is that strings are immutable, which means you can’t change an existing string.
Strings Have Length
- The built-in function len gives us the length of a string
>>> fruit = 'banana'
>>> print(len(fruit))
6
Looping and Counting
word = 'banana'
count = 0
for letter in word :if letter == 'a' : count = count + 1
print(count)
Slicing Strings
- We can also look at any continuous section of a string using a colon operator
- The second number is one beyond the end of the slice - “up to but not including”
- If the second number is beyond the end of the string, it stops at the end
- If we leave off the first number or the last number of the slice, it is assumed to be the beginning or end of the string respectively
>>> s = 'Monty Python'
>>> print(s[0:4])
Mont
>>> print(s[6:7])
P
>>> print(s[6:20])
Python
>>> print(s[:2])
Mo
>>> print(s[8:])
thon
>>> print(s[:])
Monty Python
Using in as a Logical Operator
- The in keyword can also be used to check to see if one string is “in” another string
- The in expression is a logical expression that returns True or False and can be used in an if statement
>>> fruit = 'banana'
>>> 'n' in fruit
True
>>> if 'a' in fruit :
... print('Found it!')
Found it!
String Library
- Python has a number of string functions which are in the string library
- These functions are already built into every string - we invoke them by appending the function to the string variable
- These functions do not modify the original string, instead they return a new string that has been altered
Searching a String
- find() finds the first occurrence of the substring
- If the substring is not found, find() returns -1
- Often when we are searching for a string using find() we first convert the string to lower case so we can search a string regardless of case
- find(a,b) a is the target string and b is the start index number
>>> fruit = 'banana'
>>> pos = fruit.find('na')
>>> print(pos)
2
>>> aa = fruit.find('z')
>>> print(aa)
-1
Search and Replace
- The replace() function is like a “search and replace” operation in a word processor
- It replaces all occurrences of the search string with the replacement string
>>> greet = 'Hello Bob'
>>> nstr = greet.replace('o','X')
>>> print(nstr)
HellX BXb
Stripping Whitespace
- lstrip() and rstrip() remove whitespace at the left or right
- strip() removes both beginning and ending whitespace
Prefixes
>>> line = 'Please have a nice day'
>>> line.startswith('Please')
True
>>> line.startswith('p')
False
Parsing and Extracting
>>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
>>> atpos = data.find('@')
>>> print(atpos)
21
>>> sppos = data.find(' ',atpos)
>>> print(sppos)
31
>>> host = data[atpos+1 : sppos]
>>> print(host)
uct.ac.za
Reading Files (Chapter 7)
File Processing
- A text file can be thought of as a sequence of lines
- A text file has newlines at the end of each line (talk about later)
Opening a File
- handle = open(filename, mode)
- returns a handle use to manipulate the file
- filename is a string
- mode is optional and should be ‘r’ if we are planning to read the file and ‘w’ if we are going to write to the file
handle = open('mbox.txt', 'r')
Meaning of handle: Handle is a thing allow you to get the file instead of file itself or the data in the file. Just like a wrapper.
The handle is a connection to the file’s data
The newline Character
- We use a special character called the “newline” to indicate when a line ends
- We represent it as \n in strings
- Newline is still one character - not two
>>> stuff = 'X\nY'
>>> print(stuff)
X
Y
File Handle as a Sequence
- We can use the for statement to iterate through a sequence
- Remember - a sequence is an ordered set
xfile = open('mbox.txt')
for cheese in xfile:print(cheese)
Reading the Whole File
-We can read the whole file (newlines and all) into a single string
>>> fhand = open('mbox-short.txt')
>>> inp = fhand.read()
>>> print(len(inp))
94626
>>> print(inp[:20])
From stephen.marquar
Searching Through a File (fixed)
- We can put an if statement in our for loop to only print lines that meet some criteria
- We can strip the whitespace from the right-hand side of the string using rstrip() from the string library
- The newline is considered “white space” and is stripped
fhand = open('mbox-short.txt')
for line in fhand:line = line.rstrip()if line.startswith('From:') :print(line)
Skipping with continue
Do the same things with continue
fhand = open('mbox-short.txt')
for line in fhand:line = line.rstrip()if not line.startswith('From:') :continueprint(line)
Using in to Select Lines
fhand = open('mbox-short.txt')
for line in fhand:line = line.rstrip()if not '@uct.ac.za' in line : continueprint(line)
Dealing with bad files
fname = input('Enter the file name: ')try:fhand = open(fname)except:print('File cannot be opened:', fname)quit()count = 0for line in fhand:if line.startswith('Subject:') :count = count + 1print('There were', count, 'subject lines in', fname)
三章学完脑子有点乱…
Python learning- Loops and Iteration Strings Reading Files相关推荐
- python OSError: [Errno 24] Too many open files | HTTPConnectionPool(host=‘‘, port=80): Max retries e
对于问题:python OSError: [Errno 24] Too many open files 原因:超出了进程同一时间最多可开启的文件数. 解决方案P: 使用ulimit -n查看进程同一时 ...
- Python Learning Notes - 2
Python Learning Notes - 2 主体感想 我们要想表达出一个事件(event),或一系列相联系的事件(events series that construct a system w ...
- Python爬虫之string、strings、stripped_strings、get_text和text用法区别
Python爬虫获取html中的文本方法多种多样,这里主要介绍一下string.strings.stripped_strings和get_text用法 string:用来获取目标路径下第一个非标签字符 ...
- A Survey of Zero-Shot Learning: Settings, Methods, and Applications [reading notes]
原文链接:https://joselynzhao.top/2019/04/15/A-Survey-of-Zero-Shot-Learning_-Settings,-Methods,-and-Appli ...
- the day of python learning(考试解释)
一,基础题. 1. 简述变量命名规范 #1.必须是字母,数字,下划线任意组合,不可以单数字#2.不可以是中文或拼音#3.命名得有可理解性#4.关键字不可以作为命名 2. 字节和位的关系 #一字节等于八 ...
- My python learning
2.17 面向对象编程 1.学习了面向对象编程中的一些基础函数 1.1__init__: init是实例创建后被调用的,用以设置对象属性的初始值.依据需求看是否需要这个函数.init函数可对类进行初始 ...
- python learning day1
输入输出 输入 a=input('提示内容') a的数据类型是字符 数据类型转换 int(a) 按回车前的都输入 输出 print()各参数说明: print([obj1,obj2,....][,se ...
- Python Learning Day8
bp4解析库 pip3 install beautifulsoup4 # 安装bs4 pip3 install lxml # 下载lxml解析器 html_doc = ""&quo ...
- Python Turtle 初学者指南
了解 Python turtle库 turtle是一个预装的 Python 库,它使用户能够通过为他们提供虚拟画布来创建图片和形状.您用于绘图的屏幕笔称为乌龟,这就是库的名称.简而言之,Pythont ...
最新文章
- http://www.cnblogs.com/amboyna/archive/2008/03/08/1096024.html
- 卡迪夫大数据专业排名_2020年卡迪夫大学卫报排名前10热门专业
- linux 处理 BOM头 ^M 方法
- 小程序开发(3)-之wx.request封装
- LeetCode算法入门- Longest Valid Parentheses -day12
- CAS客户端认证流程
- Veeam FAQ系列转载(一):备份
- 什么是SQL Server数据库镜像?
- 首富带你畅谈:蓝绿部署、滚动发布、灰度发布/金丝雀发布
- cannot be cast to android.support.v4.app.Fragment
- win10系统怎么改奇摩输入法_windows10如何更改输入法
- Java中this关键字的用法
- ORACLE有EXCEL中trend函数,借助Excel TREND 函数来解决线性插值的计算
- 用PS制作GIF动图
- 论文阅读《SHINE: Signed Heterogeneous Information Network Embedding for Sentiment Link Prediction》
- missing privilege separation directory /var/empty/sshd问题解决
- Gentoo 教程:基本系统安装
- 云计算基础:云计算运用越来越广泛,我们应该如何去学习云计算
- 低版本cad如何打开高版本图纸?不用升级软件也可以搞定
- 第6章 放大器的频率特性