Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Dictionary and fuctions Python Exercise solutions

Uploaded by

stefanymca12
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Dictionary and fuctions Python Exercise solutions

Uploaded by

stefanymca12
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

Notes:

Dictionary:

- Dictionary items
- Ordered
- Changeable
- does not allow duplicates.

firstEmployee = {
"id" : 1234,
"name" : "krunal",
"salary" : 5000
}

firstEmployee["id"]

firstEmployee = {
"id" : 1234,
"name" : "krunal",
"salary" : 5000
}

#update the value of dictionary element


firstEmployee["name"] = "tanveer"
print(firstEmployee["name"])

firstEmployee.update({"salary":8000.50})
print(firstEmployee["salary"])

#add key value pair into the dictionary


firstEmployee.update({"address" : "Montreal"})

print(firstEmployee["address"])

#remove the element from the dictionary


print(firstEmployee)

firstEmployee.pop("name")

print(firstEmployee)

firstEmployee = {
"id" : 1234,
"name" : "krunal",
"salary" : 5000,
"address" : "Montreal"
}

#print key from the dictionary


for key in firstEmployee.keys():
print(key)

#print value from the dictionary


for value in firstEmployee.values():
print(value)

#print key and value from the dictionary


for key,value in firstEmployee.items():
print(key,value)
firstEmployee = {
"id" : 1234,
"name" : "krunal",
"salary" : 5000,
"address" : "Montreal"
}

employee = firstEmployee.copy()

print(employee)

secondEmployee = dict(employee)
print(secondEmployee)

Nested dictionary:
- dictionary inside the dictionary.

employees = {
"firstEmployee" :{
"id" : 101,
"name" : "krunal",
"address" : "montreal"
},
"secondEmployee" : {
"id" : 102,
"name" : "erick",
"address" : "laval"
},
"thirdEmployee" : {
"id" : 103,
"name" : "stepany",
"address" : "toronto"
}
}

print(employees["firstEmployee"]["id"])

User Defined Function: (Function)


- Function if block of code which you can run multiple times.
- You can pass data(Using parameters)(optional) and return(Optional) output from
the function.
- write once, call multiple times

- Declare and define the function


def function_name(parameters):
statements

- Call the function


function_name(value of parameters)

#define the function


def printMenu():
print("1. Deposit")
print("2. Withdraw")
print("3. Pay bill from credit card")
print("4. Pay credit card bill")
print("5. Exit")
#call the function
printMenu()
printMenu()
printMenu()

#define the function to pass data into it


def greeting(message):
print("Good",message)

#Call the function


greeting("Afternoon")

#define the function to pass data into it


def addition(firstNumber,secondNumber):
print("Answer: ",(firstNumber + secondNumber))

#Call the function


addition(30,35)
addition(30.30,35.35)

Arbitrary arguments:
- Specify only one parameter, you can pass multiple parameters into one.

#define the function with arbitrary parameters


def printStudentNames(*students):
print("Student Name 1",students[0])
print("Student Name 2", students[1])
print("Student Name 3", students[2])

#call the function


printStudentNames("vernoica","sandra","josecano","gabi")

- You can pass parameters in form of dictionary.


#define the function with arbitrary parameters in form of dictionary
def printEmployeeInformation(**employee):
print("Employee ID: ",employee["id"])
print("Employee Name: ",employee["name"])
print("Employee Address: ",employee["address"])

#call the function


printEmployeeInformation(id = 101,name = "krunal",address = "Montreal")

Default parameter value into the function:


#define function with default value
def chooseProgram(program = "Business Intelligence"):
print("Program Name: ",program)

#call the function


chooseProgram("Database Administration")
chooseProgram()

Function can return value:


#define function to find the square and return the answer
def findSquare(number):
return number * number;

#call function
print(findSquare(5))

Lambda function:
- One line function.

syntax:
secondVariable = lambda variablename : variablename * variablename

Example:
#define lambda function with only one parameter
square = lambda number : number * number

#Call the function


print(square(15))

#define lambda function with 3 parameters


simpleInterest = lambda p,r,t : p * r * t / 100

#call the function


print(simpleInterest(5000,3,2))

accountNumber = input("Enter the account number: ")


holderName = input("Enter the account holder name: ")
accountBalance = float(input("Enter the account balance: "))
initialCreditcardLimit = float(input("Enter the credit card limit: "))
creditLimit = initialCreditcardLimit
transactionsAmount = []
transactionDesc = []

def showMenuGetChoice():
print("1. Deposit")
print("2. Withdraw")
print("3. Pay bill from credit card")
print("4. Pay credit card bill")
print("5. View Credit card transactions")
print("6. View account details")
print("7. Exit")
choice = int(input("Enter the choice: "))
return choice

def depositAmount(accountBalance):
depositAmount = float(input("Enter the amount that you want to deposit: "))
if depositAmount < 0:
print("Invalid amount!Enter amount greater than 0.")
else:
accountBalance = accountBalance + depositAmount
return accountBalance

def withdrawAmount(accountBalance):
withdrawAmount = float(input("Enter the amount that you want to withdraw: "))
if withdrawAmount < 0:
print("Invalid amount!Enter amount greater than 0.")
elif withdrawAmount > accountBalance:
print("Insufficient Balance! You can't withdraw more than the account
balance.")
else:
accountBalance = accountBalance - withdrawAmount
return accountBalance
def displayTransactions(transAmount,transDesc,ICLimit,CCLimit):
if (len(transAmount) == 0):
print("There is no transactions.")
else:
i = 0
while (i < len(transAmount)):
print(transDesc[i], transAmount[i])
i += 1
print("Total Bill: ", (ICLimit - CCLimit))

def displayDetails():
print("Account Number: ", accountNumber)
print("Account Holder Name: ", holderName)
print("Account Balance: ", accountBalance)
print("Credit card Limit: ", creditLimit)

def payFromCreditCard(creditLimit):
tAmount = float(input("Enter the amount that you want to pay"))
if tAmount <= 0:
print("Invalid amount! Enter the amount greater than 0.")
elif tAmount > creditLimit:
print("You don't have sufficient limit to complete the transaction.")
else:
tDescription = input("Enter the transaction description: ")
transactionsAmount.append(tAmount)
transactionDesc.append(tDescription)
creditLimit = creditLimit - tAmount
print("You have successfully paid", tAmount, "at", tDescription)
return creditLimit

while (True):
choice = showMenuGetChoice()
if choice == 1:
accountBalance = depositAmount(accountBalance)
print("Account Balance: ", accountBalance)
elif choice == 2:
accountBalance = withdrawAmount(accountBalance)
print("Account Balance: ", accountBalance)
elif choice == 3:
creditLimit = payFromCreditCard(creditLimit)
print("Remaining Credit card limit: ",creditLimit)
elif choice == 4:
if (len(transactionsAmount)==0):
print("There is no pending bill.")
else:
print("Total Bill: ",(initialCreditcardLimit - creditLimit))
tBillAmount = float(input("Enter the amount that you want to pay: "))
if tBillAmount <= 0:
print("Invalid amount!Enter amount greater than 0.")
elif tBillAmount > accountBalance:
print("Insufficient Balance! You can't pay bill more than the
account balance.")
else:
creditLimit = creditLimit + tBillAmount
accountBalance = accountBalance - tBillAmount
print("Credit card limit: ",creditLimit)
print("Account Balance: ",accountBalance)
elif choice == 5:
displayTransactions(transactionsAmount,transactionDesc,initialCreditcardLimit,credi
tLimit)
elif choice == 6:
displayDetails()
elif choice == 7:
print("Thank you for using my system.")
break
else:
print("Error: Invalid choice! Enter choice from 1 to 7.")

You might also like