【CS50】Week 6 Python

主要内容:Python: Functions, Arguments, Return Values; Variables; Boolean Expressions, Conditionals; Loops. Modules, Packages.


Lecture

Functions

format

print(f"hello, {answer}!")

input

input的输入是str类型
强制转换:

x = int(input("x: "))

数据类型

range list tuple dict set

条件判断

NOTE: 中间是elif

if x < y:
	print("x is less than y")
elif x > y:
	print("x is greater than y")
else
	print("x is equal to y")

or 的用法

s = input("Do you agree? ").lower()
if s == "Y" or s == "y":
    print("Agreed")
elif s  == "N" or s == "n":
    print("Not agreed")

OOP 面向对象编程

数据可以有函数,内置功能
例子:

s = input("Do you agree? ").lower()

循环 loops

for循环:

for i in range(3):
	print("hello wolrd!")

取消i

for _ in range(3):
	print("hello world!")

while 循环

NOTE: 注意True是大写

while True:
	print("meow")

named parameters 命名参数

在Python中,named parameters(也称为关键字参数或命名参数)是函数参数的一种形式,允许在调用函数时使用参数名明确指定每个参数的值。这种方式可以提高代码的可读性,并且在函数有多个参数时,可以让你只设置需要的参数而不用关心它们的顺序。
例子:
使用end=“”取消换行

before = input("Before: ")
print("After:  ", end="")
for c in before:
    print(c.upper(), end="")
print()

在这里插入图片描述
改进:对整个str使用函数

before = input("Before: ")
after = before.upper()
print(f"After:  {after}")

更短:

before = input("Before: ")
print(f"After:  {before.upper()}")

meow

def meow():
	print("meow")
	
for i in range(3):
	meow()

若更改位置,则会出错

for i in range(3):
	meow()
	
	
def meow():
	print("meow")

改进:

def main():
	for i in range(3):
		meow()
	
	
def meow():
	print("meow")

缺少call,只定义,但没call
更正:

def main():
	for i in range(3):
		meow()
	
	
def meow():
	print("meow")

main()

增加参数

def main():
		meow(3)
	
	
def meow(n):
	for i in range(n):
		print("meow")

main()

在这里插入图片描述

truncation 截断

自动转换成浮点数

x = int(input("x: "))
y = int(input("y: "))

z = x / y
print(z)

在这里插入图片描述
输出格式

print(f"{z:.50f}")

在这里插入图片描述
NOTE:存在精度问题
NOTE: 不存在溢出

Exception

处理异常情况

def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Not a integer")


def main():
    x = get_int("x: ")
    y = get_int("y: ")

    print(x + y)


main()

或者使用pass

def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            pass

mairo

python 版本:

from cs50 import get_int

while True:
    n = get_int("Height: ")
    if n > 0:
        break

for i in range(n):
    print("#")

List

scores = [72, 73, 33]

average = sum(scores) / len(scores)
print(f"Average: {average}")

改进:

from cs50 import get_int

scores = []
for i in range(3):
    score = get_int("Score: ")
    scores.append(score)

average = sum(scores) / len(scores)
print(f"Average: {average}")

for-else
错误:

names = ["Cater", "David", "John"]

name = input("Name: ")

for n in names:
	if name == n:
		print("Found")
		break
	else:
		print("Not found")

正确:

names = ["Cater", "David", "John"]

name = input("Name: ")

for n in names:
	if name == n:
		print("Found")
		break
else:
	print("Not found")

if-else

names = ["Cater", "David", "John"]

name = input("Name: ")

if name in names:
		print("Found")
else:
	print("Not found")

dict

people = [
	{"name": "Carter", "number": "+1-617-495-1000"},
	{"name": "David", "number": "..."},
	...
]

name = input("Name: ")

for person in people:
	if person["name"] == name:
		number = person["number"]
		print(f"Found {number}")
		break
else:
	print("Not found")

改进:

people = [
	{"name": "Carter", "number": "+1-617-495-1000"},
	{"name": "David", "number": "..."},
	...
]

name = input("Name: ")

for person in people:
	if person["name"] == name:
		//  不用双引号
		print(f"Found {person['number'}")
		break
else:
	print("Not found")

继续改进dict:

people = {
	"Cater": "12323414",
	"David": "12345456",
	"John": "1861232",
}

name = input("Name: ")

if name in people:
	number = people[name]
	print(f"Found {number}")
else:
	print("Not found")

sys

from sys import argv

if len(argv) == 2:
    print(f"hello, {argv[1]}")
else:
    print(f"hello, world")
import sys

if len(sys.argv) != 2:
    print("Missing command_line argument")
    sys.exit(1)

print(f"Hello, {sys.argv[1]}")
sys.exit(0)

pip

使用pip

section

1 strip()函数

删除前后的空字符

2 lower() 函数 capitalize()

大小写变换

3

problem set

1 hello.py

def main():
    name = input("What is your name? ")
    print(f"hello, {name}")


if __name__ == "__main__":
    main()

2 mario.py

def get_height():
    while True:
        try:
            height = int(input("Height: "))
            if 1 <= height <= 8:
                break
        except ValueError:
            print("Not a number! ")
    return height


def main():
    height = get_height()
    for row in range(height):
        for i in range(height - row - 1, 0, -1):
            print(" ", end="")
        for i in range(row + 1):
            print("#", end="")
        print("  ", end="")
        for i in range(row + 1):
            print("#", end="")
        print()
        

if __name__ == "__main__":
    main()

3 Credit.py

import sys

def main():
    num = input("Number: ")  # 获取用户输入的信用卡号码
    length = len(num)  # 获取信用卡号码的长度

    # 检查信用卡号码的长度是否有效
    if length != 13 and length != 15 and length != 16:
        print("INVALID!")
        sys.exit()

    # 确定从哪一位开始进行双倍处理
    flag = length % 2 == 0

    checksum = 0  # 初始化校验和

    # 遍历信用卡号码的每一位
    for i in range(length):
        if flag:
            tmp = int(num[i]) * 2  # 双倍处理当前位
            
            # 如果双倍后的值大于等于10,则减去9
            if tmp >= 10:
                checksum += tmp - 9
            else:
                checksum += tmp
            
            flag = False  # 切换标志位
        else:
            checksum += int(num[i])  # 直接加上当前位的值
            flag = True  # 切换标志位
    
    check = int(num[0]) * 10 + int(num[1])  # 获取前两位数字

    # 根据校验和和前两位数字判断信用卡类型
    if checksum % 10 == 0:
        if check == 34 or check == 37:
            print("AMEX")
        elif 51 <= check <= 55:
            print("MASTERCARD")
        elif int(num[0]) == 4:
            print("VISA")
        else:
            print("INVALID")
    else:
        print("INVALID")

if __name__ == "__main__":
    main()

readability.py

# TODO
def main():
    text = input("Text: ")
    l = count_letters(text) * 100 / count_words(text)
    s = count_sentences(text) * 100 / count_words(text)
    grade = round(0.0588 * l - 0.296 * s - 15.8)

    if grade < 1:
        print("Before Grade 1")
    elif grade > 16:
        print("Grade 16+")
    else:
        print(f"Grade {grade}")


def count_letters(text):
    cnt = 0
    for i in range(len(text)):
        if text[i].isalnum():
            cnt += 1
    return cnt


def count_words(text):
    cnt = 0
    for i in range(len(text)):
        if text[i].isspace():
            cnt += 1
    return cnt + 1


def count_sentences(text):
    cnt = 0
    for i in range(len(text)):
        if text[i] == '.' or text[i] == '!' or text[i] == '?':
            cnt += 1
    return cnt


if __name__ == "__main__":
    main()

DNA

import csv
import sys


def main():

    # TODO: Check for command-line usage ��������в����������Ƿ���ȷ
    if len(sys.argv) !=3:
        sys.exit("Usage: python dna.py data.csv sequence.txt")

    # TODO: Read database file into a variable ��ȡ���ݿ��ļ�������
    with open(sys.argv[1], "r") as file:
        reader = csv.DictReader(file) # csv.DictReader ��ȡ CSV �ļ����������Ϊ�ֵ��б��������ڽṹ������
        data = list(reader)
        
    # TODO: Read DNA sequence file into a variable ��ȡ DNA �����ļ������� 
    with open(sys.argv[2], "r") as file:
        seq = file.read()

    # TODO: Find longest match of each STR in DNA sequence ���� DNA ������ÿ�� STR ���ƥ��
    STR = []
    for i in range(1, len(reader.fieldnames)): # 1 ����csv�ļ��ĵ�һ���ֶ���
        STR.append(longest_match(seq, reader.fieldnames[i]))

    # TODO: Check database for matching profiles ������ݿ����Ƿ���ƥ��ĸ�������
    for person in data:
        match = True
        for i in range(1, len(reader.fieldnames)):
            if int(person[reader.fieldnames[i]]) != STR[i-1]:
                   match = False
                   break
        if match:
            print(person['name'])
            return
        
    print("No match")
    return


def longest_match(sequence, subsequence):
    """Returns length of longest run of subsequence in sequence."""

    # Initialize variables
    longest_run = 0
    subsequence_length = len(subsequence)
    sequence_length = len(sequence)

    # Check each character in sequence for most consecutive runs of subsequence
    for i in range(sequence_length):

        # Initialize count of consecutive runs
        count = 0

        # Check for a subsequence match in a "substring" (a subset of characters) within sequence
        # If a match, move substring to next potential match in sequence
        # Continue moving substring and checking for matches until out of consecutive matches
        while True:

            # Adjust substring start and end
            start = i + count * subsequence_length
            end = start + subsequence_length

            # If there is a match in the substring
            if sequence[start:end] == subsequence:
                count += 1
            
            # If there is no match in the substring
            else:
                break
        
        # Update most consecutive matches found
        longest_run = max(longest_run, count)

    # After checking for runs at each character in seqeuence, return longest run found
    return longest_run


main()

  • 24
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值