I'm working on a Python assignment and I'm totally stuck. Any assistance would be greatly appreciated. I know it's probably not as convoluted as it seems in my head... The details are below. Thanks very much.
Implement the following three functions (you should use an appropriate looping construct to compute the averages):
allNumAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list.
posNumAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list that are greater than zero.
nonPosAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list that are less than or equal to zero.
Write a program that asks the user to enter some numbers (positives, negatives and zeros). Your program should NOT ask the user to enter a fixed number of numbers. Also it should NOT ask for the number of numbers the user wants to enter. But rather it should ask the user to enter a few numbers and end with -9999 (a sentinel value). The user can enter the numbers in any order. Your program should NOT ask the user to enter the positive and the negative numbers separately.
Your program then should create a list with the numbers entered (make sure NOT to include the sentinel value (-9999) in this list) and output the list and a dictionary with the following Key-Value pairs (using the input list and the above functions):
Key = 'AvgPositive' : Value = the average of all the positive numbers
Key = 'AvgNonPos' : Value = the average of all the non-positive numbers
Key = 'AvgAllNum' : Value = the average of all the numbers
Sample run:
Enter a number (-9999 to end): 4
Enter a number (-9999 to end): -3
Enter a number (-9999 to end): -15
Enter a number (-9999 to end): 0
Enter a number (-9999 to end): 10
Enter a number (-9999 to end): 22
Enter a number (-9999 to end): -9999
The list of all numbers entered is:
[4, -3, -15, 0, 10, 22]
The dictionary with averages is:
{'AvgPositive': 12.0, 'AvgNonPos': -6.0, 'AvgAllNum': 3.0}
EDIT: This is what I have so far, which I did pretty quick just to have a something to work with but I can't figure out how to implement the keys/dictionary like the assignment asks. Thanks again for any help.
print("This program takes user-given numbers and calculates the average")
counter = 0
sum_of_numbers = 0
first_question = int(input('Please enter a number. (Enter -9999 to end):'))
while first_question != -9999 :
ent_num = int(input('Please enter a number. (Enter -9999 to end):'))
sum_of_numbers = sum_of_numbers + ent_num
counter = counter + 1
first_question = int(input('Please enter a number (Enter -9999 to end):'))
print("Your average is " + str(sum_of_numbers/counter))
Welcome to Python programming, and programming in general!
From your code, I assume you are not entirely familiar with Python lists, dictionaries, and functions and how to use them. I'd suggest you look up tutorials for these; knowing how to use them will make your assignment much easier.
Here are some tutorials I found with some quick searches that might help:
Dictionary Tutorial,
List Tutorial,
Function Tutorial
When your assignment says to make three functions, you should probably make actual functions rather than trying to fit the functionality into your loop. For example, here is a simple function that takes in a number and adds 5 to it, then returns it:
def addFive(number):
return number + 5
To use it in your code, you would have something like this:
num = 6 # num is now 6
num = addFive(num) # num is now 11
So what you should do is create a list object containing all the numbers the user entered, and then pass that object into three separate functions - posNumAvg, nonPosAvg, allNumAvg.
Creating a dictionary of key-value pairs is pretty easy - first create the dictionary, then fill it with the appropriate values. For example, here is how I would create a dictionary like {'Hello': 'World'}
values = {}
values['Hello'] = 'World'
print(values) # Will print out {'Hello': 'World'}
So all you need to do is for each of the three values you need, assign the result of the function call to the appropriate key.
If this doesn't feel like quite enough for you to figure out this assignment, read the tutorials again and play with lists, dictionarys, and functions to try and get a feel for them. Good luck!
P.S. The append method of lists will be helpful to you. Try to figure out how to use it!
Related
I have a set of numbers which is generated real-time during running the code. In the snippet of code shown below with the function constant_set, the number generated real time are stored in the variable set_accepted_list_frozen. What i want to ask is, if i want to keep a constant number always in the set_accepted_list_frozen before the other numbers are appended to the list set_accepted_list_frozen, how should i proceed?
set_accepted_list_frozen = set()
def constant_set(set_accepted_list,set_forbidden_list):
global set_accepted_list_frozen
if num_accepted >= len(set_accepted_list_frozen):
for var in set_accepted_list:
if len(set_accepted_list_frozen) == num_accepted:
break
set_accepted_list_frozen.add(var)
I am really having a hard time with loop statements for python, please see below:
I want it to check the users age, so if they are over 18, it will say "old enough, if they are over 16, it will say "almost there" and if they are younger than this, it will say "sorry you're too young"
I got the following code below:
age = int(raw_input("Enter your age:"))
if age >= 18:
print "You are old enough!"
elif age >= 16:
print "Almost there"
else:
print "You're just too young"
my problem is, how do I write code the includes an if statement and a for loop that will print out all the numbers from 0 that are less than the user's inputted age?
do I say:
for age in range (0,num)
if num <= age
print ....
else:
print...
Please kindly help. I'm new at this and still learning :(
So you could construct a variable that contains a list of numbers that is smaller than the user's age. You can construct this using python's range function; something like range(age) would do this nicely.
Then you need to use a for loop to loop through all these numbers and print them to the command line. Something like for x in range(age) would be a good place to start.
Then, in the loop, you'd just need to turn x from an integer into a string using the str() function, and print it to the command line.
So as pseudo-code:
if the age is greater than 18:
print that they're old enough
else if the age is greater than 16:
print that they're nearly old enough
otherwise:
print that they're not old enough.
for each number between 0 and age:
print the number
Come back when you have some code and we can help you with any trouble you have.
I'm a new programmer and I'm having a difficult time finishing up my 4th program. The premise was to create a program that would take input from the user, creating a list then compares this list to a tuple. After it prints a statement letting the user know which items they chose correspond to the items in the tuple and also in which position they are in the tuple.
The problem I'm having is the last part, I can't get the correct position to print right and I fail to understand why. For example, if someone chose GPS correctly during their guesses, it should print position 0, but it doesn't. If water is chosen, it says it's in position 13...but it should be 5.
#here is the code I have so far:
number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user
survival_gear = () #this is the tuple that will be compared against
survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")
#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in case of a survival situation, think Bear Grylls. Once chosen, your list will be compared to the top 10 survival items list.")
while number_items_input < 10:
print("Please choose.")
guessed_items = input()
guessed_inventory_list.append(guessed_items)
number_items_input = number_items_input + 1
print ("You have chosen the following:", guessed_inventory_list)
#block of code below here compares the input to the tuple
t = 1
while t < 1:
t = t + 1
for individual_items in guessed_inventory_list:
for top_items in survival_gear:
if individual_items == top_items:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print ("You have chosen wisely", top_items)
print ("It's in position", t, "on the survival list")
t = t + 1
The reason you are getting a wrong index is because of the wrong nesting of loops , your outer loop should be the tuple you wish to compare and the inner loop should be the list generated from the input where as in this case it is reverse, see the below corrected code snippet
Code snippet:
for top_items in survival_gear:
for individual_items in guessed_inventory_list:
if individual_items == top_items:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print ("You have chosen wisely", top_items)
print ("It's in position", t, "on the survival list")
t = t + 1
The above code snippet should solve your problem , but your code contains
while loop which can be avoided using the range built in function
Incrementing the variable t manually can be avoided by using enumerate built in function
The nested forloop and if loop can be replaced by using the "in" membership test operator
Find the below updated code:
#!/usr/bin/python
number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user
survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")
#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in caseof a survival situation, think Bear Grylls.Once chosen, your list will be compared to the top 10 survival items list.")
# One can use range functions to loop n times in this case 10 times
for i in range(0,10):
guessed_items = raw_input("Please choose:")
guessed_inventory_list.append(guessed_items)
print ("You have chosen the following:", guessed_inventory_list)
# Enumerate is one of the built-in Python functions.
# It returns an enumerate object.
# In this case that object is a list of tuples (immutable lists),
# each containing a pair of count/index and value.
# like [(1, 'GPS'), (2, 'map'), (3, 'compass'),...,(6, 'signal mirror')]
# in the below for loop the list of tuple will be
#unpacked in to t and individual_items for each iteration
for t,individual_items in enumerate(survival_gear,start=1):
#the "in" is a membership test operator which will test whether
#individual_items is in list guessed_inventory_list
if individual_items in guessed_inventory_list:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print("You have chosen wisely", individual_items)
print("It's in position", t, "on the survival list")
I am fairly new to python and was wondering how to make this loop run for a the number of iterations that is entered by the user, however it is an infinite loop at the moment:
def randMod():
import random
heads = 0
tails = 0
tries = raw_input('Enter a number:')
while True:
runs = 0
if tries == runs:
break
else:
runs + 1
coinFlip = random.randrange(0,1+1)
if coinFlip == 0:
print "Tails"
tails + 1
elif coinFlip == 1:
print "Heads"
heads + 1
print heads
print tails
randMod()
I am trying to make it so it will simulate a coin flip for how many times the user enters then tallies it at the end. Only problem is I am fairly new to python so I don't know if I got this right or not.
The problem I see here is that you are using raw_input() to read the user's input. That method stores the input as a string. You must convert the information contained in tries to a number in order for this to work. As it is comparing tries == runs and a string will never be equal to a int, it is stuck forever.
You can use the conversion like this:
Explained here
I have to create a function that takes an input, and returns a corresponding Grade.
So for example if the user inputs A+ output is 90%
or
if the input is A output is 80%
or
if the input is B output is 70%
I have some sort of Idea on how to do this... but I am having trouble on wrapping my head around on how I can return the statement??
def percent (percentage):
if ( percentage )== A+
return ("90%")
elif (percentage)== A
return ("80%")
Is this the correct way of going about it?
OK, so first, welcome to Python. Second, this is Pythonic way of doing this - define a dict:
grades = {'A+': "90%", 'A': "80%", ...}
then
return grades[precentage]
will do the job.
You need to protect against the case where the grade is not in the dict, for example, if the user entered some mistake, like G. There are a few ways to go about that:
A simple if:
if precentage in grades:
return grades[precentage]
else:
return "bad precentage"
After you get used to Python you will be more aesthetic about your code and will want to do better than state twice bote grades and precentage, so you can do simply:
return grades.get(precentage, "bad precentage")
Or using a special dict with default values:
import collections
grades = collections.defaultdict(lambda: "bad precentage", [("A+", "90%"), ("A", "80%")])
then
grades[precentage]
will automatically return "bad precentage" upon bad input.
#user2829744 You don't want to have to repeatedly call if statements based on what the percentage is, that would make the code unnecessarily long.
Instead, you want to have a list or tuple (a variable which stores multiple elements) that the program can compare the user's inputted value to, and then calculate the percentage mark.
Take this for example:
def percentage(per):
grades=["A+","A","B","C","D","E","F"]
percentage=("90%","80%","70%","60%","50%","40%","30%")
for i in range(7):
if per.upper()==grades[i]:
return percentage[i]
d="a"
print(percentage(d))
What happens is that i counts up to the number seven, and if the value of i in grades (let's say i is 5, then that would be grades[5] which would be an "E") then the function returns the value of i in the percentage tuple. In my case, the interpreter outputs 80%
Logically, your way of going about it (by actually dealing with every grade possible in separate if statements) would work too, however like I said your code would be longer and chances are you'd make a few typos along the way that you'd have to edit. Of course, my code has a few problems too, like what if the user enters a grade which I don't have in the tuple. This is easily fixable though as you would just need to tell the interpreter what to do if that happens.
A bit brief I know, but I hope this helps
You could do something like this
user_input = int(input("percentage: ")
if user_input < 0 and user_input > 10:
print('F")
And then you can just duplicate the code and change the numbers and the return grade
Hope it helps :)