New Line, Concatenate, Variable
print("Hello World!")
Hello World!
print("Day 1 - Python Print Function")
print("The function is declared like this")
print("print('what to print')")
Day 1 - Python Print Function The function is declared like this print('what to print')
print("Day 1 - Python print function\nThe function is declared like this\nprint('what to print?')")
Day 1 - Python print function The function is declared like this print('what to print?')
print('Day 1 - String Manipulation\nString Concatenation is done with the "+" sign.\ne.g. print("Hello" + "world")\nNew lines can be created with a backslash and n.')
Day 1 - String Manipulation String Concatenation is done with the "+" sign. e.g. print("Hello" + "world") New lines can be created with a backslash and n.
print("Teni is a loving peron\nwhy wouldn't you love her?")
Teni is a loving peron why wouldn't you love her?
print("Thank you, " + input("What is your name? ") + "!")
What is your name?Teni Thank you, Teni!
print(len(input("What is your name? ")))
What is your name? TenifayoOlutade 15
A = input("Enter a word:\nI'll return the count")
print(len(A))
print("Hello Aunty, how're you doing?\nIt's nice to meet you" + input("What's your name?"))
What's your name?Teni Hello Aunty, how're you doing? It's nice to meet youTeni
from re import A
a= input("a: ")
b = input("b: ")
c = a
a = b
b = c
print("a = " + b)
print("b = " + a)
a: 5 b: 6 a = 5 b = 6
print("Welcome to the Band Name Generator.")
name = input("What's the name of the city you grew up in?")
pet = input("What's your pet's name? ")
print("Your band name could be " + name + " "+ pet)
Welcome to the Band Name Generator. What's the name of the city you grew up in?Lagos What's your pet's name? Obas Your band name could be Lagos Obas
Subscripting & Data Types
print("Hello"[4])
o
Note
print(type("123)"))
<class 'str'>
name = input(("What is your name? "))
len_name = len(name)
new_name = str(len_name)
print(name + ", Your name has " + new_name + " characters.")
What is your name? Tenifayo Tenifayo, Your name has 8 characters.
print(70 + 105)
175
print(70 + float("10222"))
10292.0
print(str(70) + str(100))
70100
print(type("1092887jhhg"))
<class 'str'>
a = input("Enter a number ")
b = input("Enter another number ")
print( int(a) + int(b))
Enter a number 9 Enter another number 8 17
# OR
num = input("Type a two digit number ")
# Using Substring to get the indexed number and then convert to Int, afterwards
first_number = (num[0])
second_number = (num[1])
# Chnage the data type...using a cast
result = int(first_number) + int(second_number)
print(result)
Type a two digit number 66 12
Following the PEMDAS_LR rule. The mathematical oeprations are worked on in the order of priority starting with:
w = input("Enter your weight: ")
h = input("Enter your height: ")
r = int(w)/int(h) * int(h)
print(r)
Enter your weight: 67 Enter your height: 27 67.0
w = input("Enter your weight: ")
h = input("Enter your height: ")
r = int(w)/int(h)**2
# to print the result as a float then data cast the result
r= int(r)
print(r)
Enter your weight: 4 Enter your height: 3 0
Returns the Whole number of a fraction division
Returns the fraction from a given division
(Fraction or operation, number of decimal places to be rounded to). print(round(2.88889897766555, 3)) or print(round(8/3, 3))
Used to include mathematical operation as a sequence to an existing mathematical variable.
e.g: score = 25 score +=20 print(score +=25) Ans: 45
print(8/3)
2.6666666666666665
print(round(8/3, 2))
2.67
print(round(2.666666666666666, 2))
2.67
print(8//3)
2
score = 25
score +=79
print(score)
104
Fstring:
Also us print Strings with Other data type- as a concatenation.
Where there'll be a datatype error is I'm to print out sth like this:
score = 20
print("Your score is" + score)
i.e. new_score = str(score)
print("Your score is " + new_score)
But with fstring all I need do is add the score in a curly bracket....like so; and have the letter f in front of the quotation mark.
print(f"Your score is {score})"
score = 20
new_score = str(score)
print("Your score is " + new_score)
Your score is 20
# with the Fstring
score = 25
height = 1.9
Winning = True
print(f"Your score is {score}, your height is {height}, your are winning is {Winning}, Cheers!")
Your score is 25, your height is 1.9, your are winning is True, Cheers!
age = input("What is your current age? ")
new_age = int(age)
years = 100 - new_age
months = years * 12
days = round (years * 365, 0)
weeks = round (days * 52, 0)
print(f"You have {years} years, {months} months, {weeks} weeks, and {days} days left")
What is your current age? 28 You have 72 years, 864 months, 1366560 weeks, and 26280 days left
print("Welcome to the tip calculator!")
bil = input("What was the total bill? $")
bill = float(bil)
ti = input("What percentage tip would you like to give? 10, 12 0r 15?")
tip = int(ti)
tip /=100
num_of_people = input("How many of you are splitting the bill? ")
num = int(num_of_people)
result1 = bill + (bill * t hi ip)
result2 = round(result1/num, 2)
print(f"Each person should pay: ${result2}")
Welcome to the tip calculator! What was the total bill? $300 What percentage tip would you like to give? 10, 12 0r 15?15 How many of you are splitting the bill? 2 Each person should pay: $172.5
print('Welcome to the Rollercoaster!')
Height = int(input("Enter your height in cm: "))
if Height >= 120:
print("Go ahead! You can ride the Rollercoaster")
else:
print("Oops! You'd have to grow taller before you can ride.")
Welcome to the Rollercoaster! Enter your height in cm: 121 Go ahead! You can ride the Rollercoaster
7%2
1
7 // 2
3
number = int(input("Enter a number: "))
if number % 2 != 0:
print("This is an odd number")
else:
print("This is an even number")
# OR
Enter a number: 22 This is an even number
number = int(input("Enter a number: "))
if number % 2 == 0:
print("This is an even number")
else:
print("This is an odd number")
Enter a number: 24 This is an even number
print("Welcome to the RollerCoaster! We're glad to have you here")
height = int(input("Enter your height in cm: "))
if height >= 120:
age = int(input("How old are you? "))
if age > 18:
print("Pay $12 to the cashier and go ahead to roller coast! :)")
else:
print("Pay $7 to the cashier and go ahead to roller coast! :)")
else:
print("Sorry! You'd need to grow taller :(")
# The conditions of IF or ELSE MUST BE on the same block line of indentation
Welcome to the RollerCoaster! We're glad to have you here Enter your height in cm: 121 How old are you? 19 Pay $12 to the cashier and go ahead to roller coast! :)
print("Welcome to the RollerCoaster! We're glad to have you here")
height = int(input("Enter your height in cm: "))
if height >= 120:
age = int(input("How old are you? "))
if age < 12:
print("Pay $5 to the cashier and go ahead to roller coast. Enjoy your ride! :)")
elif age >= 12 and age <= 18:
# The above is to represent age 12-18
print("Pay $7 to the cashier and go ahead to roller coast. Enjoy your ride! :)")
else:
print("Pay $12 to the cashier and go ahead to roller coast. Enjoy your ride! :)")
else:
print("Sorry, you'd need to grow taller to roller coast. :(")
Welcome to the RollerCoaster! We're glad to have you here Enter your height in cm: 124 How old are you? 7 Pay $5 to the cashier and go ahead to roller coast. Enjoy your ride! :)
print("Welcome to the BMI Interpreter")
height = float(input("Please, enter your height in cm: "))
weight = float(input("Please, ebter your weight in cm: "))
result = round(weight/height ** 2, 1)
if result <= 18.5:
print(f"Your BMI score is {result}\nThis interprets to an Underweight")
elif result < 25:
# This still addresses between from 18.5 to less than 25 because the above condition already addresses the from and below 18.5
print(f"Your BMI score is {result}\nThis interprets to a Normal weight")
elif result < 30:
print(f"Your BMI score is {result}\nThis interprets to an Overweight")
elif result < 35:
print(f"Your BMI score is {result}\nThis interprets to Obesity")
else:
print(f"Your BMI score is {result}\nThis interprets to a Clinical Obesity")
Welcome to the BMI Interpreter Please, enter your height in cm: 5.0 Please, ebter your weight in cm: 55 Your BMI score is 2.2 This interprets to an Underweight
Difference between == and =
## The difference betwen '==' and '=' "
check = int(input("Enter your age: "))
if check == 20:
print("You're a genius!")
elif check < 20:
print("You're a Rockstar")
else:
print("You're a Superstar!")
Enter your age: 22 You're a Superstar!
Leap Year Task:
Write a program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February. The reason why we have leap years is really fascinating, this video does it more justice:
This is how you work out whether if a particular year is a leap year.
on every year that is evenly divisible by 4
except every year that is evenly divisible by 100 unless the year is also evenly divisible by 400
e.g. The year 2000:
2000 ÷ 4 = 500 (Leap)
2000 ÷ 100 = 20 (Not Leap)
2000 ÷ 400 = 5 (Leap!)
So the year 2000 is a leap year.
The FlowChart
print("Welcome to the Leap Year Calculator")
year = int(input("Enter a year: "))
if year % 4 == 0:
if year % 100 != 0:
print("This is a leap year")
elif year % 400 == 0:
print("This is a leap year")
else:
print("This is not a leap year")
else:
print("This is not a leap year")
Welcome to the Leap Year Calculator Enter a year: 2400 This is a leap year
Multiple IF statements in succession
print("Welcome to the RollerCoaster! We're glad to have you here")
height = int(input("Enter your height in cm: "))
if height >= 120:
age = int(input("How old are you? "))
if age < 12:
print("Child tickets are $5")
bill = 5
elif age >= 12 and age <= 18:
# The above is to represent age 12-18
print("Youth tickets are $7")
bill = 7
else:
print("Adult tickets are $12")
bill = 12
photo = input("Do you want a photo taken? Y or N:")
if photo == "Y":
bill += 3
print(f"Your total bill is {bill}. Enjoy your ride :)")
else:
print("Sorry, you'd need to grow taller to roller coast. :(")
Welcome to the RollerCoaster! We're glad to have you here Enter your height in cm: 120 How old are you? 20 Adult tickets are $12 Do you want a photo taken? Y or N:Y Your total bill is 15. Enjoy your ride :)
## Pizza Challenge
print("Welcome to Python Pizza Deliveries!")
size = input("What Pizza size would you like? S, M or L: ")
pepperoni = input("Do you want some pepperon? Y or N: ")
cheese = input("Do you want extra cheese? Y or N: ")
# small_pizza = 15
# medium_pizza = 20
# large_pizza = 25
# small_pepperoni = 2
# med_lar_pepproni = 3
# cheese = 1
bill = 0
if size == "S":
bill += 15
elif size == "M":
bill += 20
else:
bill += 25
if pepperoni == "Y" and size == "S":
bill += 2
elif pepperoni == "Y":
# elif pepperoni == "Y" and size == "M" or size == "L": *(Not using this in order to make the code very felxible and so for entries outside S or M or L- we can still charge for our Pepperoni)*
bill += 3
if cheese == "Y":
bill += 1
print(f"Your total bill is ${bill}")
Welcome to Python Pizza Deliveries! What Pizza size would you like? S, M or L: l Do you want some pepperon? Y or N: y Do you want extra cheese? Y or N: y Your total bill is $25
## Pizza Challenge
print("Welcome to Python Pizza Deliveries!")
size = input("What Pizza size would you like? S, M or L: ")
pepperoni = input("Do you want some pepperon? Y or N: ")
cheese = input("Do you want extra cheese? Y or N: ")
# small_pizza = 15
# medium_pizza = 20
# large_pizza = 25
# small_pepperoni = 2
# med_lar_pepproni = 3
# cheese = 1
bill = 0
if size == "S":
bill += 15
elif size == "M":
bill += 20
else:
bill += 25
# The else 25 is to keep us afloat of any wrong entry and also profitable. That is for any/every entry made beside "S, M or L"- we're still profitable and the system is not loss charging customers.
# # With this order if any entry other than M or L is entered- and the buyer originally intended to buy a large size, the system will charge a Dollar less because the conditional entry of either M or L was not met
# if pepperoni != "N" and size == "M" or size == "L":
# # elif pepperoni == "Y" and size == "M" or size == "L": *(Not using this in order to make the code very flexible and so for entries outside S or M or L- we can still charge for our Pepperoni)*
# bill += 3
# elif pepperoni != "N" and size != "M" or size != "L":
# # Doding this so that the we don't run at a loss; the system still calculates all entries.
# bill += 2
# With this order if any entry other than L or M or S is made- and the buyer intends for a large size, we may run at a loss of $1- since the entry was neither M nor L.
if pepperoni != "N" and size == "S":
# Coding this so that the we don't run at a loss; the system still calculates all entries outisde Y for small-sized Pizza
bill += 2
elif pepperoni != "N" and size == "M" or size == "L":
# elif pepperoni == "Y" and size == "M" or size == "L": *(Not using this in order to make the code very felxible and so for entries outside S or M or L- we can still charge for our Pepperoni)*
bill += 3
# To ensure our system keep us profitable, the extra 3 dollas will be charged for every wrong entry
else:
bill += 3
if cheese != "N":
bill += 1
# It is better "!= N" than "== Y", so that all (wrong) entries outside N doesn't make us run into any loss and keeps us profitable- nregardless.
print(f"Your total bill is ${bill}")
Welcome to Python Pizza Deliveries! What Pizza size would you like? S, M or L: S Do you want some pepperon? Y or N: Y Do you want extra cheese? Y or N: Y Your total bill is $18
# ?Update the code for those between 45-55 who have an existential crisis for a free roller coast ride
print("Welcome to the RollerCoaster! We're glad to have you here")
height = int(input("Enter your height in cm: "))
if height >= 120:
age = int(input("How old are you? "))
if age < 12:
print("Child tickets are $5")
bill = 5
elif age >= 12 and age <= 18:
# The above is to represent age 12-18
print("Youth tickets are $7")
bill = 7
elif age >= 45 and age <= 55:
print("Everything is going to be okay. Have a free ride on us!")
bill = 0
else:
print("Adult tickets are $12")
bill = 12
photo = input("Do you want a photo taken? Y or N: ")
if photo == "Y" and not age >= 45 and age <= 55:
bill += 3
print(f"Your total bill is ${bill}. Enjoy your ride :)")
else:
print("Sorry, you'd need to grow taller to roller coast. :(")
Welcome to the RollerCoaster! We're glad to have you here Enter your height in cm: 120 How old are you? 46 Everything is going to be okay. Have a free ride on us! Do you want a photo taken? Y or N: Y Your total bill is $0. Enjoy your ride :)
print("Welcome to the Love Calculator\nWhere you find out if you and your crust or partner go together")
name1 = input("Enter your full name: ")
name2 = input("Enter their full name: ")
together = name1 + name2
low_name = together.lower()
t = low_name.count("t")
r = low_name.count("r")
u = low_name.count("u")
e = low_name.count("e")
true = t + r + u + e
l = low_name.count("l")
o = low_name.count("o")
v = low_name.count("v")
e = low_name.count("e")
love = l + o + v + e
result = int(str(true)) + int(str(love))
if result < 10 or result > 90:
print(f"Your score is {result}, you go together like coke and mentos")
elif result > 39 and result < 51:
print(f"Your score is {result}, you are alright together")
else:
print(f"Your score is {result}")
Welcome to the Love Calculator Where you find out if you and your crust or partner go together Enter your full name: Kojusolwua mOLUTADE OMOWUNMI TENIFAYO Enter their full name: odunayo roberts oluwadamilare oluwatimileyin Your score is 41, you are alright togehther
print("Welcome to Treasure Island\nYour mission is to find the treasure")
print('''
*******************************************************************************
| | | |
_________|________________.=""_;=.______________|_____________________|_______
| | ,-"_,="" `"=.| |
|___________________|__"=._o`"-._ `"=.______________|___________________
| `"=._o`"=._ _`"=._ |
_________|_____________________:=._o "=._."_.-="'"=.__________________|_______
| | __.--" , ; `"=._o." ,-"""-._ ". |
|___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________
| |o`"=._` , "` `; .". , "-._"-._; ; |
_________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______
| | |o; `"-.o`"=._`` '` " ,__.--o; |
|___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________
____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____
/______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_
____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____
/______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_
____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____
/______/______/______/______/______/______/______/______/______/______/[TomekK]
*******************************************************************************
'''
)
first_pick = input("Choose between Right or Left by entering 'l or r': ")
if first_pick == 'r':
print('''
_ _
| | | |
| |__ ___ | | ___
| '_ \ / _ \| |/ _ \
| | | | (_) | | __/
|_| |_|\___/|_|\___|
''')
print("Fall into a hole.\nGame Over! :(")
else:
second_pick = input("Choose swim or wait by entering either s or w: ")
if second_pick == "s":
print("Attacked by trout.\nGame Over! :(")
print('''
(`.
\ `.
) `._..---._
\`. __...---` o )
\ `._,--' , ___,'
) ,-._ \ ) _,-'
/,' ``--.._____\/--''
''' )
else:
third_pick = input("Pick a door: 'b' for Blue, 'y' for Yellow or 'r' for Red: ")
if third_pick == 'r':
print('''
( . )
) ( )
. ' . ' . ' .
( , ) (. ) ( ', )
.' ) ( . ) , ( , ) ( .
). , ( . ( ) ( , ') .' ( , )
(_,) . ), ) _) _,') (, ) '. ) ,. (' )
''')
print("Burned by Fire\nGame Over! :(")
elif third_pick == 'b':
print('''
((((()))
|o\ /o)|
( ( _')
(._. /\__
,\___,/ ' ')
'.,_,, ( .- . . )
\ \\ ( ' )( )
\ \\ \. _.__ ____( . |
\ /\\ .( .' /\ '. )
\( \\.-' ( / \/ \)
' ()) _'.-|/\/\/\/\/\|
'\\ .( |\/\/\/\/\/|
'(( \ /\ /
(((( '.__\/__.')
((,) / ((() )
"..-, (()(" /
pils _//. ((() ."
_____ //,/" ___ ((( ', ___
(( )
/ /
_/,/'
/,/,"
''')
print("Eaten by beasts\nGame Over! :(")
elif third_pick == 'y':
print('''
'._==_==_=_.'
.-\: /-.
| (|:. |) |
'-|:. |-'
\::. /
'::. .'
) (
_.' '._
''')
print("You Won! :)")
else:
print("Game Over! :(")
Welcome to Treasure Island Your mission is to find the treasure ******************************************************************************* | | | | _________|________________.=""_;=.______________|_____________________|_______ | | ,-"_,="" `"=.| | |___________________|__"=._o`"-._ `"=.______________|___________________ | `"=._o`"=._ _`"=._ | _________|_____________________:=._o "=._."_.-="'"=.__________________|_______ | | __.--" , ; `"=._o." ,-"""-._ ". | |___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________ | |o`"=._` , "` `; .". , "-._"-._; ; | _________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______ | | |o; `"-.o`"=._`` '` " ,__.--o; | |___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________ ____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____ /______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_ ____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____ /______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_ ____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____ /______/______/______/______/______/______/______/______/______/______/[TomekK] ******************************************************************************* Choose between Right or Left by entering 'l or r': r _ _ | | | | | |__ ___ | | ___ | '_ \ / _ \| |/ _ | | | | (_) | | __/ |_| |_|\___/|_|\___| Fall into a hole. Game Over! :(
As the above diagrams
To have apostrophe in a sentence.
use the backslash as demonstrated below
print('You\'re a boy so "yes" or "no"? ')
You're a boy so "yes" or "no"?
Randomization and Python List (Day 4)
import random
num = random.randint(0, 20)
if num <= 10:
print(f"Hey! Generated Number is {num}; this is less than or equal to 10- so this is a Tail.")
else:
print(f"Hey! Generated Number is {num}; this is greater than 10- so this is a Head.")
Hey! Generated Number is 19; this is greater than 10- so this is a Head.
states_in_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia", "Connecticut", "Massachusetts", "Maryland", "South Carolina", "New Hampshire", "Virginia", "New York", "North Carolina", "Rhode Island", "Vermont", "Kentucky", "Tennessee", "Ohio", "Louisiana", "Indiana", "Mississippi", "Illinois", "Alabama", "Maine", "Missouri", "Arkansas", "Michigan", "Florida", "Texas", "Iowa", "Wisconsin", "California", "Minnesota", "Oregon", "Kansas", "West Virginia", "Nevada", "Nebraska", "Colorado", "North Dakota", "South Dakota", "Montana", "Washington", "Idaho", "Wyoming", "Utah", "Oklahoma", "New Mexico", "Arizona", "Alaska", "Hawaii"]
print(states_in_america)
# This returns the indexed values. Originally starting from 0
print(states_in_america[3])
# To start returning the items from last value of the item, we use -. The item starts from -1, unlike 0
print(states_in_america[-1])
# To change or update the value of an item in the list
states_in_america[1] = "Pencilvania"
# This updates Pennsylvania to Pencilvania
print(states_in_america)
# This adds a value to the end of the list.
states_in_america.append('Love Island')
print(states_in_america)
# This extends the list item by adding more thna one value (unlike the append). The list should/MUST be netered using Square brackets
states_in_america.extend(["Teni's island", "Love", "Island"])
print(states_in_america)
['Delaware', 'Pennsylvania', 'New Jersey', 'Georgia', 'Connecticut', 'Massachusetts', 'Maryland', 'South Carolina', 'New Hampshire', 'Virginia', 'New York', 'North Carolina', 'Rhode Island', 'Vermont', 'Kentucky', 'Tennessee', 'Ohio', 'Louisiana', 'Indiana', 'Mississippi', 'Illinois', 'Alabama', 'Maine', 'Missouri', 'Arkansas', 'Michigan', 'Florida', 'Texas', 'Iowa', 'Wisconsin', 'California', 'Minnesota', 'Oregon', 'Kansas', 'West Virginia', 'Nevada', 'Nebraska', 'Colorado', 'North Dakota', 'South Dakota', 'Montana', 'Washington', 'Idaho', 'Wyoming', 'Utah', 'Oklahoma', 'New Mexico', 'Arizona', 'Alaska', 'Hawaii'] Georgia Hawaii ['Delaware', 'Pencilvania', 'New Jersey', 'Georgia', 'Connecticut', 'Massachusetts', 'Maryland', 'South Carolina', 'New Hampshire', 'Virginia', 'New York', 'North Carolina', 'Rhode Island', 'Vermont', 'Kentucky', 'Tennessee', 'Ohio', 'Louisiana', 'Indiana', 'Mississippi', 'Illinois', 'Alabama', 'Maine', 'Missouri', 'Arkansas', 'Michigan', 'Florida', 'Texas', 'Iowa', 'Wisconsin', 'California', 'Minnesota', 'Oregon', 'Kansas', 'West Virginia', 'Nevada', 'Nebraska', 'Colorado', 'North Dakota', 'South Dakota', 'Montana', 'Washington', 'Idaho', 'Wyoming', 'Utah', 'Oklahoma', 'New Mexico', 'Arizona', 'Alaska', 'Hawaii'] ['Delaware', 'Pencilvania', 'New Jersey', 'Georgia', 'Connecticut', 'Massachusetts', 'Maryland', 'South Carolina', 'New Hampshire', 'Virginia', 'New York', 'North Carolina', 'Rhode Island', 'Vermont', 'Kentucky', 'Tennessee', 'Ohio', 'Louisiana', 'Indiana', 'Mississippi', 'Illinois', 'Alabama', 'Maine', 'Missouri', 'Arkansas', 'Michigan', 'Florida', 'Texas', 'Iowa', 'Wisconsin', 'California', 'Minnesota', 'Oregon', 'Kansas', 'West Virginia', 'Nevada', 'Nebraska', 'Colorado', 'North Dakota', 'South Dakota', 'Montana', 'Washington', 'Idaho', 'Wyoming', 'Utah', 'Oklahoma', 'New Mexico', 'Arizona', 'Alaska', 'Hawaii', 'Love Island'] ['Delaware', 'Pencilvania', 'New Jersey', 'Georgia', 'Connecticut', 'Massachusetts', 'Maryland', 'South Carolina', 'New Hampshire', 'Virginia', 'New York', 'North Carolina', 'Rhode Island', 'Vermont', 'Kentucky', 'Tennessee', 'Ohio', 'Louisiana', 'Indiana', 'Mississippi', 'Illinois', 'Alabama', 'Maine', 'Missouri', 'Arkansas', 'Michigan', 'Florida', 'Texas', 'Iowa', 'Wisconsin', 'California', 'Minnesota', 'Oregon', 'Kansas', 'West Virginia', 'Nevada', 'Nebraska', 'Colorado', 'North Dakota', 'South Dakota', 'Montana', 'Washington', 'Idaho', 'Wyoming', 'Utah', 'Oklahoma', 'New Mexico', 'Arizona', 'Alaska', 'Hawaii', 'Love Island', "Teni's island", 'Love', 'Island']
import random
name_string = input("Enter everyone's names separated by a space and a comma: ")
name_split = name_string.split(", ")
name_len = len(name_split)
random_names = random.randint(0, name_len - 1)
rand_name = name_split[random_names]
print(f"{rand_name} will pay the bill today")
Enter everyone's names separated by a space and a comma: Love, Joy, Peace, Perserverance, Kindness, Tolerance, Joy, Patience, Grace Peace will pay the bill today
states_in_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia", "Connecticut", "Massachusetts", "Maryland", "South Carolina", "New Hampshire", "Virginia", "New York", "North Carolina", "Rhode Island", "Vermont", "Kentucky", "Tennessee", "Ohio", "Louisiana", "Indiana", "Mississippi", "Illinois", "Alabama", "Maine", "Missouri", "Arkansas", "Michigan", "Florida", "Texas", "Iowa", "Wisconsin", "California", "Minnesota", "Oregon", "Kansas", "West Virginia", "Nevada", "Nebraska", "Colorado", "North Dakota", "South Dakota", "Montana", "Washington", "Idaho", "Wyoming", "Utah", "Oklahoma", "New Mexico", "Arizona", "Alaska", "Hawaii"]
# When indexing, the items starts from 0- 49.
# However, length ends at the normal count.
print(len(states_in_america))
# 50th number same as Hawaii
# To index a len, YOU MUST Add a - 1 or to get the desired outcome.
length = len(states_in_america)
print(states_in_america[length - 1])
# 50 - 1 to get same Hawaii
50 Hawaii
# dirty_dozens = ["Strawberries", "Spinach", "Kale", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears", "Tomatoes", "Celery", "Potatoes", "Avocados", "Sweet corn", "Pineapples", "Cabbages", "Onions", "Sweet peas" "Papayas", "Asparagus", "Mangoes", "Eggplants", "Honeydew melons", "Kiwis", "Cantaloupes", "Cauliflower", "Broccoli"]
fruits = ["Strawberries", "Spinach", "Kale", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears"]
vegetables = ["Tomatoes", "Celery", "Potatoes", "Avocados", "Sweet corn", "Pineapples", "Cabbages", "Onions", "Sweet peas" "Papayas", "Asparagus", "Mangoes", "Eggplants", "Honeydew melons", "Kiwis", "Cantaloupes", "Cauliflower", "Broccoli"]
dirty_dozen = [fruits, vegetables]
print(dirty_dozen)
# This produces a nested list. A list inside another list.
[['Strawberries', 'Spinach', 'Kale', 'Nectarines', 'Apples', 'Grapes', 'Peaches', 'Cherries', 'Pears'], ['Tomatoes', 'Celery', 'Potatoes', 'Avocados', 'Sweet corn', 'Pineapples', 'Cabbages', 'Onions', 'Sweet peasPapayas', 'Asparagus', 'Mangoes', 'Eggplants', 'Honeydew melons', 'Kiwis', 'Cantaloupes', 'Cauliflower', 'Broccoli']]
row1 = ["🤖", "🤖","🤖"]
row2 = ["🤖", "🤖","🤖"]
row3 = ["🤖", "🤖","🤖"]
map = [row1, row2, row3]
game_post = input("Enter a 2 digit number, between 1 and 3, to indicate your move: ")
list_input = list(game_post)
vertical = int(list_input[0])
horizontal = int(list_input[1])
# select_col = map[vertical] + 1
sel_row = (map[vertical - 1])
sel_row[horizontal - 1] = "X"
print(f"{row1}\n{row2}\n{row3}")
Enter a 2 digit number, between 1 and 3, to indicate your move: 33 ['🤖', '🤖', '🤖'] ['🤖', '🤖', '🤖'] ['🤖', '🤖', 'X']
number = 23
number_str = str(number) # Convert the number to a string
digits = list(number_str) # Split the string into individual characters
print(digits)
['2', '3']
ROCK PAPER & SCISSORS GAME
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
#Write your code below this line 👇
map_list = ["Rock", "Paper", "Scissors"]
# USER ENTRY
user = int(input("Enter a number between 0 and 2. 0 for Rock, 1 for Paper and 2 for Scissors:\n "))
if user > 2:
print("Incorrect number entry.\nTry again but enter any 1-digit number from number 0 to number 2.")
else:
# Users' coding
list_set = [rock, paper, scissors]
indexed_user = list_set[user]
map = map_list[user]
print(f"You picked {user}; {map}\n{indexed_user}")
# Computer's coding
computer_choice = random.randint(0, 2)
indexed_comp = list_set[computer_choice]
map_comp = map_list[computer_choice]
print(f"Computer's Choice is:\n{computer_choice}; {map_comp}\n{indexed_comp}")
if user == 0 and computer_choice == 2:
print("Rock beats Scissors, so you win! :)")
elif user == 1 and computer_choice == 0:
print("Paper beats Rock, so you win! :)")
elif user == 2 and computer_choice == 1:
print("Scissors beats Paper, so you win! :)")
elif user == computer_choice:
print("It's a draw.")
else:
print("You lose :(")
Enter a number between 0 and 2. 0 for Rock, 1 for Paper and 2 for Scissors: 1 You picked 1; Paper _______ ---' ____)____ ______) _______) _______) ---.__________) Computer's Choice is: 0; Rock _______ ---' ____) (_____) (_____) (____) ---.__(___) Paper beats Rock, so you win! :)
fruits = ["Apple", "Pear", "Peach"]
for fruit in fruits:
print(fruit)
print(fruit + "Pie")
print(fruits)
# Any print oitside the indentation will not be looped throigh or repeated for every item within the loop list.
# e.g
print(f"Here's the example of the outside indentation result, which is a stand-alone from the other list of fruit that was repeated\n{fruits}")
Apple ApplePie ['Apple', 'Pear', 'Peach'] Pear PearPie ['Apple', 'Pear', 'Peach'] Peach PeachPie ['Apple', 'Pear', 'Peach'] Here's the example of the outside indentation result, which is a stand-alone from the other list of fruit that was repeated ['Apple', 'Pear', 'Peach']
student_heights = input("Input a list of student heights separated by comma: ").split(", ")
print(type(student_heights))
# This is alist of string
print(student_heights)
# To convert a list of string items into integer, the best way to go abut it is to use the For n in range loop. As shown below:
# To make the list of student_heights integers in order to get the AVG heighs to the students (Sum/N), we'd use the For loop.
for n in range (0, len(student_heights)):
# We using the range instead of:
# For height in student_heights:
# because we need to access the indexed number of all items in the student list to do a cast data type.
student_heights[n] = int(student_heights[n])
print(student_heights)
# This should be a list of Integer number that'd make our mathemantical operation possible
# --------------------------------------------------
X = sum(student_heights)
Y = len(student_heights)
result = round(X/Y, 2)
print(f"The average students' height of the {Y} students is {result}")
Input a list of student heights separated by comma: 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 <class 'list'> ['100', '200', '300', '400', '500', '600', '700', '800', '900', '1000'] [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000] The average students' height of the 10 studnets is 550.0
# USING ONLY THE FOR LOOP TO SOLVE THE ABOVE QUESTION.
student_height = input("Enter the list of student heights to be averaged: ").split(", ")
# To amke an integer
for n in range(0, len(student_height)):
student_height[n] = int(student_height[n])
# print(student_height)
start = 0
for length in student_height:
start += length
print(f"The total sum of the students' height is: {start}")
start_n = 0
for n in student_height:
start_n += 1
print(f"The number of students is: {start_n}")
result = round(start/start_n, 1)
print(f"The average number of the students' height is: {result}")
Enter the list of student heights to be averaged: 10, 20, 30, 40, 50 The total sum of the students' height is: 150 The number of students is: 5 The average number of the students' height is: 30.0
states_in_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia", "Connecticut", "Massachusetts", "Maryland", "South Carolina", "New Hampshire", "Virginia", "New York", "North Carolina", "Rhode Island", "Vermont", "Kentucky", "Tennessee", "Ohio", "Louisiana", "Indiana", "Mississippi", "Illinois", "Alabama", "Maine", "Missouri", "Arkansas", "Michigan", "Florida", "Texas", "Iowa", "Wisconsin", "California", "Minnesota", "Oregon", "Kansas", "West Virginia", "Nevada", "Nebraska", "Colorado", "North Dakota", "South Dakota", "Montana", "Washington", "Idaho", "Wyoming", "Utah", "Oklahoma", "New Mexico", "Arizona", "Alaska", "Hawaii"]
# print(states_in_america.append("Love"))
# states_in_america[-2]= "Peace"
student_scores = input("Enter the score of the students separated by a comma and a space: ").split(", ")
# Turn thse entry into Integer. Change the data Type to an Integer.
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# Using For Loop to get the highest value will be below...without usibng MAX or MIN function
highest_score = 0
for score in student_scores:
if score > highest_score:
highest_score = score
print(f"The highest score is {highest_score}")
Enter the score of the students separated by a comma and a space: 1, 2, 3, 4, 5, 9, 8 [1, 2, 3, 4, 5, 9, 8] The highest score is 9
RANGE and the FizzBuzz Challenge...using FOR LOOOP Function
for n in range(1, 101):
if n % 3 == 0 and n % 5 != 0:
print ("Fizz")
elif n % 5 == 0 and n % 3 != 0:
print("Buzz")
elif n % 3 == 0 and n % 5 == 0:
print("Fizzbuzz")
else:
print(n)
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 Fizzbuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 Fizzbuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 Fizzbuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 Fizzbuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 Fizzbuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 Fizzbuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
# OR
for n in range(1, 101):
if n % 3 == 0 and n % 5 == 0:
print("Fizzbuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 Fizzbuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 Fizzbuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 Fizzbuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 Fizzbuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 Fizzbuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 Fizzbuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
result = 0
for n in range (1, 101, 2):
result += n
print( result)
2500
# OR
result = 0
for n in range(1, 101):
if n % 2 == 0:
result += n
print(result)
2550
#Password Generator Project
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
# nr_symbols = int(input(f"How many symbols would you like?\n"))
# nr_numbers = int(input(f"How many numbers would you like?\n"))
for n in range(1, nr_letters):
indexed = letters[n]
print(indexed)
# for n in range(1, nr_letters):
# indexed_l = letters[n]
# print(n)
# for n in range(1, nr_symbols + 1):
# indexed_s = symbols[n]
# for n in range(1, nr_numbers + 1):
# indexed_n = numbers[n]
Welcome to the PyPassword Generator! How many letters would you like in your password? 7 g
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
# Easy Method:
# password = " "
# for number in range (1, nr_letters + 1):
# password += random.choice(letters)
# # print(password)
# for number in range(1, nr_numbers + 1):
# password += random.choice(numbers)
# for number in range(1, nr_symbols + 1):
# password += random.choice(symbols)
# print(f"Your generated password is{password}")
# Hard Method:
password_list = []
for n in range (1, nr_letters + 1):
password_list += random.choice(letters)
# print(password)
for n in range(1, nr_numbers + 1):
password_list += random.choice(numbers)
for n in range(1, nr_symbols + 1):
password_list += random.choice(symbols)
random.shuffle(password_list)
password = ""
for n in password_list:
password += n
print(f"Your generated password is:{password}")
Welcome to the PyPassword Generator! How many letters would you like in your password? 5 How many symbols would you like? 2 How many numbers would you like? 1 Your generated password is:0BV%Kp#E
def my_function():
print("Hello Tester :)")
# To call my defined Function
my_function()
Hello Tester :)
While something_is_true: print("Still true)
x = 1
while x < 6:
print(x)
x+=1
print(f"This is the final result: {x}")
1 2 3 4 5 this is the final result: 6
def my_function(name):
print(f"Hello {name}\nit's nice to have you here, {name}")
# Here, "name is referred to as a PARAMETER"
my_function("Teni")
# Here, Teni is refereed to as ARGUMENT
Hello Teni it's nice to have you here, Teni
def greet_with(name, location):
print(f"Hello, {name}\nWhat is it like in {location}?")
greet_with("Teni", "The UK")
Hello, Teni What is it like in The UK?
def greet_with_2(name = 1, location = 3, mood = 2):
if mood in ["happy", "Excited"]:
print(f"Hello {name},\nI'm glad you're in a great mood today!\nWhat's like in {location} today?")
elif mood not in ["happy", "Elated"]:
print(f"Hello {name}, everything's going to be alright. Cheer up!:)\n Do you mind sharing what's it like in {location} today?")
else:
print(f"Hello {name}, everything's going to be alright. Cheer up!:)\n Do you mind sharing what's it like in {location} today?")
greet_with_2("Teni", "happy", "Northampton")
Hello Teni, everything's going to be alright. Cheer up!:) Do you mind sharing what's it like in happy today?
greet_with_2(location = "Northampton", name = "Teni", mood = "Excited")
# I can either use the positional Argument or the Keyword Argument
Hello Teni, I'm glad you're in a great mood today! What's like in Northampton today?
VALUE is to KEY, as ARGUMENT is to PARAMETER
( )_ are for Python Funtions
{ }_ are for calling VARIABLES or for Dictionary Nesting
[ ]_ are for indexing or form using the IN function
dic_test = {"Bug": "A programming code or error", "Love":"To be kind and affectionate", "Peace":"No worries"
}
print(dic_test)
{'Bug': 'A programming code or error', 'Love': 'To be kind and affectionate', 'Peace': 'No worries'}
# To Fetch a Key
print(dic_test["Peace"])
No worries
# To add a new Key & Value
dic_test["Wealth"] = "Assets"
print(dic_test)
{'Bug': 'A programming code or error', 'Love': 'To be kind and affectionate', 'Peace': 'No worries', 'Wealth': 'Assets'}
# To replace a value
dic_test["Wealth"] = "God, please make me financially freed!"
print(dic_test)
{'Bug': 'A programming code or error', 'Love': 'To be kind and affectionate', 'Peace': 'No worries', 'Wealth': 'God, please make me financially freed!'}
def score_grade(name, score):
if score <= 70:
print(f"Hello {name}, you scored {score} and your grade is 'Fail'")
elif score > 70 and score <= 80:
print(f"Hello {name}, you scored {score} and your grade is 'Acceptable'")
else:
print(f"Hello {name}, you scored {score} and your grade 'Exceeds Expectations'")
score_grade(score = 90, name = "Teni")
Hello Teni, you scored 90 and your grade 'Exceeds Expectations'
# OR
student_scores = {
"Harry": 81,
"Ron": 78,
"Hermione": 99,
"Draco": 74,
"Neville": 62
}
student_grade = {}
for student in student_scores:
# print(student)
# print(student_scores[student])
if student_scores[student] <= 70:
# student = "Love"
student_grade[student] = "Fail"
elif student_scores[student] >= 80:
student_grade[student] = "Acceptable"
elif student_scores[student] >= 90:
student_grade[student] = "Exceeds Expectations"
else:
student_grade[student] = "Outstanding"
print(student_grade)
{'Harry': 'Acceptable', 'Ron': 'Outstanding', 'Hermione': 'Acceptable', 'Draco': 'Outstanding', 'Neville': 'Fail'}
Each Key can only have 1 Value.
To enable multiple value entries, use a list...as so:
A LIST in a Dictionary
travel_log = { "Nigeria" = ["Lagos", "Ogun State", "Abuja"], "United Kingom = ["Northampton", "Blackpool"] }
Nested Dictionary; A Dictionary in a Dictionary
travel_log = {"Nigeria" : {"cities_visited": ["Lagos_Island", "Yaba", "Lekki", "VI"]}
}
# **A LIST in a Dictionary**
travel_log = {
"Nigeria": ["Lagos", "Ogun State", "Abuja"],
"United Kingom": ["Northampton", "Blackpool"]
}
# **Nested Dictionary; A Dictionary in a Dictionary**
travel_log_2 = {"Nigeria" : {"cities_visited": ["Lagos_Island", "Yaba", "Lekki", "VI"],
"total_visited_cities": 12},
"United Kingdom": {"visited_cities": ["Northampton", "United Kingdom"]}
}
travel_log_2['Nigeria']['cities_visited']
['Lagos_Island', 'Yaba', 'Lekki', 'VI']
cities_visited_uk = travel_log_2["United Kingdom"]["visited_cities"]
cities_visited_Nigeria = travel_log_2["Nigeria"]["cities_visited"]
for city in cities_visited_Nigeria:
print(city)
Lagos_Island Yaba Lekki VI
# Having a Dictionary in a list.
travel_log = [
{
"Country": "Nigeria",
"cities_visited": ["Lagos", "Yaba", "Abeokuta", "Banana Island"],
"total_visit": 40
},
{
"Country": "United Kingdom",
"cities_visited": ["Northampton", "Heathrow Airport", "Blackpool"],
"total_visit": 3
}
]
travel_log = [
{
"Country": "Nigeria",
"cities_visited": ["Lagos", "Yaba", "Abeokuta", "Banana Island"],
"total_visit": 40
},
{
"Country": "United Kingdom",
"cities_visited": ["Northampton", "Heathrow Airport", "Blackpool"],
"total_visit": 3
}
]
def add_new_country(country, number, city_list):
travel = {
"Country": country,
"cities_visited": city_list,
"total_visited": number}
travel_log.append(travel)
print(add_new_country("Russia", 2, ["Moscow", "Yaba"]))
print(travel_log)
None [{'Country': 'Nigeria', 'cities_visited': ['Lagos', 'Yaba', 'Abeokuta', 'Banana Island'], 'total_visit': 40}, {'Country': 'United Kingdom', 'cities_visited': ['Northampton', 'Heathrow Airport', 'Blackpool'], 'total_visit': 3}, {'Country': 'Russia', 'cities_cisited': ['Moscow', 'Yaba'], 'total_visited': 2}, {'Country': 'Russia', 'cities_cisited': ['Moscow', 'Yaba'], 'total_visited': 2}, {'Country': 'Russia', 'cities_cisited': ['Moscow', 'Yaba'], 'total_visited': 2}, {'Country': 'Russia', 'cities_cisited': ['Moscow', 'Yaba'], 'total_visited': 2}]
student_scores = {
"Harry": 81,
"Ron": 78,
"Hermione": 99,
"Draco": 74,
"Neville": 62
}
student_grade = {}
# Creating an empty list allows us access to MODIFY the Value of the Keys
for student in student_scores:
score = student_scores[student]
# The student_scores[student] allows access to the values of the Keys student
if score <= 70:
student_grade[student] = "Fail"
#student_grade[student] = "Fail" This allows us access to MODIFY the keys whose values are less than 70
elif score < 80:
student_grade[student] = "Acceptable"
#student_grade[student] = "Fail" This allows us access to MODIFY the keys whose values are less than 80
elif score < 90:
student_grade[student] = "Exceeds Expectations"
#student_grade[student] = "Fail" This allows us access to MODIFY the keys whose values are less than 90
else:
student_grade[student] = "Outstanding"
#student_grade[student] = "Fail" This allows us access to MODIFY the keys whose values are above 90
print(student_grade)
travel_log = [
{
"Country": "Nigeria",
"cities_visited": ["Lagos", "Yaba", "Abeokuta", "Banana Island"],
"total_visit": 40
},
{
"Country": "United Kingdom",
"cities_visited": ["Northampton", "Heathrow Airport", "Blackpool"],
"total_visit": 3
}
]
def add_new_country(country_visited, times_visited, cities_visited):
new_country = {}
# Creating an empty list and assigning the key to it as shown below...
# new_emptylist_dictionary["KEY"] allows us MODIFY the value of the key "KEY"
new_country["country"] = country_visited
# This assigns the VALUE of the country_visited to the KEY country
new_country["total_visits"] = times_visited
# This assigns the VALUE of the times_visited to the KEY total_visits
new_country["cities_visited"] = cities_visited
# This assigns the VALUE of the cities_visited (utside the equation) to the KEY cities_visited (indexed)
travel_log.append(new_country)
print(add_new_country("Russia", 2, ["Moscow", "Yaba"]))
print(travel_log)
None [{'Country': 'Nigeria', 'cities_visited': ['Lagos', 'Yaba', 'Abeokuta', 'Banana Island'], 'total_visit': 40}, {'Country': 'United Kingdom', 'cities_visited': ['Northampton', 'Heathrow Airport', 'Blackpool'], 'total_visit': 3}, {'country': 'Russia', 'total_visits': 2, 'cities_visited': ['Moscow', 'Yaba']}]
starting_dictionary = {
"a": 9,
"b": 8,
}
# final_dictionary = {
# "a": 9,
# "b": 8,
# "c": 7,
# }
final_dictionary = starting_dictionary.append({"c": 7})
# This didn't work becasue the APPEND only works to add a value or a variable, and NOT a LIST
# Rather this should
starting_dictionary = {
"a": 9,
"b": 8,
}
# final_dictionary = {
# "a": 9,
# "b": 8,
# "c": 7,
# }
starting_dictionary["c"] = 7
final_dictionary = starting_dictionary
print(final_dictionary)
{'a': 9, 'b': 8, 'c': 7}
starting_dictionary = {
"a": 9,
"b": 8,
}
starting_dictionary["c"] = [7, 8, 9]
# This is trhe best way to add a long line of VALUES tp a given KEY
print(starting_dictionary)
{'a': 9, 'b': 8, 'c': [7, 8, 9]}
starting_dictionary = {
"a": 9,
"b": 8,
}
for key in starting_dictionary:
starting_dictionary[key] +=1
# This worked because ALL THE ITems IN THE starting_dictionary are of the SAME OBJECT (Simple dictionary, not a list)
The isinstance() function is a built-in Python function used to check if an object belongs to a specific class or data type. It takes two arguments: the object you want to check, and the class or data type you want to check against.
# USED WHEHN TRYING TO MODIFYU BY INCREMENTING THE VALUE OF A LIST BY 1.
# A LIST INTO A DICTUIONARY WHERE THE OTHER OBJECTS IN THE DICTIOARY HAVE A DIFFERENT OBJECT DINMENSION
starting_dictionary = {
"a": 9,
"b": 8,
}
starting_dictionary["c"] = [7, 8, 9]
for key in starting_dictionary:
if isinstance(starting_dictionary[key], list):
starting_dictionary[key] = [x + 1 for x in starting_dictionary[key]]
else:
starting_dictionary[key] +=1
print(starting_dictionary)
{'a': 10, 'b': 9, 'c': [8, 9, 10]}
order = {
"starter": {1: "Salad", 2: "Soup"},
"main": {1: ["Burger", "Fries"], 2: ["Steak"]},
"dessert": {1: ["Ice Cream"], 2: []},
}
print(order["main"][2])
# This retuns all the value under the KEY 2 as a a LIST
['Steak']
print(order["main"][1])
# To fetch the entire value of KEY 1
['Burger', 'Fries']
order = {
"starter": {1: "Salad", 2: "Soup"},
"main": {1: ["Burger", "Fries"], 2: ["Steak"]},
"dessert": {1: ["Ice Cream"], 2: []},
}
print(order["main"][2][0])
# The indexed number 0, takes away the string
Steak
order = {
"starter": {1: "Salad", 2: "Soup"},
"main": {1: ["Burger", "Fries"], 2: ["Steak"]},
"dessert": {1: ["Ice Cream"], 2: []},
}
# To fetch 0 indexed of the 1 KEY, Burger
print(order["main"][1][0])
Burger
print(order["main"][1][1])
Fries
name = input("What is your name? ")
bid = int(input("How much are you bidding? "))
bidder = input("Is there another bidder? Type 'yes or 'no")
def bidding_code(name, bid):
bid_2 = max(bid)
print(f" {name} is the highest bidder with a bid of {bid}")
print("Welcome to the bidding show")
while bidder == 'yes':
print(name, bid, bidder)
bidding_code(name, bid)
name = input("What is your name? ")
bid = int(input("How much are you bidding? "))
bidder = input("Is there another bidder? Type 'yes' or 'no'")
def bidding_code(name, bid):
print(f"{name} is the highest bidder with a bid of {bid}")
print("Welcome to the bidding show")
while bidder == 'yes':
print(name)
print(bid)
print(bidder)
name = input("What is your name? ") # Add this line to get new input for each iteration
bid = int(input("How much are you bidding? ")) # Add this line to get new input for each iteration
bidder = input("Is there another bidder? Type 'yes' or 'no'") # Add this line to get new input for each iteration
bidding_code(name, bid)
What is your name? Teni How much are you bidding? 120 Is there another bidder? Type 'yes' or 'no'yes Welcome to the bidding show Teni 120 yes What is your name? Teni How much are you bidding? 200 Is there another bidder? Type 'yes' or 'no'no Teni is the highest bidder with a bid of 200
# With the CLEAR Function.
from IPython.display import clear_output
print("Welcome to the bidding show")
name = input("What is your name? ")
bid = int(input("How much are you bidding? "))
bidder = input("Is there another bidder? Type 'yes' or 'no'")
def bidding_code(name, bid):
print(f"{name} is the highest bidder with a bid of {bid}")
while bidder == 'yes':
clear_output(wait=True) # This clears the output of the cell
print("Welcome to the bidding show")
# print(f"Last Bidder: {name}, Bid: {bid}")
name = input("What is your name? ") # Add this line to get new input for each iteration
bid = int(input("How much are you bidding? ")) # Add this line to get new input for each iteration
bidder = input("Is there another bidder? Type 'yes' or 'no'") # Add this line to get new input for each iteration
REclear_output(wait=True)
bidding_code(name, bid)
Tolu is the highest bidder with a bid of 900000000000
The Title Function helps return proper Nouns.
def name_format(f_name, l_name):
formatted_f_name = f_name.title()
formatted_l_name = l_name.title()
# Return funtion does use or have brackets or parethesis.
return f"It's nice to meet you, {formatted_f_name} {formatted_l_name}."
name_format(input("What is your first name? "), input("What is your last name? "))
# As per the definition of the FUNCTION, the f_name represents all of this "(input("What is your first name? "), regardless of the question that may be asked there.
What is your first name? teni What is your last name? OLUTADE
"It's nice to meet you, Teni Olutade."
def name_format(f_name, l_name):
if f_name == "" or l_name == "":
return "You didn't provide valid inputs"
# Return funtion does use or have brackets or parethesis.
# without using ELSE, teh indentation makes that to defaulty happen
formatted_f_name = f_name.title()
formatted_l_name = l_name.title()
return f"It's nice to meet you, {formatted_f_name} {formatted_l_name}."
print(name_format(input("What is your first name? "), input("What is your last name?")))
What is your first name? What is your last name? You didn't provide valid inputs
print("Welcome to the Leap Year Calculator")
def is_leap( year):
year = int(input("Enter a year: "))
if year % 4 == 0:
if year % 100 != 0:
print("True")
elif year % 400 == 0:
print("False")
else:
print("False")
else:
print("False")
is_leap(2024)
Welcome to the Leap Year Calculator
# The Easy Function:
def easy():
number = 0
attempts = 10
print("You have 10 attempts remaining to guess the number")
while attempts > 0 and number != 30:
number = int(input("Make a guess: "))
attempts -= 1
if number < 30:
print("Too low, try again.")
elif number == 30:
print(f"You guessed right with {attempts} attempts left! :) ")
else:
print("Too high, try again.")
if attempts > 0 and number != 30:
print(f"You have {attempts} attempts left to guess the number")
if attempts == 0 and number != 30:
# loop = False
print("You've run out of attempts. Game Over :(")
# The Hard Function:
def hard():
number = 0
attempts = 5
print("You have 5 attempts remaining to guess the number")
while attempts > 0 and number != 30:
number = int(input("Make a guess: "))
attempts -= 1
if number < 30:
print("Too low, try again.")
elif number == 30:
print(f"You guessed right with {attempts} attempts left! :) ")
else:
print("Too high, try again.")
if attempts > 0 and number != 30:
print(f"You have {attempts} attempts left to guess the number")
if attempts == 0 and number != 30:
# loop = False
print("You've run out of attempts. Game Over :(")
import logo_module
print(f"Welcome to the Game: {logo_module.logo}\nI'm thinking of a number between 1 and 100. Can you guess it? :)")
level = input("Choose a level. Type 'easy' or 'hard': ")
if level == "easy":
easy()
elif level == "hard":
hard()
Welcome to the Game: _____ _______ _ _ _ _ / ____| |__ __| | | \ | | | | | | __ _ _ ___ ___ ___ | | | |__ ___ | \| |_ _ _ __ ___ | |__ ___ _ __ | | |_ | | | |/ _ \/ __/ __| | | | '_ \ / _ \ | . ` | | | | '_ ` _ \| '_ \ / _ \ '__| | |__| | |_| | __/\__ \__ \ | | | | | | __/ | |\ | |_| | | | | | | |_) | __/ | \_____|\__,_|\___||___/___/ |_| |_| |_|\___| |_| \_|\__,_|_| |_| |_|_.__/ \___|_| I'm thinking of a number between 1 and 100. Can you guess it? :) Choose a level. Type 'easy' or 'hard': hard You have 5 attempts remaining to guess the number Make a guess: 45 Too high, try again. You have 4 attempts left to guess the number Make a guess: 55 Too high, try again. You have 3 attempts left to guess the number Make a guess: 56 Too high, try again. You have 2 attempts left to guess the number Make a guess: 30 You guessed right with 1 attempts left! :)