import math
#print("hello world")
#number = float(7) / 2
#print(number) name321 = """fannan Cakti
Wibisono
"""
"""
this is a comment bro
"""
# some of a function, print(), among them take multiple argument, in which we can deal with it as such like this
#name = input("What's your name? ")
#print("Hello,", name)
# by this approach i dont need to actually placing a space after the comma of hello,
# or i could do this instead
#print("Hello, " + name)
#for i in range(1, 110):
# print(i % 10 == 1)
#name = input("whats your name? ")
#numlok = input("what is your lucky number? ")
#print(name + numlok)
#age = input("What's your age? ")
#print("im " + str(age) + " years old!")
#number1 = "100"
#number2 = "10"
#string_addition = number1 + number2
#print(string_addition)
## string_addition now has a value of "10010"
#int_addition = int(number1) + int(number2) XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#print(int_addition)
## int_addition has a value of 110
#same work for float
#sub2 = "23.12"
#print (float(sub2))
"""
float_1 = 0.25 float_2 = 40.0
product = float_1 * float_2 big_string = "The product was "
print(big_string + str(product)) or we could do this instead
float_1 = 0.25 float_2 = 40.0
product = float_1 * float_2
big_string = "The product was " + str(product) print(big_string)
"""
# the objective of this code is to get a floating number printed as a string in a litteral combined with a value of variable that contain str
""" ALL THAT HAVE BEEN LEARN FROM THE ABOVE -Print statements
-How to create, modify, and use variables
-Arithmetic operations like addition, subtraction, division, and multiplication
-How to use comments to make your code easy to understand
-Different data types, including strings, ints, floats, and booleans -Converting between data types
Here are a few more resources to add to your toolkit:
Codecademy Docs: Python
Codecademy Workspaces: Python
Make sure to bookmark these links so you have them at your disposal.
"""
'''
+ for adition - for substraction
* for multiplied / for dividing
% for modulo operator or, remainder from the result of dividing
** for to the power of (eksponen) '''
#REVIEW 1
'''skill_completed = "Python Syntax"
exercises_completed = 13
#The amount of points for each exercise may change, because points don't exist yet
points_per_exercise = 5
resultXXX = exercises_completed * points_per_exercise point_total = 100
point_total = 100 + resultXXX
print("I got " + str(point_total) , "points!")
'''
'This isn\'t flying, this is falling with style!' #ESCAPE SEQUENCE ''' ACCESS BY INDEX
fifth_letter = "MONTY"[4]
print fifth_letter '''
''' COUNTING CHARACTER parrot = "Norwegian Blue"
print len(parrot) '''
''' LOWER CASE
parrot = "Norwegian Blue".lower() /// .upper() print (parrot)
'''
''' STR() pi = 3.14 print str(pi) '''
'''
Let’s take a closer look at why you use len(string) and str(object), but dot notation (such as "String".upper()) for the rest. .... Methods that use dot notation only work with strings, On the other hand, len() and str() can work on other data types.
'''
''' String Concatenation
print("Spam " + "and " + "eggs") '''
''' Explicit String Conversion
print("I have " + str(2) + " coconuts!") '''
'''STRING FORMATING with %, Part 1
The % operator after the string is used to combine a string with variables. The % operator will replace the %s in the string with the string variable that comes after it.
If you’d like to print a variable that is an integer, you can “pad” it with zeros using %02d. The 0 means “pad with zeros”, the 2 means to pad to 2 characters wide, and the d means the number is a signed integer (can be positive or negative).
EXAMPLE : day = 6
print "03 - %s - 2019" % (day)
# 03 - 6 - 2019
print "03 - %02d - 2019" % (day)
# 03 - 06 - 2019
#FOR THIS EXAMPLE WE USE 2 argument, that mean i had to use 2 %s in the string text otherwise it would not work, and yes its sequentially (berurutan)
string_1 = "Camelot"
string_2 = "place"
print ("Let's not go to %s. 'Tis a silly %s." % (string_1,string_2)) '''
''' STRING FORMATING wih %, Part 2 name = "Alex"
quest = "Teaching Python"
color = "Blue"
print ("Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)) '''
''' DATE AND TIME LIBRARY :
from datetime import datetime
GETTING THE CURRENT DATE AND TIME : from datetime import datetime
print(datetime.now())
the line 144 can also be stored in a variable such as : now = (datetime.now())
print(now) '''
''' EXTRACTING INFORMATION
# Notice how the output looks like 2013-11-25 23:45:14.317454. What if you don’t want the entire date and time?
from datetime import datetime now = (datetime.now())
print(now.year) print(now.month) print(now.day)
# or you could just turn it into a variable b4 printing it '''
''' HOT DATE
# What if we want to print today’s date in the following format?
mm/dd/yyyy.
from datetime import datetime now = datetime.now()
print ('%02d/%02d/%04d' % (now.month, now.day, now.year)) '''
''' PREETY TIME
#Let’s do the same for the hour, minute, and second. hh/mm//ss from datetime import datetime
now = datetime.now()
print ("%02d:%02d:%02d" % (now.hour, now.minute, now.second)) '''
'''#Let’s do the same for all of it from datetime import datetime
now = datetime.now()
print ("Years : %02d/%02d/%04d...." \
" Time : %02d:%02d:%02d...." % (now.month, now.day, now.year, now.hour, now.minute, now.second))
'''
''' PRINTING A REAL PERCENT STRING
# To print a real string type of percent, you need to escape the
percent symbol by using double percent signs (%%). This tells Python to treat the percent symbol as a literal character rather than
interpreting it as a special character.
percent_health = str("%d %%" % 5)
print(f"Your health's percentage is : {percent_health}, keep trying") '''
''' CONTROL FLOW
# gives us this ability to choose among outcomes based on what else is happening in the program. The Python programs we’ve written so far have had one-track minds: they can add two numbers or print something, but they don’t have the ability to pick one of these outcomes over the other.
'''
''' COMPARATORS (control flow)
# Equal to (==) / Not equal to (!=) / Less than (<) / Less than or equal to (<=) / Greater than (>) / Greater than or equal to (>=)
# Comparators check if a value is (or is not) equal to, greater than (or equal to), or less than (or equal to) another value.
# Note that == compares whether two things are equal, and = assigns a value to a variable.
THIS IS CALLED BOOLEAN
#boolean is a true or false condition in which the answer give as for such is :
print("Fannan" == "Fannan") BOOLEAN OPERATOR
Compare statements and result in boolean values. There are three boolean operators:
>>> and, which checks if both the statements are True; as for such True + True = True , False + False = False , True + False = False , False + True = False
# EXAMPLE
# False and False
bool_one = 31 > 43 and 21 == 23
# -(-(-(-2))) == -2 and 4 >= 16 ** 0.5 bool_two = False
# 19 % 4 != 300 / 10 / 10 and False bool_three = False
# -(1 ** 2) < 2 ** 0 and 10 % 10 <= 20 - 10 * 2 bool_four = True
# True and True
bool_five = 2 + 2 <= 4 and 4 * 4 == 16
>>> or, which checks if at least one of the statements is True; as for such True + True = True , False + True = True , True + False = True , False + False = False
# EXAMPLE
# 2 ** 3 == 108 % 100 or 'Cleese' == 'King Arthur' bool_one = True
# True or False
bool_two = 4 + 2 < 7 or 84 == 43
# 100 ** 0.5 >= 50 or False bool_three = False
# True or True
bool_four = 23 == 23 or 43 == 43
# 1 ** 100 == 100 ** 1 or 3 * 2 * 1 != 3 + 2 + 1 bool_five = False
and / or is just the opposite
>>> not, which gives the opposite of the statement. if it was A = True, if it was NOT A = False, and vice versa
# EXAMPLE
# not True
bool_one = False
# not 3 ** 4 < 4 ** 3 bool_two = True
# not 10 % 3 <= 10 % 2 bool_three = True
# not 3 ** 2 + 4 ** 2 != 5 ** 2 bool_four = True
#not not False bool_five = False
(COMPUTER READABILITY)
>>> not is evaluated first;
>>> and is evaluated next;
>>> or is evaluated last.
True or not False and False returns [True].
Parentheses () ensure your expressions are evaluated in the order you want as for example :
- True and not (False or False) return [False]
- False or not (True and True) return [False]
'''
''' CONDITIONAL STATEMENT SYNTAX
if statement is a conditional statement that executes some specified code after checking if its expression is True.
Pay attention to the indentation before the print statement. This space, called white space, is how Python knows we are entering a new block of code. Python accepts many different kinds of indentation to indicate blocks. In this lesson, we use four spaces but elsewhere you might encounter two-space indentation or tabs (which Python will see as different from spaces).
If the indentation from one line to the next is different and there is no command (like if) that indicates an incoming block then Python will raise an IndentationError. These errors could mean, for example, that one line had two spaces but the next one had three. Python tries to indicate where this error happened by printing the line of code it couldn’t parse and using a ^ to point to where the indentation was different from what it expected.
In Python, the colon : is used to declare the start of an indented block. It is used primarily to enhance readability and to explicitly mark the beginning of a block of code that should be executed when a certain condition is met or a function is called. This concept aligns with the Python philosophy that "explicit is better than implicit The colon is used in several places in Python, including function definitions (def), control flow statements (if, elif, else), loops (for, while), and class declarations. In all these cases, the colon signifies the start of a block of code that will be executed under certain conditions
# EXAMPLE
def using_control_once():
if True:
return "Success #1"
def using_control_again():
if True:
return "Success #2"
print (using_control_once()) print (using_control_again())
# what you see here should be like this : i defined a function called using_control_once() when that function is true,
then it will print return the value that is Success #1 to the caller which is the using_control_once() then i print that function
''' ''' ELSE
# The else statement complements the if statement. An if/else pair says:
“If this expression is true, run this indented code block; otherwise, run this code after the else statement.” unlike if statement, else statement doesnt need an expression such as is it True or False
# EXAMPLE
answer = "'Tis but a scratch!"
def black_knight():
if answer == "'Tis but a scratch!":
return True else:
return False # Make sure this returns False def french_soldier():
if answer == "Go away, or I shall taunt you a second time!":
return True else:
return False # Make sure this returns False '''
''' ## COBA COBA AJA INI answer = input()
def halodek():
if answer == "yes":
print("ok bro") else:
print("kaga") print(halodek())
'''
''' 'ELIF' SHORT FOR ELSE IF
# elif is short for “else if.” It means exactly what it sounds like:
“otherwise, if the following expression is true, do this!”
# EXAMPLE
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1 else:
return 0
print greater_less_equal_5(4) print greater_less_equal_5(5) print greater_less_equal_5(6)
# by doing that, the 4, 5, and 6 is the value that will be printed to the answer argument, for example 4 > 5 then the answer < 5 then it will return -1 and so on
'''
''' # REVIEW 2 , PROJECT GRADE CONVERTER
The purpose of this function is to take a number grade (1-100), defined by the variable grade, and to return the appropriate letter grade (A, B, C, D, or F).
Your task is to complete the function by creating appropriate if and elif statements that will compare the input grade with a number and then return a letter grade.
Your function should return the following letter grades:
90 or higher should get an “A”
80 - 89 should get a “B”
70 - 79 should get a “C”
65 - 69 should get a “D”
Anything below a 65 should receive an “F”
def grade_converter(grade):
if grade >= 90:
return "A"
elif grade >= 80 and grade <= 89:
return "B"
elif grade >= 70 and grade <= 79:
return "C"
elif grade >= 65 and grade <= 69:
return "D"
else:
return "F"
# This should print an "A"
print grade_converter(92)
# This should print a "C"
print grade_converter(70)
# This should print an "F"
print grade_converter(61)
# this is the hardcode version def grade_converter():
grade = float(input("Enter a grade between 0 - 100 : ")) if grade >= 90:
return "A"
elif grade >= 80 and grade <= 89:
return "B"
elif grade >= 70 and grade <= 79:
return "C"
elif grade >= 65 and grade <= 69:
return "D"
else:
return "F"
print(grade_converter())
# its a input function version '''
''' PYGLATIN // INPUT FUNCTION
# a function to return the answer put by the user back to the caller
# EXAMPLE
print('Welcome to the Pig Latin Translator!')
# Start coding here!
original = input("Enter a word: ") # raw_input() in pyhton 2 and input() in python 3
if len(original) > 0:
print (original) else:
print("empty") '''
''' CHECKING IF THE VARIABLE IN THE STRING TYPE LETTER CONTAINS ALPHABET ONLY OR DIGIT ONLY
variable.isalpha() is for alphabet variable.isdigit() is for digit
# EXAMPLE
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = raw_input("Enter a word: ") # raw_input() in pyhton 2 and input() in python 3
if len(original) > 0 and original.isalpha():
print (original)
elif len(original) > 0 and original.isdigit():
print ("Name cannot contain number!") else:
print("empty")
# we can use [and] to add a second condition to the if statement '''
''' CUMA COBA COBA
original = input("input a word: ") word = original.upper()
first = word
#original = input('Enter a word:') def hello1():
if len(first) > 0 and first.isalpha():
print (first) else:
print ('empty') print(hello1())
# input function huruf gede
# atau ini yang nambahin huruf pertama diakhir kata lalu dilanjut sama 'ay' dan dalam low-case
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower() first = word[0]
new_word = word + first + pyg else:
print 'empty' print(new_word)
# ACCESS BY INDEX TO THE INPUT FUNCTION pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower() first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
# start from index 1 all the way to end if want a slice of the name go for [1:4] for example
else:
print 'empty' print(new_word) '''
''' DEFINE FUNCTION
# You might have considered the situation where you would like to reuse a piece of code, just with a few different values. Instead of rewriting the whole code, it’s much cleaner to define a function, which can then be used repeatedly.
# EXAMPLE
# this is a bill with tax and tip of a restaurant function def tax(bill):
"""Adds 8% tax to a restaurant bill."""
bill *= 1.08
print ("With tax: %f" % bill) return bill
def tip(bill):
"""Adds 15% tip to a restaurant bill."""
bill *= 1.15
print ("With tip: %f" % bill) return bill
meal_cost = 100
meal_with_tax = tax(meal_cost) meal_with_tip = tip(meal_with_tax) '''
''' FUNCTION DEF
# in a defined function there should be a 3 main component which is : the header that is def keyword followed by the function that created and the parameter of that function
, next is a comment to show what that function does
, next is a body that command what that function does by idented bellow the function that created same as conditional statement.
# EXAMPLE def spam():
# printing "Eggs!"
print ("Eggs!") spam()
'''
""" (n) AS ANY INSIDE THE PARANTHESES OF A FUNCTION def square(n):
# Returns the square of a number.
squared = n ** 2
print "%d squared is %d." % (n, squared) return squared
# Call the square function on line 10! Make sure to
# include the number 10 between the parentheses.
# by calling the function, square() and adding 10, im adding the value to the n that will be executed by the square function
# A function can have any number of parameters. The values of the parameters passed into a function are known as the arguments. Recall in the previous example, we called:
square(10)
"""
''' PARAMETERS AND ARGUMENT To summarize:
- When defining a function, placeholder [variables]
(https://www.codecademy.com/resources/docs/python/variables) are called parameters.
- When using, or calling, a function, inputs into the function are called arguments.
# you can add as many parameter as you want, but if it isnt n, then you need to idented all of it and use it all in the calling line such as def power(base, exponent): # Add your parameters here!
result = base ** exponent
print "%d to the power of %d is %d." % (base, exponent, result) power(37, 4) # Add your arguments here!
'''
''' FUNCTION CALLING FUNCTION
# We’ve seen functions that can print text or do simple arithmetic, but functions can be much more powerful than that. For example, a function can call another function:
# EXAMPLE
def one_good_turn(n):
return n + 1
def deserves_another(n):
return one_good_turn(n) + 2 print(deserves_another(23)) def cube (number):
# to the power of 3!
return number * number * number def by_three (number):
if number % 3 == 0:
return cube(number) else:
return ("its not divisible by 3!") print(by_three(21))
'''
''' GENERIC IMPORTS
# Remember [import this] from the first exercise in this course? That was an example of importing a module. A module is a file that contains definitions—including variables and functions—that you can use once it is imported.
# EXAMPLE
# Did you see that? Python said: NameError: name 'sqrt' is not defined.
Python doesn’t know what square roots are—yet.
#There is a Python module named math that includes a number of useful variables and functions, and sqrt() is one of those functions. In order to access math, all you need is the import keyword. When you simply import a module this way, it’s called a generic import.
import math
print (math.sqrt(25)) '''
''' FUNCTION IMPORT
# like a generic import we, import things from the module which is math, then if we want to implement it to a function we need to call [math.] again.
# but, with a [from] statement keyword we can import the module and the specific things we want, so we dont need to call it again.
# EXAMPLE
# from [module] import [function]
from math import sqrt z = sqrt(24)
print(z) '''
''' UNIVERSAL IMPORT
# but if we want to import everyting from math module, it would be tiresome too right?, well this is when asterisk symbol can be used
# EXAMPLE
from math import * print(sqrt(25))
# but when it comes to readablity, its hard to know which one which so, we better stick of with the [module.]
# to check all of the module function such as math, we can do this import math # Imports the math module
everything = dir(math) # Sets everything to a list of things from math print everything # Prints 'em all!
'''
''' BUILT-IN FUNCTION
# other than a module, some of a function were built-in to py. such as len(), str(), float(), print(), .upper(), .lower(), if and many other that we have previously use
# but thats for string, how about for more analytical things?
max() # The max() function takes any number of arguments and returns the largest one. (“Largest” can have odd definitions here, so it’s best to use max() on integers and floats, where the results are
straightforward, and not on other objects, like strings.)
# EXAMPLE
def maxi(*args):
print (max(args)) return max(args) maxi(31,23)
min() # The min() function takes any number of argument and returns the lowest one
# EXAMPLE
def min1(*args):
print (min(args)) return min(args) min1(23,432,-4)
abs() # The abs() function returns the absolute value of the number it takes as an argument—that is, that number’s distance from 0 on an imagined number line. For instance, 3 and -3 both have the same
absolute value: 3. The abs() function always returns a positive value, and unlike max() and min(), it only takes a single number.
# EXAMPLE
def distance_from_zero(arg):
print (abs(arg)) return abs(arg)
distance_from_zero(-21)
type() # Finally, the type() function returns the type of the data it receives as an argument. and return to the caller, what type of data it is (might be usefull for a boolean type of question)
# EXAMPLE
z = type("hello")
x = type(3) y = type(2.3) print(z) print(x) print(y)
# EXAMPLE 2
def distance_from_zero(a):
if type(a) == int or type (a) == float:
print(abs(a)) return (abs(a)) else:
print ("Nope") return abs(a)
distance_from_zero(-23.2)
NOTE if y'want to make an user input such as input() convert it to a float type because args only accept variable number value.
NOTE : THIS CODE IS WRONG def shut_down(s):
if s == "yes":
print ("Shutting down") return s
elif s == "no":
print ("Shutdown aborted") return s
else:
print("Sorry")
user_input = input("yes or no? ").lower() # we need to make a storage for the function, then the function's argument can acquire the variable (storage)
shut_down(user_input) # remember if you want to call the comman, call the function not the variable
# in this code, the elif and else is not executed, its because In Python, once a return statement is encountered during the execution of a function, the function terminates immediately and sends the return value back to the caller. As a result, any code written after a return statement within the same block will not be executed
'''
''' REVIEW - CONCATENATING DEFINED FUNCTION def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car_cost(days):
cost = days * 40 if days >= 7:
cost -= 50 elif days >= 3:
cost -= 20 return cost
def trip_cost(city, days, spending_money):
return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(city) + spending_money
print(trip_cost("Los Angeles", 5, 600 )) '''
''' LIST
# Lists are a datatype you can use to store a collection of different pieces of information as a sequence under a single variable name.
(Datatypes you’ve already learned about include strings, numbers, and booleans.)
# EXAMPLE
zoo_animals = ["pangolin", "cassowary", "sloth","capybara" ]
# One animal is missing!
if len(zoo_animals) > 3:
print ("The first animal at the zoo is the " + zoo_animals[0]) print ("The second animal at the zoo is the " + zoo_animals[1]) print ("The third animal at the zoo is the " + zoo_animals[2]) print ("The fourth animal at the zoo is the " + zoo_animals[3])
# You can access an individual item on the list by its index. An index is like an address that identifies the item’s place in the list. The index appears directly after the list name, in between brackets, like this: list_name[index]. the counter starts from 0 not 1
# We can also change the value of a index on the list
# EXAMPLE
zoo_animals[2] = "hyena"
# to add more items into the list without adding it to the list, we can do this
#EXAMPLE
suitcase = ["hell"]
suitcase.append("suit")
print(suitcase[1]) # it will print suit
# we can also slice or pick only some items in the list
# EXAMPLE
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
# The first and second items (index zero and one) first = suitcase[0:2]
# Third and fourth items (index two and three) middle = suitcase[2:4]
# The last two items (index four and five) last = suitcase[4:6]
# SLICING STRINGS THROUGH LIST INDEX
# EXAMPLE
animals = "catdogfrog"
# The first three characters of animals cat = animals[:3]
# The fourth through sixth characters dog = animals[3:6]
# From the seventh character to the end
frog = animals[6:10] # 6 is index 7, because we count from 0, but the 10 is 10 because we count from 1
#in this example, as you can see, the first index of a variable is the number indices before the character you want to pick, and after that the second index is the indices of that character
# SEARCHING INDEX AND CHANGING POSITION OF LIST
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # Use index() to find "duck"
print(duck_index) #this will search on what index is "duck"
# Your code here!
animals.insert(duck_index, "cobra") #this will change where duck was into a cobra, and duck is backwarding 1 indices
print (animals) # Observe what prints after the insert operation '''
''' FOR LOOP
# If you want to do something with every item in the list, you can use a for loop.
# Then in my_list designates my_list as the list the loop will work on.
The line ends with a colon (:) and the indented code that follows it will be executed once per item in the list.
# EXAMPLE
for number in my_list:
# Your code here print(2*number)
# we can also use .sort() if our list is a mess, it sort through an alphabetical from the start of the strings, or a number
# EXAMPLE
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here!
for number in start_list:
square_list.append(number ** 2) square_list.sort()
print (square_list)
NOTE : If you want to changing the items in the list refered to the for loop, use [number] as it is the instances you called
DICTIONARY
# A dictionary is similar to a list, but you access values by looking up a key instead of an index. A key can be any string or number.
Dictionaries are enclosed in curly braces, like so:
d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
# This is a dictionary called d with three key-value pairs. The key 'key1' points to the value 1, 'key2' to 2, and so on.
#Dictionaries are great for things like phone books (pairing a name with a phone number), login pages (pairing an e-mail address with a username), and more!
# Like Lists, Dictionaries are mutable. This means they can be changed after they are created. One advantage of this is that we can add new key/value pairs to the dictionary after it is created
# The length len() of a dictionary is the number of key-value pairs it has. Each pair counts only once, even if the value is a list. (That’s right: you can put lists inside dictionaries!)
# EXAMPLE
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
# Your code here: Add some dish-price pairs to menu!
menu['somme'] = 13 menu["hell"] = 13.31 menu["heaven"] = 13.31
print "There are " + str(len(menu)) + " items on the menu."
print menu
MODIFYING DICTIONARIES
# to modify dictionary we can change the value but not the key, and we can delete a key with its value, this might be usefull
# EXAMPLE
# key - animal_name : value - location
zoo_animals = { 'Unicorn' : 'Cotton Candy House', 'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House', 'Atlantic Puffin' : 'Arctic Exhibit', 'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines
# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.) del zoo_animals['Unicorn']
# Your code here!
del zoo_animals["Bengal Tiger"]
del zoo_animals["Sloth"]
zoo_animals["Rockhopper Penguin"] = "Volcanic Mountain"
print zoo_animals
NOTE : use square bracket for everything and curly bracket only for the dictionary, as the dictionary has a higher hierarcy than list i guess DELETING IN A LIST
# same as a dictionary a list items can also be deleted as such
# EXAMPLE
backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger') print(backpack)
'''
''' MODIFYING DICTIONARIES PART 2
# in this code, we delete a list inside dictionary, and adding value into one of the dictionary's key, and sorting a key inside the
dictionary inventory = {
'pocket' : ['seashell', 'strange berry', 'lint'], 'gold' : 550,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}
inventory['backpack'].remove('dagger') inventory['backpack'].sort()
# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
inventory['gold'] = inventory['gold'] + 50
# Sorting the list found under the key 'pouch' inventory['pouch'].sort()
print(inventory)
# Your code here '''
''' FOR LOOPS #PART 2
# for loops allow us to iterate through all of the elements in a list from the left-most (or zeroth element) to the right-most element
a = ["List", "of", "some", "sort"]
for item in a:
# or this
for item in [1, 3, 21]:
print item
# Do something for every item
# This loop will run all of the code in the indented block under the for x in a: statement. The item in the list that is currently being evaluated will be x
# The variable between for and in can be set to any variable name (currently item), but you should be careful to avoid using the word list as a variable, since that’s a reserved word (that is, it means something special) in the Python language.
'''
''' DICTIONARY #2
#You can also use a for loop on a dictionary to loop through its keys with the following:
# A simple dictionary d = {"foo" : "bar"}
for key in d:
print d[key] # prints "bar"
# Note that dictionaries are unordered, meaning that any time you loop through a dictionary, you will go through every key, but you are not guaranteed to get them in any particular order.
'''
''' FLOW CONTROL
# The blocks of code in a for loop can be as big or as small as they need to be.
# While looping, you may want to perform different actions depending on the particular item in the list.
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for num in a:
if num % 2 == 0:
print num
# in here we create a conditional statement whereas if the num in the list is even it could be printed
'''
''' ADDING FUNCTION IN TO FOR LOOPS
# Functions can also take lists as inputs and perform various operations on those lists.
def count_small(numbers):
total = 0
for n in numbers:
if n < 10:
total = total + 1 return total
lotto = [4, 8, 15, 16, 23, 42]
small = count_small(lotto) print (small)
# In the above example, we define a function count_small that has one parameter, numbers.
# We initialize a variable total that we can use in the for loop.
# For each item n in numbers, if n is less than 10, we increment total.
# After the for loop, we return total.
# After the function definition, we create an array of numbers called lotto.
# We call the count_small function, pass in lotto, and store the returned result in small.
# Finally, we print out the returned result, which is 2 since only 4 and 8 are less than 10.
# EXAMPLE fizz_count = [ 'fizz', 'hex',
'zen', 'fizz', 'horrified', ]
def fizz_counter(num1):
counter1 = 0 for rar in num1:
if rar == 'fizz':
counter1 += 1 return counter1
rex = fizz_counter(fizz_count) print(rex)
# this is a string counter '''
''' STRING LOOPING
# strings are like lists with characters as elements. You can loop through strings the same way you loop through lists!
# EXAMPLE
for letter in "Codecademy":
print letter
# Empty lines to make the output pretty print
word = "Programming is fun!"
for letter in word:
# Only print out the letter i if letter == "i":
print letter '''
''' USING A DIFFRENT DICTIONARY IN FOR LOOP
# EXAMPLE
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
for food in prices:
if food == 'apple':
print food
print "price: %s" % prices['apple']
print "stock: %s" % stock['apple']
'''
''' CALCULATING EACH VALUE IN 2 DICTIONARY prices = {
"banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3, }
stock = {
"banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15, }
for key in prices:
total = 0
total = float(prices[key] * stock[key]) print "total value: %s" % total
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
'''
''' PRINTING TOTAL VALUE IN 2 DICTIONARY prices = {
"banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3, }
stock = {
"banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15, }
total = 0 #The variable container for total has to be outside so it doesnt get looped to zero again after each calculation for key in prices:
total += prices[key] * stock[key]
#thisline indicate that each total has to be multiplied by each other, and to return to the real variable (outside the loop, everything has to be added alltoghether)
print ("value of this items: %s" % total) print (key)
print ("price: %s" % prices[key]) print ("stock: %s" % stock[key])
print ("total cost value of all item is: %s" % total) #The print total has to be outside the for loop to indicate the total from for loop function
'''
''' CREATING A SHOPPING LIST THAT NEED TO BE BUYED, AND CALCULATED THE PRICE OF THE CHOOSEN ITEM INSIDE A LIST
shopping_list = ["banana", "orange", "apple"]
stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 }
prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 }
# Write your code below!
def compute_bill(food, prices, stock):
total = 0
for nums in food:
total = prices[food] * stock[food]
return total
print (compute_bill(shopping_list[2], prices, stock)) '''
''' DECREASING STOCK
# Now you need your compute_bill function to take the stock/inventory of a particular item into account when computing the cost.
# Ultimately, if an item isn’t in stock, then it shouldn’t be included in the total. You can’t buy or sell what you don’t have!
shopping_list = ["banana", "orange", "apple"]
stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 }
prices = { "banana": 4, "apple": 2,
"orange": 1.5, "pear": 3 }
# Write your code below!
def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total += prices[item]
stock[item] -= 1 return total
print(compute_bill(shopping_list)) NOTE : EXPLANATION BELLOW
# The total cost becomes 5.5 due to the operations performed in the compute_bill function. Let's break down what happens:
The function loops through each item in the food list.
For each item, it checks if the stock count of the item is greater than zero.
If the stock count is greater than zero, it adds the price of the item to the total and subtracts one from the item's stock count.
Let's go through each item in the shopping_list:
Banana: The stock count is 6, which is greater than zero. So, the function adds the price of banana (4) to the total, making the total 4.
It also subtracts one from the banana's stock count, making the stock count 5.
Orange: The stock count is 32, which is greater than zero. So, the function adds the price of orange (1.5) to the total, making the total 5.5. It also subtracts one from the orange's stock count, making the stock count 31.
Apple: The stock count is 0, which is not greater than zero. So, the function does not add the price of apple to the total. The total remains 5.5.
Therefore, the total cost of the items in the shopping_list is 5.5 '''
''' PROJECT CLASS GRADE lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
# Add your function below!
def average(numbers):
total = sum(numbers) total = float(total) return total/len(numbers) def get_average(student):
homework = average(student["homework"]) quizzes = average(student["quizzes"]) tests = average(student["tests"])
return 0.1 * homework + 0.3 * quizzes + 0.6 * tests def get_letter_grade(score):
score = int(score) if score >= 90:
return "A"
elif score >= 80 and score <= 89:
return "B"
elif score >= 70 and score <= 79:
return "C"
elif score >= 60 and score <= 69:
return "D"
else:
return "E"
# this print out the avarage score of each individual print(get_average(tyler))
print(get_letter_grade(get_average(tyler))) print(get_average(lloyd))
print(get_letter_grade(get_average(lloyd))) print(get_average(alice))
print(get_letter_grade(get_average(alice)))
def get_class_average(class_list):
results = []
for student in class_list:
student_avg = get_average(student)
results.append(student_avg) return average(results)
students = [alice, lloyd, tyler]
# this is the class grade
print(get_letter_grade(get_class_average(students))) '''
''' LIST ACCESSING/ MODIFYING/ REVIEWING 1. n = [1, 3, 5]
# Add your code below
print(n[1]) # will print n on index 1 list which is 3 2. n = [1, 3, 5]
# Do your multiplication here
n[1] = n[1] * 5 # will multiply index 1 on n list by 5 print n
3. n = [1, 3, 5]
# Append the number 4 here
n.append(4) # will adding 4 as int value to 3rd index of n print n
4. n = [1, 3, 5]
# Remove the first item in the list here
#n.pop(0) # will delete a value from a list by index and return it
#del(n[1]) # will delete a value from a list by index but not return it
#n.remove(5) # will delete a value from a list by a litteral value 5. #Passing a list to a function will store it in the argument (just like with a string or a number!)
def list_function(x):
return x[1]
n = [7, 2, 7, 5, 1]
print list_function(n)
6. # Modifying an element in a list in a function is the same as if you were just modifying an element of a list outside a function.
def list_function(x):
x[1] += + 3 return x
n = [7, 2, 7, 5, 1]
print list_function(n) print n
7. # You can also append or delete items of a list inside a function just as if you were manipulating the list outside a function.
n = [3, 5, 7]
# Add your function here def list_extender(lst):
lst.append(9) return lst
print list_extender(n) '''
''' RANGE FUNCTION
# The Python range() function is just a shortcut for generating a list, so you can use ranges in all the same places you can use lists.
range(6) # => [0, 1, 2, 3, 4, 5]
range(1, 6) # => [1, 2, 3, 4, 5]
range(1, 6, 3) # => [1, 4]
# The range() function in Python generates a sequence of numbers, starting from the first argument (if provided), up to but not including the second argument. The third argument specifies the increment (also known as the step) between each number in the sequence.
In the case of range(1, 6, 3), the function starts at 1 (because 1 is the first argument), stops before 6 (because 6 is the second argument), and increments by 3 at each step (because 3 is the third argument).
so, the sequence generated by range(1, 6, 3) would be: 1, 4. This is because 1 is less than 6, so it's included in the sequence. Then, 1 plus 3 equals 4, which is still less than 6, so it's also included in the sequence. After that, 4 plus 3 equals 7, which is greater than 6, so the sequence stops.
The range function has three different versions:
range(stop)
range(start, stop)
range(start, stop, step)
In all cases, the range() function returns a list of numbers from start up to (but not including) stop. Each item increases by step. If
omitted, start defaults to 0 and step defaults to 1.
'''
''' Iterating over a list in a function
Now that we’ve learned about range, we have two ways of iterating through a list.
Method 1 - for item in list:
for item in list:
print item
Method 2 - iterate through indexes:
for i in range(len(list)):
print list[i]
Method 1 is useful to loop through the list, but it’s not possible to modify the list this way.
Method 2 uses indexes to loop through the list, making it possible to also modify the list if needed. Since we aren’t modifying the list, feel free to use either one on this lesson!
# EXAMPLE n = [3, 5, 7]
def total(numbers):
result = 0
for items in range (3, len(n)):
print (items) return numbers print(total(n))
# or to iterate through all the numbers n = [3, 5, 7]
def total(numbers):
result = 0
for i in range(0,len(numbers)): # so in here i guess if you counting from 0 as index untill it reach the end of the index on the list
result += numbers[i]
return result print(total(n)) '''
''' Using strings in lists in functions n = ["Michael", "Lieberman"]
# Add your function here def join_strings(words):
result = ""
for word in words:
result += word return result
print join_strings(n)
# this code iterate through all of in the list '''
''' Concatenating two argument from a list in a function m = [1, 2, 3]
n = [4, 5, 6]
# Add your code here!
def join_lists(x, y):
return x +y
print join_lists(m, n)
# You want this to print [1, 2, 3, 4, 5, 6]
'''
''' A LIST INSIDE LIST
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here def flatten(lists):
results = [] # An empty list results is initialized. This list will store the flattened list.
for numbers in lists: # The function enters a loop where numbers represents each sublist in lists.
for number in numbers: # Within this loop, another loop is initiated where each number represents an item in the current sublist (numbers).
results.append(number) # Each number is appended to the results list using the append() method.
return results # After all items in all sublists have been appended to results, the function returns results.
print (flatten(n)) '''
''' Uniting indexes in a list
# now that you know how to flatten a list, time to uniting the indexes inside a list
zen = ['o', 'o', 'o', 'o']
print(" ".join(zen)) # will print : o o o o
print("---".join(zen)) # will print : o---o---o---o
print(zen) # will print : ['o', 'o', 'o', 'o']
'''
''' RANDOM MODULE
from random import randint
coin = randint(0, 1) # will create a instance of 1 or 0 randomly
dice = randint(1, 6) # will create a instance of 1 inclusive 6 randomly
'''
''' BATLESHIP PROJECT
NOTE : I STILL DONT KNOW HOW THE FUCK THIS SHIT WORK, I MADE A MISTAKE WHERE I CAN ONLY PLACE 1 X AND IT DOESNT CHANGE, THEN THE THING IS SCRAMBLED AF, THE FAILED CODE IS IN FAIL.py
# PLEASE COMMENT EVERY LINE FOR WHAT IT DOES!
from random import randint board = []
for x in range(0, 5):
board.append(["O"] * 5) def print_board(board):
for row in board:
print (" ".join(row)) print_board(board)
def random_row(board):
return randint(0, len(board[0]) - 1) def random_col(board):
return randint(0, len(board[0]) - 1) ship_row = random_row(board)
ship_col = random_col(board)
#print (ship_row)
#print (ship_col)
# Everything from here on should be in your for loop
# don't forget to properly indent!
for turn in range(4):
print ('Turn', turn + 1)
guess_row = int(input("Guess Row: ")) guess_col = int(input("Guess Col: "))
if guess_row == ship_row and guess_col == ship_col:
print ("Congratulations! You sank my battleship!") break
else:
if guess_row not in range(5) or \ guess_col not in range(5):
print ("Oops, that's not even in the ocean.") elif board[guess_row][guess_col] == "X":
print ("You guessed that one already." )
else:
print ("You missed my battleship!") board[guess_row][guess_col] = "X"
if turn == 3:
print ("Game Over")
print ("the battleship is on: ") print("row : " + str(ship_row)) print("column : " + str(ship_col)) break
print_board(board) '''
''' WHILE
# The while loop is similar to an if statement: it executes the code inside of it if some condition is true. The difference is that the while loop will continue to execute as long as the condition is true.
In other words, instead of executing if something is true, it executes while that thing is true.
NOTE : Be careful not to alter or remove the counting statement. If your program has no way to increase count, your loop could go on forever and become an infinite loop which could crash your
computer/browser!
# EXAMPLE count = 0 if count < 5:
print "Hello, I am an if statement and count is", count while count < 10:
print "Hello, I am a while and count is", count count += 1
'''
''' CONDITION
# The condition is the expression that decides whether the loop is going to continue being executed or not.
# IN THE CONDITION STEPS THERE ARE 5 RULES:
- The loop_condition variable is set to True in order to be executed by default
- The while loop checks to see if loop_condition is True. It is, so the loop is entered.
- The code statement is executed. when the condition met the requirement
- The variable loop_condition can be set to False.
- The while loop again checks to see if loop_condition is True. It is not, so the loop is not executed a second time.
# EXAMPLE
loop_condition = False
while loop_condition == False:
print "I am a loop"
loop_condition = True
# EXAMPLE 2 WHILE CONDITIONAL - EXPONENTIAL
num = 1 # THE DEFAULT VALUE OF num CONTAINER IS 1
while num <= 10: # Fill in the condition # WHILE THIS CONDITION IS MET WHICH IS num LESS THAN OR EQUAL TO 10
# Print num squared
print(num ** 2) # THIS STATEMENT WILL BE PRINTED (VISUALLY, WHICH MEAN ITS NOT ADDING THE REAL VALUE OF NUM ) num += 1 # THIS LINE ADDING THE VALUE OF num BY 1 EVERYTIME THE LOOP DONE FOR EACH TIME, UNTIL IT ADD THE num VALUE TO 11 THEN THE CONDITION IS NOT MET ANYMORE.
# Increment num (make sure to do this!) '''
''' SIMPLE ERROR
# IN THIS EXAMPLE, IT IS A USER INPUT CODE, AND THE QUESTION IS ONLY Y/N, IF THE USER DOESNT INPUTING BETWEEN Y/N, PTOMPT WILL BE GIVEN AGAIN
choice = raw_input('Enjoying the course? (y/n)')
while choice != "y" and choice != "n": # Fill in the condition (before the colon)
choice = raw_input("Sorry, I didn't catch that. Enter again: ") '''
''' BREAK
The break is a one-line statement that means “exit the current loop.”
An alternate way to make our counting loop exit and stop executing is with the break statement.
First, create a while with a condition that is always true. The simplest way is shown.
Using an if statement, you define the stopping condition. Inside the if, you write break, meaning “exit the loop.”
The difference here is that this loop is guaranteed to run at least once.
count = 0 def surely(f):
count = 0 while True:
print (count) count += 1 if count >= 10:
break surely(count) '''
''' WHILE / ELSE
# Something completely different about Python is the while/else construction. while/else is similar to if/else, but there is a
difference: the else block will execute anytime the loop condition is evaluated to False. This means that it will execute if the loop is never entered or if the loop exits normally. If the loop exits as the result of a break, the else will not be executed.
# In this example, the loop will break if a 5 is generated, and the else will not execute. Otherwise, after 3 numbers are generated, the loop condition will become false and the else will execute.
import random
print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"
count = 0
while count < 3:
num = random.randint(1, 6) print num
if num == 5:
print "Sorry, you lose!"
break count += 1 else:
print "You win!"
'''
''' RANDOM NUMBER INPUT + WHILE LOOP from random import randint
# Generates a number from 1 through 10 inclusive random_number = randint(1, 10)
guesses_left = 3
# Start your game!
while guesses_left > 0:
guess = int(raw_input("Your guess: ")) if guess == random_number:
print("You win!") break
else:
guesses_left -= 1
print(str(("Go, and try again, your guesses left : %s" % guesses_left)))
else:
print("You lose!") '''
''' CREATING A FOR LOOP (filling an empty list with for loop to print user input)
hobbies = []
for i in range (3):
hobbies.append(input("Input three of your hobby: ")) print(hobbies)
# or if i want to save the value after appending to the empty list, i could do this
hobbies = []
for i in range (3):
truer = (input("Input three of your hobby: ")) hobbies.append(truer)
print(hobbies) '''
''' USING FOR LOOP IN STRING TO MAKE ITERATION OF EACH WORD
# IN A SINGLE LINE thing = "spam!"
for c in thing:
print (f"{c}") print("\n") word = "eggs!"
for c in word:
print (c)
# IN ONE LINE
# use the , comma symbol after print, in this case we printing the phrase value when there's no A or a str type,
but when there are, we print char and deleting the true condition literal string with X
NOTE : THIS ON PYTHON 2
phrase = "A bird in the hand..."
# Add your for loop for char in phrase:
if char == "A" or char == "a":
print "X", else:
print char,
NOTE : THIS ON PYTHON 3
phrase = "A bird in the hand..."
# Add your for loop for char in phrase:
if char == "A" or char == "a":
print ("X", end= " ") else:
print (char, end=" ")
#Don't delete this print statement!
print '''
''' FOR LOOPS ( LIST )
# The usual use of for loops is to looping through a list, in such a way, On each iteration, the variable num will be the next value in the list.
So, the first time through, it will be 7, the second time it will be 9, then 12, 54, 99, and then the loop will exit when there are no more values in the list.
numbers = [7, 9, 12, 54, 99]
print "This list contains: "
for num in numbers:
print num
# Add your loop below!
for num in numbers : print num ** 2 '''
''' FOR LOOP ( DICTIONARY )
# When we looping through dictionary the print statement will generate the key value, but we access it through the value of it or vice versa.
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
for key in d:
# Your code here!
if d[key] == "berry":
print key # will print the key print d[key] # will print the value
# we can use comma in between the key and d[key] to print both the key and value on the same line.
# or you could use the regular parameter for the print statement.
# remember that's a conditional statement that will print each of the key or value if only the value is on the condition, if we want to just print all of it :
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
for key in d:
# Your code here!
print key, d[key]
'''
''' ENUMERATING LOOPS
# A weakness of using this for-each style of iteration is that you don’t know the index of the thing you’re looking at. Generally this isn’t an issue, but at times it is useful to know how far into the list you are. Thankfully the built-in enumerate function helps with this.
# Enumerate works by supplying a corresponding index to each element in the list that you pass it. Each time you go through the loop, index will be one greater, and item will be the next item in the sequence.
It’s very similar to using a normal for loop with a list, except this gives us an easy way to count how many items we’ve seen so far.
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices, start=412): # Start=412 indicate the starting point of the count
print index + 1, item # index + 1 indicate that item that will be enumerated will be +1 for each count '''
''' MULTIPLE LIST (ZIP FUNCTION)
# It’s also common to need to iterate over two lists at once. This is where the built-in zip function comes in handy.
# zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
# zip can handle three or more lists as well!
# EXAMPLE
# In this code a reffer to list_a, and b reffer to list_b list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
# print(max(a, b)) # i can use max function alternatively to see which list is larger or i can use if/else
statement in the bellow if a > b:
print (a) else:
print (b)
# Add your code here!
'''
''' FOR/ELSE
# Just like with while, for loops may have an else associated with them.
# In this case, the else statement is executed after the for, but only if the for ends normally—that is, not with a break. This code will break when it hits 'tomato', so the else block won’t be executed.
# EXAMPLE
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print ('You have...') for f in fruits:
if f == ('tomato'):
print ('A tomato is not a fruit!') # (It actually is.)
print ('A', f) else:
print ('A fine selection of fruits!')
# If we use break in this code, it will stop at tomato and will not print pear, grape and the else statement.
EXAMPLE 2
all_sword = ["Heaven Slasher", "Hell's Dawn", "Earth's GREATEST Champion", "Hologram Sword", "Rusty Sword", "Low-Tier Sword"]
print ("Collect all of the legendary sword") for x in all_sword:
print (x)
if x == "Rusty Sword":
print ("That's a trash sword") elif x == "Low-Tier Sword":
print ("That's a trash sword") else:
print ("that's all the legendary sword")
NOTE : The best way to get good at anything is a lot of practice. This lesson is full of practice problems for you to work on. Each exercise will contain minimal instructions to help you solve these problems. The goal is to help you take your programming skills and apply them to real life problems.
'''
''' CHECKING IF AN INPUT IS A TYPE INT OR FLOAT def is_int(x):
absolute = abs(x)
rounded = round(absolute) return absolute - rounded == 0 print is_int(10)
print is_int(10.5)
# alternatively i could use if x == isinstance(x, int):
return True according to phind '''
''' RETURNING SUM OF NUMBER EACH BY EACH OF NUM def digit_sum(n):
total = 0
string_n = str(n) # THIS LINE REQUIRED TO PASSING INPUT INTO STRING SO THAT IT CAN BE ITERATE (DITAMBAHKAN)
for nums in string_n: # THIS LINE READ EACH OF CHAR IN THE VARIABLE
total += int(nums) # THIS LINE CONVERTING THE STRING BACK TO INT THEN ADDING THE INT ONE BY ONE
return total
print (digit_sum(213))
# alternative ways def digit_sum(n):
total = 0 while n > 0:
total += n % 10 n = n // 10 return total
Initialize total = 0.
# STEP BY STEP LOOP ON THIS
# Enter the loop with n = 1234. Add 1234 % 10 (which is 4) to total, making total = 4. Then update n to 1234 // 10 (which is 123).
# Repeat the process with n = 123. Add 123 % 10 (which is 3) to total, making total = 7. Then update n to 123 // 10 (which is 12).
# Repeat again with n = 12. Add 12 % 10 (which is 2) to total, making total = 9. Then update n to 12 // 10 (which is 1).
# Finally, with n = 1, add 1 % 10 (which is 1) to total, making total = 10. Then update n to 1 // 10 (which is 0), ending the loop.
# Return total, which is 10.
print (digit_sum(1234)) '''
''' FACTORIAL NUM
# we can use import math then factorial(x) as alternative
# or
def factorial(x):
total = 1 while x > 0:
total *= x x -= 1 return total print(factorial(201)) '''
''' PRIME NUMBER def is_prime(x):
if x < 2:
return False else:
for n in range(2, x-1):
if x % n == 0:
return False return True
print is_prime(13) print is_prime(10) '''