In [4]:
def Prime_Number(n, i=2):
if n == i:
return True
elif n % i == 0:
return False
return Prime_Number(n, i + 1)
n = 113971
if Prime_Number(n):
print("Yes,", n, "is Prime")
else:
print("No,", n, "is not a Prime")
No, 113971 is not a Prime
In [6]:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
apple banana cherry
In [9]:
fruits = ("apple", "banana", "cherry")
(green, *a) = fruits
print(green)
print(a)
apple ['banana', 'cherry']
In [14]:
fruits = ("apple", "banana", "cherry")
(_,yellow, _) = fruits
print(yellow)
print(fruits[1])
banana banana
In [20]:
fruits += "kiwi",
fruits += 1,
print(fruits)
('apple', 'banana', 'cherry', 'kiwi', 'kiwi', 'kiwi', 'kiwi', 'kiwi', 'kiwi', 'kiwi', 'kiwi', 1)
In [23]:
x = 1
y = 1.5
(x, y) = (y, x)
print(x)
print(y)
1.5 1
In [25]:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
print(x,thistuple.index(5))
2 5
Dictionary¶
Key: immutable: int, str, bool, tuple, float (not recommended)
In [37]:
my_dict = {'a':1,1.01:'a',True:'b',(1,1.):True}
print(my_dict)
{'a': 1, 1.01: 'a', True: 'b', (1, 1.0): True}
In [46]:
# my_dict[False]
print(type(my_dict.get(False,'in no False in dect')))
<class 'str'>
In [45]:
1 not in my_dict
Out[45]:
True
In [58]:
my_dict = {'a':1,'b':2,'c':3,'d':4}
print(my_dict)
print(my_dict.pop('a')) #returned value by key and delete the entry
print(my_dict.pop('b','Ups')) #returned alternative value since no key found
key1, value1 = my_dict.popitem()
{'a': 1, 'b': 2, 'c': 3, 'd': 4} 1 2
In [75]:
my_dict = {'a':1,'b':2,'c':3,'d':4}
my_dict.keys()
my_dict.values()
my_dict.items() # iterable
tuple(my_dict.items())[2]
for x in my_dict.items():
print(x)
for x in my_dict: # keys by default
print(x)
for x,y in enumerate(my_dict):
print(x,y)
('a', 1) ('b', 2) ('c', 3) ('d', 4) a b c d 0 a 1 b 2 c 3 d
In [98]:
my_dict = {'a':1,'b':2,'c':3,'d':4}
d2 = my_dict
d2['a'] = 10
print(my_dict)
my_dict = {'a':1,'b':2,'c':3,'d':4}
d2 = my_dict.copy()
d2['a'] = 10
print(my_dict)
{'a': 10, 'b': 2, 'c': 3, 'd': 4} {'a': 1, 'b': 2, 'c': 3, 'd': 4}
In [84]:
def my_func(**params):
return params
a = my_func(a=1,b=2,c=3)
print(a)
{'a': 1, 'b': 2, 'c': 3}
In [88]:
numbers = [1,2,3]
squares = [x**2 for x in numbers]
d = {}
for x, y in zip(numbers,squares):
d[x] = y
print(d)
{1: 1, 2: 4, 3: 9}
In [89]:
# dictionary comprehension
d = {x:y for x,y in zip(numbers,squares)}
print(d)
{1: 1, 2: 4, 3: 9}
In [95]:
numbers = {'first':1,'second':2,'third':3,'fourth':4}
print(sorted(numbers)) # by key
print(sorted(numbers,key=numbers.get,reverse=True)) # by value
['first', 'fourth', 'second', 'third'] ['fourth', 'third', 'second', 'first']