Python back to basics
InĀ [4]:
Copied!
#""" Python training course notes """
## Why Python ?
# - Versatility
# - Readability
# - Clear Syntax
# Usage : Games, Web dev, Data sciences ...
## Installation : ?
# Anaconda3 :
# https://www.anaconda.com/products/individual
#""" Python training course notes """
## Why Python ?
# - Versatility
# - Readability
# - Clear Syntax
# Usage : Games, Web dev, Data sciences ...
## Installation : ?
# Anaconda3 :
# https://www.anaconda.com/products/individual
InĀ [1]:
Copied!
# ### DATA TYPES & OPERATTORS ####
# Data types and operators ?
1 + 1 + 2
# ### DATA TYPES & OPERATTORS ####
# Data types and operators ?
1 + 1 + 2
Out[1]:
4
InĀ [6]:
Copied!
print(2-1)
print(2-1)
1
InĀ [7]:
Copied!
(10/3)
(10/3)
Out[7]:
3.3333333333333335
InĀ [8]:
Copied!
(4*4)
(4*4)
Out[8]:
16
InĀ [9]:
Copied!
3%1
3%1
Out[9]:
0
InĀ [10]:
Copied!
2**4
2**4
Out[10]:
16
InĀ [11]:
Copied!
13//2
13//2
Out[11]:
6
InĀ [12]:
Copied!
# Variables
holds a value in a memory
# Variables
holds a value in a memory
File "<ipython-input-12-5dc86d11971a>", line 3 holds a value in a memory ^ SyntaxError: invalid syntax
InĀ [9]:
Copied!
age = 5
age
age = 5
age
Out[9]:
5
InĀ [13]:
Copied!
# variable with same characteristic
age, name, gender = 30, 'afondiel', 'male'
print (age, name, gender)
# variable with same characteristic
age, name, gender = 30, 'afondiel', 'male'
print (age, name, gender)
30 afondiel male
InĀ [16]:
Copied!
# Variable Convention
# all variable name shold be low case with undercore between
full_name = "Wakanda Forever"
print('full_name')
# Variable Convention
# all variable name shold be low case with undercore between
full_name = "Wakanda Forever"
print('full_name')
full_name
InĀ [17]:
Copied!
age +=5
print (age)
age +=5
print (age)
35
InĀ [19]:
Copied!
age -= 5
print(age)
age -= 5
print(age)
30
InĀ [27]:
Copied!
# Numerical data types
# int, float
x = 7
y = 3
z = x/y
hi = 'hello human'
print(z)
print(hi)
# Numerical data types
# int, float
x = 7
y = 3
z = x/y
hi = 'hello human'
print(z)
print(hi)
2.3333333333333335 hello human
InĀ [28]:
Copied!
print((type(z)))
print((type(hi)))
print((type(z)))
print((type(hi)))
<class 'float'> <class 'str'>
InĀ [30]:
Copied!
# Conversion & Casting
print(int(3.7))
# Conversion & Casting
print(int(3.7))
3
InĀ [Ā ]:
Copied!
# String Data Types
# str
# String Data Types
# str
InĀ [33]:
Copied!
name = 'Terminator'
print(name)
print(type(name))
name = 'Terminator'
print(name)
print(type(name))
Terminator <class 'str'>
InĀ [38]:
Copied!
dialogue = 'Terminator said "Hello John", to which John replied, "Hello You\'re the best"'
print(dialogue)
dialogue = 'Terminator said "Hello John", to which John replied, "Hello You\'re the best"'
print(dialogue)
Terminator said "Hello John", to which John replied, "Hello You're the best"
InĀ [46]:
Copied!
segment_one = 'I\'am 25'
segment_two = 'year old'
full_sentence =segment_one + " " + segment_two # concatenation
long_sentence = full_sentence*20 # multiply strings
print(full_sentence)
print(long_sentence)
print(len(long_sentence)) #length
segment_one = 'I\'am 25'
segment_two = 'year old'
full_sentence =segment_one + " " + segment_two # concatenation
long_sentence = full_sentence*20 # multiply strings
print(full_sentence)
print(long_sentence)
print(len(long_sentence)) #length
I'am 25 year old I'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year oldI'am 25 year old 320
InĀ [Ā ]:
Copied!
# Booleans
# True or False
# Booleans
# True or False
InĀ [48]:
Copied!
cool = True
not_cool = False
print(type(cool))
cool = True
not_cool = False
print(type(cool))
<class 'bool'>
InĀ [54]:
Copied!
# Boolean used for comparaison : >, <, >=, =<, !=, and, or, not
comp = not (( 1 > 2) and (3 > 2))
print(comp)
# Boolean used for comparaison : >, <, >=, =<, !=, and, or, not
comp = not (( 1 > 2) and (3 > 2))
print(comp)
True
InĀ [Ā ]:
Copied!
#3 Methods != Functions ?
# Methods : Data Type that can be associate with multiples(specific) methods | can be access with dot (".)
# Function : accepts args and return or not a single values
#3 Methods != Functions ?
# Methods : Data Type that can be associate with multiples(specific) methods | can be access with dot (".)
# Function : accepts args and return or not a single values
InĀ [59]:
Copied!
movie_title = 'Harry Potter and Prisoner of Azkaban'
# print(movie_title.upper())
print(movie_title.count('a')) # count the number of the letter 'a' in the string
movie_title = 'Harry Potter and Prisoner of Azkaban'
# print(movie_title.upper())
print(movie_title.count('a')) # count the number of the letter 'a' in the string
4
InĀ [60]:
Copied!
# Collections Types
# List, Tuple, dict ...
# List : sequence Data Type
# Collections Types
# List, Tuple, dict ...
# List : sequence Data Type
InĀ [62]:
Copied!
names = ['John','Jane', 'Joe']
print(names[0])
print(len(names))
names = ['John','Jane', 'Joe']
print(names[0])
print(len(names))
John 3
InĀ [124]:
Copied!
random_names = [True, False,1.2, 4,'Jane', 'Joe']
name_path = len('D:\\Lab\\Training\\Udemy\\self-driving-car')
print(random_names)
print(name_path)
random_names = [True, False,1.2, 4,'Jane', 'Joe']
name_path = len('D:\\Lab\\Training\\Udemy\\self-driving-car')
print(random_names)
print(name_path)
[True, False, 1.2, 4, 'Jane', 'Joe'] 38
InĀ [125]:
Copied!
# random_names_new = random_names.append('Hendrix')
# random_names_new_new = random_names_new.insert(3,'Hendrix')
# print(random_names)
# print(random_names_new)
# print(random_names_new_new)
print(name_path[:-3])
# random_names_new = random_names.append('Hendrix')
# random_names_new_new = random_names_new.insert(3,'Hendrix')
# print(random_names)
# print(random_names_new)
# print(random_names_new_new)
print(name_path[:-3])
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-125-c83ef578373c> in <module> 4 # print(random_names_new) 5 # print(random_names_new_new) ----> 6 print(name_path[:-3]) TypeError: 'int' object is not subscriptable
InĀ [Ā ]:
Copied!
# SLICING
# List[start ========> (end - 1)]
# SLICING
# List[start ========> (end - 1)]
InĀ [132]:
Copied!
ordered_numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print (ordered_numbers[2:9])
print (ordered_numbers[:9])
print (ordered_numbers[:len(ordered_numbers)])
print (ordered_numbers[:])
print (ordered_numbers[:2])
ordered_numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print (ordered_numbers[2:9])
print (ordered_numbers[:9])
print (ordered_numbers[:len(ordered_numbers)])
print (ordered_numbers[:])
print (ordered_numbers[:2])
[2, 3, 4, 5, 6, 7, 8] [0, 1, 2, 3, 4, 5, 6, 7, 8] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [0, 1]
InĀ [140]:
Copied!
# Creating list of numbers
print(list(range(0,10)))
print(list(range(0,10,2))) # step of 2
# Creating list of numbers
print(list(range(0,10)))
print(list(range(0,10,2))) # step of 2
[0, 2, 4, 6, 8]
InĀ [143]:
Copied!
show_title = 'game_of_thrones'
print(show_title[:-3])
show_title = 'game_of_thrones'
print(show_title[:-3])
game_of_thro
InĀ [145]:
Copied!
# Membership operators
# in / not in
months = ['January', 'February', 'March']
print('January' in months)
print('January' not in months)
# Membership operators
# in / not in
months = ['January', 'February', 'March']
print('January' in months)
print('January' not in months)
True False
InĀ [149]:
Copied!
#String cases
course = 'python crash course'
print('crash' in course)
print('crash' not in course)
#String cases
course = 'python crash course'
print('crash' in course)
print('crash' not in course)
True False
InĀ [Ā ]:
Copied!
# Mutability
# Mutable : Liable to change
# Immutable : Not liable to change
# List : Mutable
# String : Immutable
# Mutability
# Mutable : Liable to change
# Immutable : Not liable to change
# List : Mutable
# String : Immutable
InĀ [151]:
Copied!
grocery_list = ['bananas','apples', 'cauliflower']
print(grocery_list)
grocery_list[2] = 'rutabagas'
print(grocery_list)
grocery_list = ['bananas','apples', 'cauliflower']
print(grocery_list)
grocery_list[2] = 'rutabagas'
print(grocery_list)
['bananas', 'apples', 'cauliflower'] ['bananas', 'apples', 'rutabagas']
InĀ [154]:
Copied!
misspelled_vegetable = 'cucomber'
misspelled_vegetable[3] = 'u'
print(misspelled_vegetable)
misspelled_vegetable = 'cucomber'
misspelled_vegetable[3] = 'u'
print(misspelled_vegetable)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-154-55840abc2b59> in <module> 1 misspelled_vegetable = 'cucomber' ----> 2 misspelled_vegetable[3] = 'u' 3 print(misspelled_vegetable) TypeError: 'str' object does not support item assignment
InĀ [155]:
Copied!
name = 'Ameer'
other_name = name
name = 'John'
print(name)
print(other_name)
name = 'Ameer'
other_name = name
name = 'John'
print(name)
print(other_name)
John Ameer
InĀ [157]:
Copied!
# Memory storage
books = ['The Catcher in the Rye', 'The Mist', 'Lord of Rings']
more_books = books
books[0] = 'A song of ice and fire'
print(books[0])
print(more_books)
# Memory storage
books = ['The Catcher in the Rye', 'The Mist', 'Lord of Rings']
more_books = books
books[0] = 'A song of ice and fire'
print(books[0])
print(more_books)
A song of ice and fire ['A song of ice and fire', 'The Mist', 'Lord of Rings']
InĀ [167]:
Copied!
# FUNCTIONS AND METHODS LIST
# Data type functions
# len () : returns number of items of an object
# max () : returns the maximum value of the list
# sorted() : sort low to higest
# insert(pos, val) :
numbers = [3, 1, 4] # list of integers
print(len(numbers))
print(max(numbers))
print(min(numbers))
print(sorted(numbers))
# FUNCTIONS AND METHODS LIST
# Data type functions
# len () : returns number of items of an object
# max () : returns the maximum value of the list
# sorted() : sort low to higest
# insert(pos, val) :
numbers = [3, 1, 4] # list of integers
print(len(numbers))
print(max(numbers))
print(min(numbers))
print(sorted(numbers))
3 4 1 [1, 3, 4]
InĀ [168]:
Copied!
name = ['Thomas', 'Gio', 'Zack']
print(min(name)) # returns the alphabet order of the less letter of the string
print(max(name)) # returns the alphabet order of the greater letter of the string
print(sorted(name))
name = ['Thomas', 'Gio', 'Zack']
print(min(name)) # returns the alphabet order of the less letter of the string
print(max(name)) # returns the alphabet order of the greater letter of the string
print(sorted(name))
Gio Zack ['Gio', 'Thomas', 'Zack']
InĀ [184]:
Copied!
# Data types Methods
#
# join(list)
# format(list of strings)
# append() :
print('-'.join(['Mon', 'Tue', 'Wed']))
print(' '.join(['Mon', 'Tue', 'Wed']))
# FORMAT STRINGS
print('This person is {}, {} and {}'.format('tall', 'slim','blond'))
months = ['January', 'February', 'March']
months.append('April')
print(months)
# Data types Methods
#
# join(list)
# format(list of strings)
# append() :
print('-'.join(['Mon', 'Tue', 'Wed']))
print(' '.join(['Mon', 'Tue', 'Wed']))
# FORMAT STRINGS
print('This person is {}, {} and {}'.format('tall', 'slim','blond'))
months = ['January', 'February', 'March']
months.append('April')
print(months)
Mon-Tue-Wed Mon Tue Wed This person is tall, slim and blond ['January', 'February', 'March', 'April']
InĀ [180]:
Copied!
# TUPLES (just like lists)
# Immutable ordered sequence of elements :stored RELATED element
# TUPLES (just like lists)
# Immutable ordered sequence of elements :stored RELATED element
This person is tall, slim and blond
InĀ [185]:
Copied!
traits = ('tail', 'slim', 'blond')
height = traits[0]
build = traits[1]
print (height, build)
traits = ('tail', 'slim', 'blond')
height = traits[0]
build = traits[1]
print (height, build)
tail slim
InĀ [186]:
Copied!
# /!\ TUPLES UNPACKING
traits = ('tail', 'slim', 'blond')
height, build, hair = traits
print (height, build, hair)
# /!\ TUPLES UNPACKING
traits = ('tail', 'slim', 'blond')
height, build, hair = traits
print (height, build, hair)
tail slim blond
InĀ [190]:
Copied!
# SETS
# a collection data types of uniques elements (it takes out the duplicated)
# Mutable, unordered
duplicated_numbers = [1, 1, 2, 2, 3, 3]
unique_numbers = set(duplicated_numbers)
print(unique_numbers)
unique_numbers.add(4)
print(unique_numbers)
# SETS
# a collection data types of uniques elements (it takes out the duplicated)
# Mutable, unordered
duplicated_numbers = [1, 1, 2, 2, 3, 3]
unique_numbers = set(duplicated_numbers)
print(unique_numbers)
unique_numbers.add(4)
print(unique_numbers)
{1, 2, 3}
{1, 2, 3, 4}
InĀ [191]:
Copied!
print(2 in unique_numbers) # membership operator
print(2 in unique_numbers) # membership operator
True
InĀ [198]:
Copied!
# !!!! DICTIONNARIES : !!!!
# more flexible data types/MUTABLE
# pair of (key:value) (/!\ key shall be unique)
# unordered sequence
# inventory = { key (item) : value(price) }
inventory = {'bananas' : 1.29, 'apples' : 2.99, 'papays' : 1.39}
print(inventory)
print(inventory['bananas'])
# !!!! DICTIONNARIES : !!!!
# more flexible data types/MUTABLE
# pair of (key:value) (/!\ key shall be unique)
# unordered sequence
# inventory = { key (item) : value(price) }
inventory = {'bananas' : 1.29, 'apples' : 2.99, 'papays' : 1.39}
print(inventory)
print(inventory['bananas'])
{'bananas': 1.29, 'apples': 2.99, 'papays': 1.39}
1.29
InĀ [197]:
Copied!
inventory['bananas'] = 2.3
print(inventory['bananas'])
inventory['bananas'] = 2.3
print(inventory['bananas'])
2.3
InĀ [200]:
Copied!
bananas_price = inventory.get('bananas')
print(bananas_price)
bananas_price = inventory.get('bananas')
print(bananas_price)
1.29
InĀ [201]:
Copied!
toto_price = inventory.get('toto')
print(toto_price)
toto_price = inventory.get('toto')
print(toto_price)
None
InĀ [202]:
Copied!
print('celery' in inventory)
print('celery' in inventory)
False
InĀ [205]:
Copied!
# /!\ COMPOUND DATA STRUCTURES /!\
grocery_items = {'bananas' : {'price' : 2.29,'country of origin': 'Guatamala' },
'apples' : {'price' : 1.29,'country of origin': 'UK' },
'papays' : {'price' : 2.39,'country of origin': 'Costa Rica' }}
print(grocery_items)
print('\n')
print(grocery_items['bananas'])
# /!\ COMPOUND DATA STRUCTURES /!\
grocery_items = {'bananas' : {'price' : 2.29,'country of origin': 'Guatamala' },
'apples' : {'price' : 1.29,'country of origin': 'UK' },
'papays' : {'price' : 2.39,'country of origin': 'Costa Rica' }}
print(grocery_items)
print('\n')
print(grocery_items['bananas'])
{'bananas': {'price': 2.29, 'country of origin': 'Guatamala'}, 'apples': {'price': 1.29, 'country of origin': 'UK'}, 'papays': {'price': 2.39, 'country of origin': 'Costa Rica'}}
{'price': 2.29, 'country of origin': 'Guatamala'}
InĀ [210]:
Copied!
print(grocery_items['bananas']['country of origin'])
print(grocery_items['bananas']['country of origin'])
Guatamala
InĀ [214]:
Copied!
# #### PARTI II : CONTROL FLOW #####
# Add Logic in the Code : Condition, Loop, ...
grocery_items = {'bananas' : 1.29, 'apples' : 2.99, 'papays' : 1.39}
# #### PARTI II : CONTROL FLOW #####
# Add Logic in the Code : Condition, Loop, ...
grocery_items = {'bananas' : 1.29, 'apples' : 2.99, 'papays' : 1.39}
InĀ [219]:
Copied!
item = 'brussel sprouts'
if item in grocery_items:
print('item found : ', item)
else :
print('item not found', item)
grocery_items.update({item: 3.1})
print('just added the item, here is the updated grocery list', grocery_items)
item = 'brussel sprouts'
if item in grocery_items:
print('item found : ', item)
else :
print('item not found', item)
grocery_items.update({item: 3.1})
print('just added the item, here is the updated grocery list', grocery_items)
item not found brussel sprouts
just added the item, here is the updated grocery list {'bananas': 1.29, 'apples': 2.99, 'papays': 1.39, 'brussel sprouts': 3.1}
InĀ [220]:
Copied!
item, price = 'rutabagas', 2.99
if item in grocery_items:
print('item found : ', item)
elif price > 2.99:
print('too expensive for inventory')
else :
print('item not found', item)
grocery_items.update({item: price})
print('just added the item, here is the updated grocery list', grocery_items)
item, price = 'rutabagas', 2.99
if item in grocery_items:
print('item found : ', item)
elif price > 2.99:
print('too expensive for inventory')
else :
print('item not found', item)
grocery_items.update({item: price})
print('just added the item, here is the updated grocery list', grocery_items)
item not found rutabagas
just added the item, here is the updated grocery list {'bananas': 1.29, 'apples': 2.99, 'papays': 1.39, 'brussel sprouts': 3.1, 'rutabagas': 2.99}
InĀ [224]:
Copied!
daytime = 'noon'
if daytime == 'dawn' :
print('still asleep')
elif daytime == 'morning' :
print('time to go to work')
else :
print('time to go to sleep')
daytime = 'noon'
if daytime == 'dawn' :
print('still asleep')
elif daytime == 'morning' :
print('time to go to work')
else :
print('time to go to sleep')
time to go to sleep
InĀ [227]:
Copied!
# COMPLEX COMPARISON
# 1000 < Reynold's Number < 2000
reynold_number = 5000
if 2000 < reynold_number < 10000:
print('flow regime is transitional')
# COMPLEX COMPARISON
# 1000 < Reynold's Number < 2000
reynold_number = 5000
if 2000 < reynold_number < 10000:
print('flow regime is transitional')
flow regime is transitional
InĀ [228]:
Copied!
if reynold_number > 2000 and reynold_number < 10000:
print('flow regime is transitional')
if reynold_number > 2000 and reynold_number < 10000:
print('flow regime is transitional')
flow regime is transitional
InĀ [Ā ]:
Copied!
# LOOOOPPPPPSSSSSS !
# For loop : iterates over an iterable :
# /!\ interable : can run one element at time (List, String, Dict, Tuples)
# LOOOOPPPPPSSSSSS !
# For loop : iterates over an iterable :
# /!\ interable : can run one element at time (List, String, Dict, Tuples)
InĀ [229]:
Copied!
months = ['January', 'February', 'March']
for month in months :
print(month)
months = ['January', 'February', 'March']
for month in months :
print(month)
January February March
InĀ [231]:
Copied!
for number in range(0, 100):
print(number)
for number in range(0, 100):
print(number)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
InĀ [239]:
Copied!
name = ['Hilary', 'Diana', 'Brian']
for idx in range (len(name)):
# print(idx)
name [idx] = name[idx].lower()
print(name)
print(name)
name = ['Hilary', 'Diana', 'Brian']
for idx in range (len(name)):
# print(idx)
name [idx] = name[idx].lower()
print(name)
print(name)
['hilary', 'Diana', 'Brian'] ['hilary', 'diana', 'Brian'] ['hilary', 'diana', 'brian'] ['hilary', 'diana', 'brian']
InĀ [241]:
Copied!
movies = {'Titanic' : 1997, 'Finding Nemo' : 2003}
for key in movies :
print(key)
movies = {'Titanic' : 1997, 'Finding Nemo' : 2003}
for key in movies :
print(key)
Titanic Finding Nemo
InĀ [249]:
Copied!
movies = {'Titanic' : 1997, 'Finding Nemo' : 2003}
for key , value in movies.items() : # item() : return the list of dict key:value pairs
print('The movie {}, was made in {}'.format(key, value))
movies = {'Titanic' : 1997, 'Finding Nemo' : 2003}
for key , value in movies.items() : # item() : return the list of dict key:value pairs
print('The movie {}, was made in {}'.format(key, value))
The movie Titanic, was made in 1997 The movie Finding Nemo, was made in 2003
InĀ [1]:
Copied!
# LOOOOOOOOOOP II
# While loop : Condition : ok => intruction
#/!\ Could run forever if condition never verified
random_number = 20
while random_number > 30 :
print(random_number)
break
# continue
# LOOOOOOOOOOP II
# While loop : Condition : ok => intruction
#/!\ Could run forever if condition never verified
random_number = 20
while random_number > 30 :
print(random_number)
break
# continue
InĀ [2]:
Copied!
numbers = list(range(0,10))
print(numbers)
numbers = list(range(0,10))
print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
InĀ [3]:
Copied!
for number in numbers :
if number % 2 != 0:
continue
print(number)
for number in numbers :
if number % 2 != 0:
continue
print(number)
0 2 4 6 8
InĀ [Ā ]:
Copied!
# ### PART III ###
# FUNCTIONS : Performs a specific task
# main goal : reusability
# scope, Docstrings, Lambda ...
# def function_name
# ### PART III ###
# FUNCTIONS : Performs a specific task
# main goal : reusability
# scope, Docstrings, Lambda ...
# def function_name
InĀ [13]:
Copied!
def rectangle_area(length, width) :
return length*width
def rectangle_area(length, width) :
return length*width
InĀ [15]:
Copied!
area = rectangle_area(2 , 4)
print(area)
area = rectangle_area(2 , 4)
print(area)
8
InĀ [18]:
Copied!
def rectangle_area(length, width) :
print(length*width)
rectangle_area(2, 3)
rectangle_area(4, 5)
def rectangle_area(length, width) :
print(length*width)
rectangle_area(2, 3)
rectangle_area(4, 5)
6 20
InĀ [Ā ]:
Copied!
# Function Scope : part of your program that can use or access a variable
# Local : Variable names assigned within a function
# Global : Variable names assigned every part of the program / Moduem (Encapsulation)
# Function Scope : part of your program that can use or access a variable
# Local : Variable names assigned within a function
# Global : Variable names assigned every part of the program / Moduem (Encapsulation)
InĀ [21]:
Copied!
number = 2 # Global scoped
def random_function() :
name = 'Bill' # name is scoped to the function
print (number)
number = 2 # Global scoped
def random_function() :
name = 'Bill' # name is scoped to the function
print (number)
2
InĀ [Ā ]:
Copied!
# Docstrings : String literal that documents a segment of code
# Docstrings : String literal that documents a segment of code
InĀ [Ā ]:
Copied!
def rectangle_area(length, width) :
"""
INPUT :
This function takes in two lenght and width
OUTPUT :
The Calculate the area based on the lenght and width by the user, where area = lenght x width
"""
return length*width
def rectangle_area(length, width) :
"""
INPUT :
This function takes in two lenght and width
OUTPUT :
The Calculate the area based on the lenght and width by the user, where area = lenght x width
"""
return length*width
InĀ [39]:
Copied!
# LAMBADA & HIGH ORDER FUNCTIONS :
numbers = [1, 2, 3, 4, 5]
for idx in range(len(numbers)+1) :
if idx % 2 != 0 :
numbers.remove(idx)
# numbers.pop(idx)
print(numbers)
# LAMBADA & HIGH ORDER FUNCTIONS :
numbers = [1, 2, 3, 4, 5]
for idx in range(len(numbers)+1) :
if idx % 2 != 0 :
numbers.remove(idx)
# numbers.pop(idx)
print(numbers)
[2, 4]
InĀ [38]:
Copied!
numbers = [1, 2, 3, 4, 5]
def even_or_odd(number) :
return number % 2 == 0
print(list(filter(even_or_odd, numbers)))
# Not reuseble
numbers = [1, 2, 3, 4, 5]
def even_or_odd(number) :
return number % 2 == 0
print(list(filter(even_or_odd, numbers)))
# Not reuseble
[2, 4]
InĀ [41]:
Copied!
numbers = [1, 2, 3, 4, 5]
# For a no reuseble code !!!
print(list(filter(lambda number : number % 2 == 0, numbers)))
numbers = [1, 2, 3, 4, 5]
# For a no reuseble code !!!
print(list(filter(lambda number : number % 2 == 0, numbers)))
[2, 4]
InĀ [Ā ]:
Copied!