0% found this document useful (0 votes)
9 views50 pages

Filter Gryffindor Students List

The document consists of multiple Python scripts demonstrating various programming concepts, including filtering duplicates, implementing a bank account, using constants, handling command-line arguments, and unpacking lists and dictionaries. Each script showcases different techniques such as loops, sets, classes, and comprehensions. The examples also illustrate error handling and type annotations in function definitions.

Uploaded by

hac22king
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views50 pages

Filter Gryffindor Students List

The document consists of multiple Python scripts demonstrating various programming concepts, including filtering duplicates, implementing a bank account, using constants, handling command-line arguments, and unpacking lists and dictionaries. Each script showcases different techniques such as loops, sets, classes, and comprehensions. The examples also illustrate error handling and type annotations in function definitions.

Uploaded by

hac22king
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

houses0.

py

1 # Filters out duplicate houses using loop


2
3 students = [
4 {"name": "Hermione", "house": "Gryffindor"},
5 {"name": "Harry", "house": "Gryffindor"},
6 {"name": "Ron", "house": "Gryffindor"},
7 {"name": "Draco", "house": "Slytherin"},
8 {"name": "Padma", "house": "Ravenclaw"},
9 ]
10
11 houses = []
12 for student in students:
13 if student["house"] not in houses:
14 [Link](student["house"])
15
16 for house in sorted(houses):
17 print(house)
[Link]

1 # Filters out duplicate houses using set


2
3 students = [
4 {"name": "Hermione", "house": "Gryffindor"},
5 {"name": "Harry", "house": "Gryffindor"},
6 {"name": "Ron", "house": "Gryffindor"},
7 {"name": "Draco", "house": "Slytherin"},
8 {"name": "Padma", "house": "Ravenclaw"},
9 ]
10
11 houses = set()
12 for student in students:
13 [Link](student["house"])
14
15 for house in sorted(houses):
16 print(house)
[Link]

1 # Implements a bank account


2
3 balance = 0
4
5
6 def main():
7 print("Balance:", balance)
8
9
10 if __name__ == "__main__":
11 main()
[Link]

1 # UnboundLocalError
2
3 balance = 0
4
5
6 def main():
7 print("Balance:", balance)
8 deposit(100)
9 withdraw(50)
10 print("Balance:", balance)
11
12
13 def deposit(n):
14 balance += n
15
16
17 def withdraw(n):
18 balance -= n
19
20
21 if __name__ == "__main__":
22 main()
[Link]

1 # Uses global
2
3 balance = 0
4
5
6 def main():
7 print("Balance:", balance)
8 deposit(100)
9 withdraw(50)
10 print("Balance:", balance)
11
12
13 def deposit(n):
14 global balance
15 balance += n
16
17
18 def withdraw(n):
19 global balance
20 balance -= n
21
22
23 if __name__ == "__main__":
24 main()
[Link]

1 # Uses class
2
3
4 class Account:
5 def __init__(self):
6 self._balance = 0
7
8 @property
9 def balance(self):
10 return self._balance
11
12 def deposit(self, n):
13 self._balance += n
14
15 def withdraw(self, n):
16 self._balance -= n
17
18
19 def main():
20 account = Account()
21 print("Balance:", [Link])
22 [Link](100)
23 [Link](50)
24 print("Balance:", [Link])
25
26
27 if __name__ == "__main__":
28 main()
[Link]

1 # Demonstrates a constant
2
3 MEOWS = 3
4
5 for _ in range(MEOWS):
6 print("meow")
[Link]

1 # Demonstrates a class constant


2
3
4 class Cat:
5 MEOWS = 3
6
7 def meow(self):
8 for _ in range([Link]):
9 print("meow")
10
11
12 cat = Cat()
13 [Link]()
[Link]

1 # Demonstrates TypeError
2
3
4 def meow(n):
5 for _ in range(n):
6 print("meow")
7
8
9 number = input("Number: ")
10 meow(number)
[Link]

1 # Argument ... has incompatible type


2
3
4 def meow(n: int):
5 for _ in range(n):
6 print("meow")
7
8
9 number = input("Number: ")
10 meow(number)
[Link]

1 # Incompatible types in assignment


2
3
4 def meow(n: int):
5 for _ in range(n):
6 print("meow")
7
8
9 number: int = input("Number: ")
10 meow(number)
[Link]

1 # Success
2
3
4 def meow(n: int):
5 for _ in range(n):
6 print("meow")
7
8
9 number: int = int(input("Number: "))
10 meow(number)
[Link]

1 # Prints None because mistakes meow as having a return value


2
3
4 def meow(n: int):
5 for _ in range(n):
6 print("meow")
7
8
9 number: int = int(input("Number: "))
10 meows: str = meow(number)
11 print(meows)
[Link]

1 # Annotates return value, ... does not return a value


2
3
4 def meow(n: int) -> None:
5 for _ in range(n):
6 print("meow")
7
8
9 number: int = int(input("Number: "))
10 meows: str = meow(number)
11 print(meows)
[Link]

1 # Success
2
3
4 def meow(n: int) -> str:
5 return "meow\n" * n
6
7
8 number: int = int(input("Number: "))
9 meows: str = meow(number)
10 print(meows, end="")
[Link]

1 # Adds docstring to function.


2
3
4 def meow(n):
5 """Meow n times."""
6 return "meow\n" * n
7
8
9 number = int(input("Number: "))
10 meows = meow(number)
11 print(meows, end="")
[Link]

1 # Uses Sphinx docstring format


2
3
4 def meow(n):
5 """
6 Meow n times.
7
8 :param n: Number of times to meow
9 :type n: int
10 :raise TypeError: If n is not an int
11 :return: A string of n meows, one per line
12 :rtype: str
13 """
14 return "meow\n" * n
15
16
17 number = int(input("Number: "))
18 meows = meow(number)
19 print(meows, end="")
[Link]

1 # Uses command-line argument


2
3 import sys
4
5 if len([Link]) == 1:
6 print("meow")
7 elif len([Link]) == 3 and [Link][1] == "-n":
8 n = int([Link][2])
9 for _ in range(n):
10 print("meow")
11 else:
12 print("usage: [Link] [-n NUMBER]")
[Link]

1 # Uses command-line argument


2
3 import argparse
4
5 parser = [Link]()
6 parser.add_argument("-n")
7 args = parser.parse_args()
8
9 for _ in range(int(args.n)):
10 print("meow")
[Link]

1 # Adds description, help


2
3 import argparse
4
5 parser = [Link](description="Meow like a cat")
6 parser.add_argument("-n", help="number of times to meow")
7 args = parser.parse_args()
8
9 for _ in range(int(args.n)):
10 print("meow")
[Link]

1 # Adds default, type; removes int()


2
3 import argparse
4
5 parser = [Link](description="Meow like a cat")
6 parser.add_argument("-n", default=1, help="number of times to meow", type=int)
7 args = parser.parse_args()
8
9 for _ in range(args.n):
10 print("meow")
[Link]

1 # Unpacks a list
2
3 first, _ = input("What's your name? ").split(" ")
4 print(f"hello, {first}")
[Link]

1 # Passes positional arguments as usual


2 # [Link]
3
4
5 def total(galleons, sickles, knuts):
6 return (galleons * 17 + sickles) * 29 + knuts
7
8
9 print(total(100, 50, 25), "Knuts")
[Link]

1 # Indexes into list


2
3
4 def total(galleons, sickles, knuts):
5 return (galleons * 17 + sickles) * 29 + knuts
6
7
8 coins = [100, 50, 25]
9
10 print(total(coins[0], coins[1], coins[2]), "Knuts")
[Link]

1 # Unpacks a list
2
3
4 def total(galleons, sickles, knuts):
5 return (galleons * 17 + sickles) * 29 + knuts
6
7
8 coins = [100, 50, 25]
9
10 print(total(*coins), "Knuts")
[Link]

1 # Passes named arguments as usual


2
3
4 def total(galleons, sickles, knuts):
5 return (galleons * 17 + sickles) * 29 + knuts
6
7
8 print(total(galleons=100, sickles=50, knuts=25), "Knuts")
[Link]

1 # Indexes into a dict


2
3
4 def total(galleons, sickles, knuts):
5 return (galleons * 17 + sickles) * 29 + knuts
6
7
8 coins = {"galleons": 100, "sickles": 50, "knuts": 25}
9
10 print(total(coins["galleons"], coins["sickles"], coins["knuts"]), "Knuts")
[Link]

1 # Unpacks a dict
2
3
4 def total(galleons, sickles, knuts):
5 return (galleons * 17 + sickles) * 29 + knuts
6
7
8 coins = {"galleons": 100, "sickles": 50, "knuts": 25}
9
10 print(total(**coins), "Knuts")
[Link]

1 # Prints positional arguments


2
3
4 def f(*args, **kwargs):
5 print("Positional:", args)
6
7
8 f(100, 50, 25)
[Link]

1 # Prints named arguments


2
3
4 def f(*args, **kwargs):
5 print("Named:", kwargs)
6
7
8 f(galleons=100, sickles=50, knuts=25)
[Link]

1 # Prints a word in uppercase


2
3
4 def main():
5 yell("This is CS50")
6
7
8 def yell(word):
9 print([Link]())
10
11
12 if __name__ == "__main__":
13 main()
[Link]

1 # Passes a list
2
3
4 def main():
5 yell(["This", "is", "CS50"])
6
7
8 def yell(words):
9 uppercased = []
10 for word in words:
11 [Link]([Link]())
12 print(*uppercased)
13
14
15 if __name__ == "__main__":
16 main()
[Link]

1 # Prints arbitrarily many args in uppercase


2
3
4 def main():
5 yell("This", "is", "CS50")
6
7
8 def yell(*words):
9 uppercased = []
10 for word in words:
11 [Link]([Link]())
12 print(*uppercased)
13
14
15 if __name__ == "__main__":
16 main()
[Link]

1 # Uses map
2
3
4 def main():
5 yell("This", "is", "CS50")
6
7
8 def yell(*words):
9 uppercased = map([Link], words)
10 print(*uppercased)
11
12
13 if __name__ == "__main__":
14 main()
[Link]

1 # Uses list comprehension


2
3
4 def main():
5 yell("This", "is", "CS50")
6
7
8 def yell(*words):
9 uppercased = [[Link]() for arg in words]
10 print(*uppercased)
11
12
13 if __name__ == "__main__":
14 main()
[Link]

1 # Filters by house using loop


2
3 students = [
4 {"name": "Hermione", "house": "Gryffindor"},
5 {"name": "Harry", "house": "Gryffindor"},
6 {"name": "Ron", "house": "Gryffindor"},
7 {"name": "Draco", "house": "Slytherin"},
8 ]
9
10 gryffindors = []
11 for student in students:
12 if student["house"] == "Gryffindor":
13 [Link](student["name"])
14
15 for gryffindor in sorted(gryffindors):
16 print(gryffindor)
[Link]

1 # Filters by house using list comprehension


2
3 students = [
4 {"name": "Hermione", "house": "Gryffindor"},
5 {"name": "Harry", "house": "Gryffindor"},
6 {"name": "Ron", "house": "Gryffindor"},
7 {"name": "Draco", "house": "Slytherin"},
8 ]
9
10 gryffindors = [
11 student["name"] for student in students if student["house"] == "Gryffindor"
12 ]
13
14 for gryffindor in sorted(gryffindors):
15 print(gryffindor)
[Link]

1 # Uses filter and key with lambda


2
3 students = [
4 {"name": "Hermione", "house": "Gryffindor"},
5 {"name": "Harry", "house": "Gryffindor"},
6 {"name": "Ron", "house": "Gryffindor"},
7 {"name": "Draco", "house": "Slytherin"},
8 ]
9
10
11 def is_gryffindor(s):
12 return s["house"] == "Gryffindor"
13
14
15 gryffindors = filter(is_gryffindor, students)
16
17 for gryffindor in sorted(gryffindors, key=lambda s: s["name"]):
18 print(gryffindor["name"])
[Link]

1 # Uses filter with lambda


2
3 students = [
4 {"name": "Hermione", "house": "Gryffindor"},
5 {"name": "Harry", "house": "Gryffindor"},
6 {"name": "Ron", "house": "Gryffindor"},
7 {"name": "Draco", "house": "Slytherin"},
8 ]
9
10
11 gryffindors = filter(lambda s: s["house"] == "Gryffindor", students)
12
13 for gryffindor in sorted(gryffindors, key=lambda s: s["name"]):
14 print(gryffindor["name"])
[Link]

1 # Creates list of dicts using loop


2
3 students = ["Hermione", "Harry", "Ron"]
4
5 gryffindors = []
6
7 for student in students:
8 [Link]({"name": student, "house": "Gryffindor"})
9
10 print(gryffindors)
[Link]

1 # Uses dictionary comprehension instead


2
3 students = ["Hermione", "Harry", "Ron"]
4
5 gryffindors = [{"name": student, "house": "Gryffindor"} for student in students]
6
7 print(gryffindors)
[Link]

1 # Uses dictionary comprehension instead


2
3 students = ["Hermione", "Harry", "Ron"]
4
5 gryffindors = {student: "Gryffindor" for student in students}
6
7 print(gryffindors)
[Link]

1 # Iterates over a list by index


2
3 students = ["Hermione", "Harry", "Ron"]
4
5 for i in range(len(students)):
6 print(i + 1, students[i])
[Link]

1 # Uses enumerate instead


2
3 students = ["Hermione", "Harry", "Ron"]
4
5 for i, student in enumerate(students):
6 print(i + 1, student)
[Link]

1 # Prints n sheep
2
3 n = int(input("What's n? "))
4 for i in range(n):
5 print("🐑" * i)
[Link]

1 # Adds main
2
3
4 def main():
5 n = int(input("What's n? "))
6 for i in range(n):
7 print("🐑" * i)
8
9
10 if __name__ == "__main__":
11 main()
[Link]

1 # Returns n sheep from helper function


2
3
4 def main():
5 n = int(input("What's n? "))
6 for i in range(n):
7 print(sheep(i))
8
9
10 def sheep(n):
11 return "🐑" * n
12
13
14 if __name__ == "__main__":
15 main()
[Link]

1 # Returns a list of sheep


2
3
4 def main():
5 n = int(input("What's n? "))
6 for s in sheep(n):
7 print(s)
8
9
10 def sheep(n):
11 flock = []
12 for i in range(n):
13 [Link]("🐑" * i)
14 return flock
15
16
17 if __name__ == "__main__":
18 main()
[Link]

1 # Uses yield
2
3
4 def main():
5 n = int(input("What's n? "))
6 for s in sheep(n):
7 print(s)
8
9
10 def sheep(n):
11 for i in range(n):
12 yield "🐑" * i
13
14
15 if __name__ == "__main__":
16 main()
[Link]

1 import cowsay
2 import pyttsx3
3
4 engine = [Link]()
5 this = input("What's this? ")
6 [Link](this)
7 [Link](this)
8 [Link]()

Common questions

Powered by AI

UnboundLocalError occurs when trying to increment or decrement a variable that a function assumes is global, without first declaring it with the 'global' keyword. For instance, in 'bank1.py', the functions 'deposit' and 'withdraw' try to modify 'balance' directly, resulting in an error. Using the 'global balance' declaration inside these functions resolves the issue by allowing them to modify the global variable .

Generator functions use 'yield' to produce items one at a time, useful for iterating over large data streams sequentially without storing the entire sequence. In 'sleep4.py', the 'sheep' function uses 'yield' to return sheep strings iteratively, creating an efficient way to manage output without holding all values in memory simultaneously .

Function annotations specify argument types and return values, offering clearer intent and aiding in error checking. For example, 'meows7.py' uses annotations to clarify that 'meow' expects an integer argument and returns a string. This not only improves code readability but also assists IDEs and tools in type error detection, minimizing runtime errors .

Positional arguments are passed based on their order, while keyword arguments are passed by naming each variable. Effective utilization of both allows functions to be more versatile and user-friendly. For instance, 'unpack8.py' demonstrates positional arguments with '*'args and keyword arguments with '**'kwargs, enabling the function to handle varying numbers of inputs seamlessly, enhancing flexibility and comprehensibility .

Property decorators allow for encapsulation and control over how class attributes are accessed and modified, offering a method for validation or computation before returning or setting a value. In 'bank2.py', the 'Account' class uses the '@property' decorator to manage '_balance', ensuring that 'balance' can be read but modifications can only occur through methods, optimizing control and integrity of the bank account's operations .

A decorator alters the behavior of functions dynamically through wrapping, while 'map' applies a function to iterable elements. In 'yell3.py', 'map' uses 'str.upper' to transform inputs to uppercase, facilitating concise iteration over words, contrasting with decorators that modify functions' execution logic as seen with the '@property' in bank accounts .

List comprehension allows filtering and transforming data concisely in a single line, reducing the need for loops. For example, in 'gryffindors1.py', list comprehension is used to filter students from Gryffindor: '[student["name"] for student in students if student["house"] == "Gryffindor"]', compactly fetching all Gryffindors' names in one line .

Dictionary unpacking allows passing dictionary values as function arguments using '**', facilitating more concise and readable code. This is demonstrated in 'unpack6.py', where the dictionary 'coins' is unpacked directly into the 'total' function, converting wizarding currency units to knuts. It eliminates the need for explicitly referencing each dictionary value individually, streamlining the function call .

Using a set to filter duplicates is generally more efficient than a loop because sets inherently store only unique elements. In 'houses1.py', using a set to keep track of houses ensures each house is stored only once automatically, while 'houses0.py' uses a loop to check each house before adding it to a list, which is less efficient as it involves more manual checks .

Command-line arguments allow for dynamic input, making scripts more adaptable for different use cases without altering code. In 'meows11.py', arguments '-n NUMBER' specify the number of 'meow''s to print, altering script behavior at runtime without changing the code, thereby enhancing usability and flexibility .

You might also like