PYTHON 1.) Write a program that lets the user input integers one at a time at th
ID: 3594277 • Letter: P
Question
PYTHON
1.) Write a program that lets the user input integers one at a time at the keyboard until they type the word done on a line by itself. Print the sum of the values entered. You may assume the user will only enter integers or "done".
For example:
2.) A variable num has already been defined. Write a while loop which calculates the sum of the perfect squares less than or equal to num. Store the result in the variable acc.
For example, if num is 10, then acc should be 1+4+9=14.
For example:
3.)
Use the Design Recipe to write a function, print_histogram, that takes a list of numbers and prints a histogram graph using asterisks to represent each number in the list. Use one output line per number in the list.
For example:
4.) Use the Design Recipe to write a function, sum_between, that takes a list and two numbers, a and b, and returns the sum of the numbers in the list that are between a and b (inclusive of both a and b).
For example:
5.) Use the Design Recipe to write a function total_numbers(number_list,weights) that takes a list of numbers and their weights and returns the weighted total of the numbers. Think about what needs to happen before using a loop, during the loop, and after the loop finishes. In this question you are required to use a for loop, and not allowed to use the sum function. If the numbers are [1,2,3] and the weights are [.1,.5,.4] then the weighted total should be 1 * .1 + 2 * .5 + 3 * .4 = 2.3
For example:
Input Result 35
done 8
Explanation / Answer
My Answer for question number one as below :
Program :
------------------
user_prompt = 'Enter a number: '
total = 0
while True:
s = raw_input(user_prompt)
if s == 'DONE' or s == 'done':
break
try: ''' Try and except block for user to prompt as invalid input '''
total += float(s)
except ValueError:
print "Invalid Input. Try again: "
print total
Solution for program number 2 :
-------------------------------------------
inp = int(input('Enter a number:'))
for i in range(1,inp+1):
if (i**0.5)**2 == i: ''' First I am finding sqrt of a given number and then finding square of the result'''
print i
Soultion for question number 4 :
-----------------------------------------
Program :
def sum_between(list1,a,b):
total = 0
for x in list1:
if x>=a and x <=b:
total += x
return total
print(sum_between([-17, -20, -33, 40],-18,60))
answer : 23
Solution for 5th question as follows :
-------------------------------------------------
def total_numbers(number_list,weights):
total=0
for i in range(0,len(number_list)):
total+=float(number_list[i]*weights[i])
return total
print (round(total_numbers([1,2,3],[.1,.5,.4]),1))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.