首页 > 其他分享 >CS50P: 2. Loops

CS50P: 2. Loops

时间:2024-07-11 09:43:25浏览次数:15  
标签:Gryffindor CS50P students list print student Loops Hermoine

control + C 终止循环

while循环

#meow 3 times
i = 0
while i < 3:
    print("meow")
    i += 1		#python中没有i++

for循环

for i in [0, 1, 2]:
    print("meow")

i 初始为 1,依次取 2、3

in 可以让 i 按序取遍 list 中的元素,其中元素可以是 int, dict, str, etc.

for _ in range(3):	
  	print("meow")

range(x) 返回 [0, 1, ..., x-1]

_ 是Pythonic的用法,因为 i 只用来计数,之后不会用到

*

print("meow\n" * 3, end = '')

continue & break

while True:    
    n = int(input("What's n? "))
    if n < 0:
        continue    #继续循环
    else:
        break

如果想让input符合预期,刻意用 while True

当然,还可以写为:

if n > 0:
  	break

list

a datatype

students = ["Hermoine", "Harry", "Ron"]
for student in students:
    print(student) 

这样可以不考虑list的长度

student会初始化为 Hermoine ,然后取 Harry ……

len

len() 返回列表的元素个数

for i in range(len(students)):
    print(students[i])

使用列表中的元素 students[i]

dict (dictionaries)

associate one value with another, keys(words) and values(definition)

定义变量

students = {
    "Hermoine": "Gryffindor", 
    "Harry": "Gryffindor", 
    "Ron": "Gryffindor",
    "Draco": "Slytherin",
}

what do I want to associate Hermoine with? Gryffindor.

keys on the left, values on the right(美观)

引用

想输出 Hermoine 的 house?

方法一

print(stu["Hermoine"])

name of the variable: stu

和 list 的数字下标不同,dict 使用 actual words as index,得到 value

方法二

for student in students:
    print(student)

这样会输出所有的 key

for student in students:
    print(student, students[student])

for student in students: 会使 student"Hermione""Draco"

如果 student 的名字是 key,那 students[student] 会去取 student 的 value

多个value

a list of dictionaries, a list of 4 students, each of the students is a dictionary

students = [
    {"name": "Hermoine", "house": "Gryffindor", "patronus": "Otter"},
    {"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
    {"name": "Ron", "house": "Gryffindor", "patronus": "Jack Russell terrier"},
    {"name": "Draco", "house": "Slytherin", "patronus": None}
]

引用多个value

for student in students:
    print(student["name"],student["house"], student["patronus"])

student 是 dict 型变量

None

python关键字,the absence of a value

标签:Gryffindor,CS50P,students,list,print,student,Loops,Hermoine
From: https://www.cnblogs.com/chasetsai/p/18295426

相关文章

  • CS50P: 1. Conditionals
    运算符python中有>=和<=,其余和C一样python支持90<=score<=100CPython||or&and布尔运算TrueorFalse选择语句ififx<y:print("xislessthany")ifx>y:print("xisgreaterthany")ifx==y:......
  • SystemVerilog -- 3.0 SystemVerilog Loops
    SystemVerilogLoopsWhatareloops?loop是一段不断执行的代码。条件语句通常包含在循环中,以便在条件变为真时终止。如果loop永远运行,那么模拟将无限期挂起。下表给出了SystemVerilog中不同类型的循环构造。\\foreverRunsthegivensetofstatementsforever......
  • Go 100 mistakes - #32: Ignoring the impact of using pointer elements in range lo
    Thissectionlooksataspecificmistakewhenusingarangeloopwithpointerelements.Ifwe’renotcautiousenough,itcanleadustoanissuewherewereferencethe wrongelements.Let’sexaminethisproblemandhowtofixit.Beforewebegin,let’scla......
  • Loops should be simplified with "LINQ" expressions
    Loopsshouldbesimplifiedwith"LINQ"expressionsWhyisthisanissue?Whenaloopisfiltering,selectingoraggregating,thosefunctionscanbehandledwithaclearer,moreconciseLINQexpressioninstead.Noncompliantcodeexamplevarresu......
  • Oracle反连接和外连接中NESTED LOOPS无法更改驱动表
     Oracle反连接和外连接中NESTEDLOOPS无法更改驱动表 先说反连接,现有SQL如下:selectt.*fromtwheret.colnotin(select/*+nl_aj*/tt.colfromttwherett.colisnotnull)andt.colisnotnull;Planhashvalue:1434981293------------------------------......
  • Loops in C++
    #include<iostream>usingnamespacestd;intmain(){intv[]={0,1,2,3,4};for(autox:v){cout<<x<<endl;}for(autoy:......
  • C++11 新特性之Range-based for loops
    声明:本文少量代码转载自AlexAllain的文章 ​​http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html​​很多语言都有Range-basedforloops这个功能,现在C++......
  • 【Swift 60秒】33 - Exiting multiple loops
    0x00LessonIfyouputaloopinsidealoopit’scalleda​​nested​​loop,andit’snotuncommontowanttobreakoutofboththeinnerloopandtheouter......
  • 【Swift 60秒】35 - Infinite loops
    0x00LessonIt’scommontouse​​while​​loopstomakeinfiniteloops:loopsthateitherhavenoendoronlyendwhenyou’reready.AllappsonyouriPhone......
  • loops/reduce/方法链 处理数组对比
    loops循环constfiles=['foo.txt','.bar','','baz.foo']letfilePaths=[]for(letfileoffiles){ constfileName=file.trim() if(fileName){ ......