Python 循环语句:for...in 和 while

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

以下哪个循环结构用于迭代列表或元组中的每个元素?

  • `for...in` 循环 (correct)
  • `if...else` 循环
  • `do...while` 循环
  • `while` 循环

while 循环中,只要条件满足,循环就会无限期地继续执行。

False (B)

在 Python 中,哪个语句可以提前结束循环的当前迭代并继续执行下一次迭代?

continue

在循环中,________ 语句可以完全退出循环。

<p><code>break</code></p> Signup and view all the answers

将以下循环相关任务与相应的 Python 语句匹配:

<p>从循环中退出。 = <code>break</code> 跳过当前迭代。 = <code>continue</code> 迭代一系列数字。 = <code>range()</code></p> Signup and view all the answers

以下哪个选项不是 dict 的有效特征?

<p><code>dict</code> 保持插入 <code>key</code> 的顺序。 (B)</p> Signup and view all the answers

如果 key 不存在,则尝试访问 dict 中不存在的 key 将返回 None

<p>False (B)</p> Signup and view all the answers

在 Python 中,从 dict 中删除 key-value 对的适当方法是什么?

<p><code>pop(key)</code></p> Signup and view all the answers

list 不同,__________ 需要大量内存。

<p><code>dict</code></p> Signup and view all the answers

将以下 dict 方法与它们的描述匹配:

<p><code>get(key, default)</code> = 如果 <code>key</code> 不存在,则返回 <code>default</code>。 <code>pop(key)</code> = 删除 <code>key</code> 并返回相应的 <code>value</code>。 <code>key in dict</code> = 检查 <code>key</code> 是否存在于 <code>dict</code> 中。</p> Signup and view all the answers

set 数据结构用于以下哪个目的?

<p>存储唯一元素的集合。 (D)</p> Signup and view all the answers

set 允许重复元素。

<p>False (B)</p> Signup and view all the answers

用于将元素添加到 set 的方法是什么?

<p><code>add(element)</code></p> Signup and view all the answers

使用 __________ 方法从 set 中删除元素。

<p><code>remove(element)</code></p> Signup and view all the answers

将以下 set 操作与其用途相匹配:

<p><code>s1 &amp; s2</code> = 返回 <code>s1</code> 和 <code>s2</code> 中存在的公共元素。 <code>s1 | s2</code> = 返回包含来自 <code>s1</code> 和 <code>s2</code> 的所有唯一元素的新 <code>set</code>。</p> Signup and view all the answers

为什么可变对象不能用作 dictset 中的 key

<p>它们会更改对象的哈希值。 (C)</p> Signup and view all the answers

字符串是 Python 中的可变对象。

<p>False (B)</p> Signup and view all the answers

在字符串是不可变的上下文中,“不变性”是什么意思?

<p>创建后内容无法修改</p> Signup and view all the answers

对于不变的对象(如字符串),修改值的方法会返回 __________。

<p>一个新的对象</p> Signup and view all the answers

匹配不变性和可变性与它们的数据类型:

<p>不变性 = 字符串 可变性 = 列表</p> Signup and view all the answers

Flashcards

for...in 循环

Python 中的一种循环结构,用于迭代列表或元组中的每个元素。

while 循环

当条件满足时,不断重复执行循环体内的代码,直到条件不再满足时退出循环。

break

一个可以提前退出循环的语句。

continue

跳过当前循环的剩余部分,直接开始下一次循环。

Signup and view all the flashcards

dict (字典)

一种使用键-值对存储数据的数据结构,查找速度非常快。

Signup and view all the flashcards

KeyError

如果 key 不存在于字典中,会发生 KeyError 错误。

Signup and view all the flashcards

set (集合)

一种存储唯一键的集合,不允许重复元素。

Signup and view all the flashcards

可变与不可变对象

Python 中可变对象的内容可以被修改,而不可变对象则不能。

Signup and view all the flashcards

add(key)

将元素添加到 set 中。

Signup and view all the flashcards

remove(key)

从 set 中删除指定元素。

Signup and view all the flashcards

Study Notes

  • This section discusses loops in Python and how to use dictionaries (dict) and sets (set).

循环 (Loops)

  • Loops are used to perform repetitive calculations.
  • Python offers two types of loops: for...in and while.

for...in 循环

  • This loop iterates through each element in a list or tuple.
  • Example:
names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)
  • This code prints each name in the names list.

  • The loop assigns each element to the variable x, then executes the indented block.

  • To calculate the sum of integers from 1-10 the following code can be used:

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    sum = sum + x
print(sum)
  • The range() function generates a sequence of integers. list(range(5)) creates a list [0, 1, 2, 3, 4]. range(101) generates a sequence from 0-100.

while 循环

  • The while loop continues as long as a condition is met.

  • The loop exits when the condition is no longer true.

  • Example for sum of odd numbers less than 100:

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)
  • Inside the loop, n decrements until it becomes -1, at which point the while condition is no longer met, and the loop terminates.

break 语句

  • The break statement exits the loop prematurely.

  • Example:

n = 1
while n <= 100:
    if n > 10:
        break
    print(n)
    n = n + 1
print('END')
  • This code prints numbers 1-10 and then prints 'END'.

continue 语句

  • The continue statement skips the current iteration and proceeds to the next.

  • Example:

n = 0
while n < 10:
    n = n + 1
    if n % 2 == 0:
        continue
    print(n)
  • This code prints odd numbers less than 10.

循环小结

  • Loops automate repetitive tasks.
  • break exits a loop, while continue skips an iteration.
  • Use if statements with break and continue.
  • Avoid overuse of break and continue to keep code clear.

dict (Dictionaries)

  • Dictionaries store key-value pairs (key-value).
  • They offer fast lookups.
  • Example:
names = ['Michael', 'Bob', 'Tracy']
scores = [95, 75, 85]
  • In this case, to look up the grade of a student, one would need to search the names list and get the index, and then use the index to look up the grade in the scores list.

  • With dict, you create a table of "name"-"score" correspondences, and can look this up directly

  • Dictionary example:

d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael']) # Output: 95
  • The key is a name, and the value is the corresponding score.
  • Dictionaries are fast because they use lookups similar to a dictionary index.
  • Data can be put into a dict using:
d['Adam'] = 67
  • If a key is assigned multiple values, the last value overwrites previous values.
d['Jack'] = 90
d['Jack'] = 88
print(d['Jack']) # Output: 88
  • If a key does not exist, an error occurs. To avoid this:

    • Check if the key exists using in: 'Thomas' in d returns False.
    • Use get(): d.get('Thomas') returns None, and d.get('Thomas', -1) returns -1.
  • The pop(key) method removes a key-value pair: d.pop('Bob') removes Bob's entry.

  • Key features of dict:

    • Fast lookups and insertions.
    • Large memory usage due to wasted space.
  • Key features of list are the opposite of dict:

    • Lookups and insertions slow as elements increase.
    • Small memory footprint.
  • Use immutable objects as dictionary keys eg strings.

set

  • Similar to dict, a set is a collection of keys, without associated values.
  • Keys in a set do not repeat.
  • To create a set, provide a list as input:
s = set([1, 2, 3])
print(s) # Output: {1, 2, 3}
  • Duplicate elements are automatically filtered out.
s = set([1, 1, 2, 2, 3, 3])
print(s) # Output: {1, 2, 3}
  • add(key) adds elements to the set. Adding an element multiple times has no effect.

  • remove(key) removes elements from the set.

  • Sets can be used for mathematical operations like intersection and union.

s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
print(s1 & s2) # Intersection: {2, 3}
print(s1 | s2) # Union: {1, 2, 3, 4}
  • Sets can't hold mutable objects because they can't determine whether the two mutable objects are equal and can't ensure the 'no repeat element' condition.

不可变对象 (Immutable Objects)

  • str is immutable, while list is mutable.
  • For a mutable object, such as list, the internal content changes when you modify the list.
a = ['c', 'b', 'a']
a.sort()
print(a) # Output: ['a', 'b', 'c']
  • For immutable objects like str, operations don't change the object.
a = 'abc'
a.replace('a', 'A')
print(a) # Output: abc
  • The replace() method doesn't change the original string, but creates a new string.
  • The variable a still points to the original string 'abc'.
a = 'abc'
b = a.replace('a', 'A')
print(b) # Output: Abc
print(a) # Output: abc
  • When you call an attribute method you create a new object, which is why immutable objects stay immutable, even after method calls such as replace().

总结

  • Dictionaries are useful for key-value storage and immutable objects such as strings are chosen as keys, tuples also work in dictionaries and sets, but must use immutable objects.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

Use Quizgecko on...
Browser
Browser