animalLookup = {
'a': ['aardvark', 'antelope'],
'b': ['bear'],
'c': ['cat'],
'd': ['dog'],
}
for letter, animals in animalLookup.items():
if len(animals) > 1:
continue
print(f'Only one animal! {animals[0]}')
for letter, animals in animalLookup.items():
.items()gives you key-value pairs from the dictionary.letterwill be the key ('a','b', etc.).animalswill be the list of animals associated with that key.
Example iteration:
First loop:
letter = 'a',animals = ['aardvark', 'antelope']Second loop:
letter = 'b',animals = ['bear']…and so on.
len(animals) counts how many animals are in the list.continue means “go to the next loop cycle”).'a' (two animals) will be skipped.animals[0] gets the first (and only) item in the list.f before the string tells Python: evaluate expressions inside {}.{animals[0]} is replaced with the first element of the list.'b', animals[0] = 'bear'.{} in are part of the f‑string syntax. They tell Python: “evaluate whatever is inside these brackets and insert the result into the string.”A prime number is a natural number greater than 1 that has no divisors other than 1 and itself.
Example:
Non‑prime (composite) numbers can be divided evenly by other numbers (e.g. ).
** is the exponentiation operator. It raises a number to the power of another number.- Starts at 2 (the first prime).
- Goes up to 99.
number by all integers from 2 up to the square root of number.% is the modulus operator (remainder).number is divisible by factor → not prime.break exits the inner loop immediately.else belongs to the for loop, not the if.Example trace
number = 7Factors checked: 2 → not divisible, 3 → not divisible.
Loop ends without
break.elseruns → prints"7 is prime!".
number = 9Factors checked: 2 → not divisible, 3 → divisible.
breaktriggers.elseskipped → nothing printed.
int() function truncates (drops the decimal part), not rounds.
沒有留言:
發佈留言