Python

As the internet has helped me trying to learn Python I thought to publish the answers to my first assignment so that it might help others. We often search for information, for me recently it’s been how to code Python. I’m a beginner, perhaps these questions can be answered much better. So here’s the assignment, it may help someone, as payback for the help I’ve found…


1

Write a function smaller_num() that takes in two number parameters to determine and return the smaller number.

def smaller_number(num1 = int, num2 = int):
result = str
if num1 == num2:
result = (‘equal’)
if num1 < num2:
result = (num1)
if num1 > num2:
result = (num2)
return(result)


2

Write a program to do the followings: Ask user for two numbers. Use the function in Q1 to determine the smaller number and display the result.

def smaller_number(num1 = int, num2 = int):
result = str
if num1 == num2:
result = (‘equal’)
if num1 < num2:
result = (num1)
if num1 > num2:
result = (num2)
return(result)
num1 = int(input(‘please provide a first number’))
num2 = int(input(‘please provide a second number’))
smaller = smaller_num (num1, num2)
print(‘The smaller number is’, smaller)


3

Write a function named getPrice() that takes in gender and age parameters to determine and return the price that a person has to pay for the meal.

def getprice(gender = str, age = int):
price = int
if gender[0] == ‘m’:
if age < 12 :
price = 12
if age >= 12:
price = 20
if gender == ‘f’:
if age < 12 :
price = 10
if age >= 12:
price = 18
return(price)


4

Write the code to do the following: Calculate the total cost for a family outing with the following members using the getPrice()function that you have defined in the Q3.

Display the total cost for the buffet meal for this family

def getprice(gender = str, age = int):
price = int
if gender[0] == ‘m’:
if age < 12 :
price = 12
if age >= 12:
price = 20
if gender == ‘f’:
if age < 12 :
price = 10
if age >= 12:
price = 18
return(price)
total_cost = int(getprice(‘m’, 42) + getprice(‘f’, 40) +
getprice(‘f’, 11) + getprice(‘f’, 10))
print(total_cost)


5

sentence = “Alibaba.com’s profit surges on revived business spending in 2018”
words = … # continue your code from here
Suppose the above codes are at the start of a python program. Write the code that follows to achieve the following:

  • Extracted all the individual words from the sentence before assign them to the words variable.
  • Print “Alibaba.com’s revived business in 2018” using the words variable.
  • Print the number of words in the string sentence.

sentence = “Alibaba.com’s profit surges on revived business
spending in 2018″
words = sentence.split()
print(*words, sep=’ ‘)
print(len(words))


6

A name is in the format of: First Name, Second Name, Third Name
Lucky Number = (F + 3*S) % 10 + T where F = Length of first name
S = Length of second name•
T = Length of third name

Write a function calculateLuckyNumber that takes in name as a parameter to calculate and return the lucky number using the formula given. Write a program to request a name from the user, call the function calculateLuckyNumber and print the lucky number you have computed.

def calculateluckynum(f, s, t):
luckynum = (f + 3 / 10 + t)
return (luckynum);
fnam = input(‘first name?’)
mnam = input(‘middle name?’)
tnam = input(‘last name?’)
fnum = int(len(fnam))
mnum = int(len(mnam))
tnum = int(len(tnam))
luckynum = (calculateluckynum(fnum, mnum, tnum))
print(luckynum)


7

Write a function calculateAverage that take in a list of 15 numbers as parameter and return the average of this 15 numbers using for or while loop.

def calculate_average(a):
total = 0
ind = 0
while ind < 3:
total = total + numbers[ind]
ind = ind + 1
average = total / 15
return(average)
count = 0
numbers = []
while count < 15:
try:
numbers.append(int(input(“Please enter 15 integer: “)))
count = count + 1
except ValueError:
print(“Not an integer”)
print(‘Average = ‘, calculate_average(numbers))


8

Write the function countLetter that takes in a sentence and a letter as arguments, and call the function to return the number of occurrence of the letter value in the word.

def count_letters(sentence, letter):
number = 0
count = 0
while count != len(sentence):
if sentence[count] == letter[0]:
number = number + 1;
count = count + 1
return(number)
sentence = str(input(“Input the sentence \n”))
letter = input(“The character to count \n”)
b = count_letters(sentence, letter)
print(b)


9

The flowchart below represents a computer program to determine the percentage of compensation based on the total number of defects reported by the user. Write a Python program based strictly on the structure of the flowchart to display the respective outputs.

defects = int (input (‘how many defects?’))
if defects > 50:
print(“15% off”);
elif defects > 30:
print(“10% off”);
elif defects > 10:
print(“3% off”);
else: print(“no compensation”);


10

Write a function getVowels that takes in a word as argument and returns the vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) in lowercase and in the order of appearance in the word using a list. The sample outputs are given below:

characters = []
def get_vowels(str):
count = len(str)
while count <= len(str):
if “a” in str:
characters.append(‘a’)
count = count + 1
if ‘e’in str:
characters.append(‘e’)
count = count + 1
if ‘i’in str:
characters.append(‘i’)
count = count + 1
if ‘o’in str:
characters.append(‘o’)
count = count + 1
if ‘u’in str:
characters.append(‘u’)
count = count + 1
return(characters)
get_vowels(‘a bigger test’)
print(characters)


11

The health promotion board has engage the elderlies to promote active living. Participants who are taking part in a series of activities will be awarded credit points. These credit points accumulated can be used to exchange for discount vouchers in the supermarkets.

The allocation of credit points for each activity in active living is as follows:
The following shows a sample input/output of the program:

Draw a flowchart to query the number of activities that an elderly has attended and the duration (in minutes) for each activity. The program will display the credit points for each activity and the total credit points that the elderly has accumulated.


12

From the table provided in Q11, write a function called get_credits that takes in one parameter tTime as the duration of the activity. The function return the credit points to be awarded based on the duration (in minutes). The program shall return zero if less than 30 minutes of the activity are logged. The program shall also return zero if negative time is entered.

def get_credits(tTime: int):
credits = tTime
if tTime >= 180:
credits = 2
if tTime >= 120:
credits = 1.5
if tTime >= 120:
credits = 1
if tTime >= 60:
credits = .5
if tTime >= 30:
credits = .5
if tTime < 30:
credits = 0
return(credits)


13

Write a Python program according to the flowchart you drew in Q11. Note that your answer must call the function get_credits you produced in Q12.

def get_credits(tTime: int):
credits = tTime
if tTime >= 180:
credits = 2
if tTime >= 120:
credits = 1.5
if tTime >= 120:
credits = 1
if tTime >= 60:
credits = .5
if tTime >= 30:
credits = .5
if tTime < 30:
credits = 0
return(credits)
number = int(input(‘How many activities did you do? \n’))
count = 0
rows = 3
columns = 1
matrix = [‘-‘ for x in range (rows) for y in range (columns)]
while number > 0:
time = 0 name = str(input(‘What was the name of activity {} \n’
.format(number )))
time = int(input(‘How long was it was it? \n’))
matrix.append(number)
matrix.append(name)
matrix.append(time)
number = number – 1
get_credits(time)
import pandas as pd
matrix = pd.DataFrame(matrix)
print(matrix[3:6])

Comment - nothing required, just click post comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s