What is the use of globals() in this code? - python

d={}
for x in range(5):
globals()['int%s' % x] = int(input("Enter the marks of the students: "))
a = int0 + int1 + int2 + int3 + int4
print ("The average marks are ", a/5)
I don't understand the use of dictionary, globals() and ['int%s' % x] in this code. I'm very new to Python, and programming in general, so it would be very much appreciated if someone could answer this in a very simple language.
Thank you so much.

Don't worry, that's the twisted and worst code to learn any language I saw... I mean, if you are learning the first principles don't look at it for too long right now. When you get more practice, review this. That's just an advice. Anyway, I will explain to you line by line:
d={}
'''
here declares a variable with name d, and saves an empty dictionary to it...
I don't know why, because it is never used
'''
for x in range(5):
globals()['int%s' % x] = int(input("Enter the marks of the students: "))
'''
this is a loop that will be repeated 5 times, globals() is a dictionary
of all the variables in the scope that are alive with in the program...
so, globals()['int%s' % x] is creating a new key-value,
for example {'int0': 4}. It is a way to dynamically create variables, so,
the x will have the values [0,1,2,3,4], that's why the variables
will have the names int0, int1, int2, int3, int4.
Finally, it ask to the user to type a number,
and this number will be stored in one of those variables,
then the maths:
'''
a = int0 + int1 + int2 + int3 + int4
'''sum all the inputs from the user'''
print ("The average marks are ", a/5)
#divide it by 5
A posible way to achieve the same, but a little more generalized:
total=0
numberOfMarks = 5
for x in range(numberOfMarks):
mark = input("Enter the marks of the students: ")
while(not mark or not mark.isdigit()):
print("please, enter a number value representin the mark")
mark = (input("Enter the marks of the students: "))
total += int(mark)
print ("The average marks are ", total/numberOfMarks)

Related

How can I average several inputs?

I'm trying to code a calculator with several options, just for the leraning experience, and one of these options is 'average', I want the user to be able to input as many values as he wants to, but it's not working yet, what should I change?
This is my code for the average so far:
elif ui1 == subop1_2:
1 = [input("Input your values, separate with a comma").split(',')]
result = sum(1) / float(len(1))
print("The average is {}".format(result))
time.sleep(10)
Since there were a lot of things pointed out, here goes an answer.
num_list = input("Input your values, separate with a comma: ").split(',')
num_list = [float(elem) for elem in num_list]
result = sum(num_list) / float(len(num_list))
This will fail if the user enters an empty string or characters...
Every thing you wrote was perfectly fine except a few mistakes...
1) Change all 1s to a valid variable name. Lets say, a.
2) Remove the square brackets around the input() function
3) Add a this line before the line where you assign the variable, result.
a = [int(x) for x in a]
Here is the code,
a = input("Input your values, separate with a comma").split(',')
a = [int(x) for x in a]
result = sum(a) / float(len(a))
print("The average is {}".format(result))
first of all u cannot name a variable:1 change that to "a" or something and it should work out
I would do it like this:
inp = input("Input your values, separate with a comma")
values = list(map(float,inp.split(',')))
avg = sum(values)/len(values)
print("The average is {}".format(avg))

Python- Function that returns a value

Im really struggling with this question, can anyone help me write a code for this program? or at least say where am I going wrong? Ive tried a lot but can't seem to get the desired output.
This is the program description: Python 3 program that contains a function that receives three quiz scores and returns the average of these three scores to the main part of the Python program, where the average score is printed.
The code I've been trying:
def quizscores():
quiz1 = int(input("Enter quiz 1 score: "))
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
average = (quiz1 + quiz2 + quiz3) / 3
print (average)
return "average"
quizscores(quiz1,quiz2,quiz3)
One, you are returning a string, not the variable. Use return average instead of return "average". You also don't need the print() statement in the function... actually print() the function.
If you call a function the way you are doing it, you need to accept parameters and ask for input outside the function to prevent confusion. Use a loop as needed to repeatedly use the function without having to rerun it every time. So the final code would be:
def quiz_average(quiz1, quiz2, quiz3):
average = (quiz1 + quiz2 + quiz3) / 3
return average
quiz1 = int(input("Enter Quiz 1 score: "))
quiz2 = int(input("Enter Quiz 2 score: "))
quiz3 = int(input("Enter Quiz 3 score: "))
print(quiz_average(quiz1, quiz2, quiz3)) #Yes, variables can match the parameters
You are returning a string instead of the value. Try return average instead of return "average".
There are a few problems with your code:
your function has to accept parameters
you have to return the actual variable, not the name of the variable
you should ask those parameters and print the result outside of the function
Try something like this:
def quizscores(score1, score2, score3): # added parameters
average = (score1 + score2 + score3) / 3
return average # removed "quotes"
quiz1 = int(input("Enter quiz 1 score: ")) # moved to outside of function
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
print(quizscores(quiz1,quiz2,quiz3)) # print the result
An alternative answer to the already posted solutions could be to have the user input all of their test scores (separated by a comma) and then gets added up and divided by three using the sum method and division sign to get the average.
def main():
quizScores()
'''Method creates a scores array with all three scores separated
by a comma and them uses the sum method to add all them up to get
the total and then divides by 3 to get the average.
The statement is printed (to see the average) and also returned
to prevent a NoneType from occurring'''
def quizScores():
scores = map(int, input("Enter your three quiz scores: ").split(","))
answer = sum(scores) / 3
print (answer)
return answer
if __name__ == "__main__":
main()

Puzzled about why I can't add strings together

I am trying to write a program that gets user information and adds it to a list and then I want to total how many user inputs there were, but I can't do it. I have tried running an accumulator, but I get TypeError: unsupported operand type(s) for +: 'int' and 'str'.
def main():
#total = 0
cel_list = []
another_celeb = 'y'
while another_celeb == 'y' or another_celeb == 'Y':
celeb = input('Enter a favorite celebrity: ')
cel_list.append(celeb)
print('Would you like to add another celebrity?')
another_celeb = input('y = yes, done = no: ')
print()
print('These are the celebrities you added to the list:')
for celeb in cel_list:
print(celeb)
#total = total + celeb
#print('The number of celebrities you have added is:', total)
main()
Here is the output as desired without the accumulator, but I still need to add the input together. I have commented out the accumulator.
Enter a favorite celebrity: Brad Pitt
Would you like to add another celebrity?
y = yes, done = no: y
Enter a favorite celebrity: Jennifer Anniston
Would you like to add another celebrity?
y = yes, done = no: done
These are the celebrities you added to the list:
Brad Pitt
Jennifer Anniston
>>>
Thanks in advance for any suggestions.
Total is an integer ( declared earlier on as )
total = 0
As the error code suggest, you are trying to join an integer with a string. That is not allowed. To get pass this error, you may :
## convert total from int to str
output = str(total) + celeb
print(" the number of celebrities you have added is', output)
or even better you can try using string formatting
##output = str(total) + celeb
## using string formatting instead
print(" the number of celebrities you have added is %s %s', % (total, celeb))
I hope this will work for you
Python is a dynamically typed language. So, when you type total = 0, the variable total becomes an integer i.e Python assigns a type to a variable depending on the value it contains.
You can check the type of any variable in python using type(variable_name).
len(object) returns integer value.
for celeb in cel_list:
print(celeb)
#end of for loop
total = 0
total = total + len(cel_list) # int + int
print('The number of celebrities you have added is:', total)
You can get the number of entries in a Python list by using the len() function. So, just use the following:
print('These are the celebrities you added to the list:')
for celeb in cel_list:
print(celeb)
total = len(cel_list)
print('The number of celebrities you have added is: ' + str(total))
Note the decreased indentation of the last two lines - you only need to run them once, after you've finished printing out the celeb's names.

How to add a set of numbers that the user inputted in Python?

How do I add numbers in between two numbers the user inputted in Python 2.7. So a person would input 75 and 80 and I want my program to add the numbers in between those two numbers. I am very new to programming and python so any help would be awesome!
This example excludes 75 and 80. If you need to include them replace with print sum(range(n1,n2+1))
n1=input('Enter first number ')
n2=input('Enter second number ')
print sum(range(min(n1,n2)+1,max(n1,n2)))
#DSM is right!
n1=input('Enter first number ')
n2=input('Enter second number ')
print (n2-n1+1)*(n2+n1)/2
to capture user input use number1 = raw_input('Input number'). From there I'm not exactly sure what you mean from adding numbers between the two? If you want 76+77+78+79 in that example
number1 = raw_input('Input number')
number2 = raw_input('Second number')
result = 0
for n in range(int(number1)+1, int(number2)):
result+=n
print result
Here's a quick sample that should handle a few different situations. Didn't go that in-depth since I don't know the scope of the situation. Realistically you should do some form of type-checking and loop until valid input is entered. However this should get you started:
def sumNums(a, b):
total = 0
if a < b:
total = sum(range(a+1, b))
elif b < a:
total = sum(range(b+1, a))
return total
num1 = int(raw_input("First Number: "))
num2 = int(raw_input("Second Number: "))
print sumNums(num1, num2)
However I'm sure there's a more comprehensive way using lists and sum() but it seems like you only need a basic working example.
easy you just go
def add(x,y):
if True:
return add(x, y)
else:
return None
add([1,2,3,4][0], [1,2,3,4][2])

Running a loop (x) times

I am trying to loop an input for a selected amount of time "enter how may ingredients you want:" say if the user inputs 5 then a loop "ingredients" will run 5 times for them to enter their ingredients. Sorry if it seems like a basic question, but I'm quite new to this. Thanks for any answers :).
a=input("hello, welcome to the recipe calculator \nenter your recipe name, number of people you will serve and the list of ingredients \n1.retrive recipe \n2.make recipe \noption:")
if a=="2":
print("now enter the name of your recipe")
f=open('c:\\username_and_password.txt', 'w')
stuff = input("create name:")
nextstuff = (int(input("enter number of people:")))
nextstufff = (int(input("enter how many ingredients you want:")))
for (nextstufff) in range(0, 10): #I have put 0, 10 because the user probably wont put more than 10 ingredients. But there's probably a much better way?
print ("ingredient") + (nextstufff) #what am I doing wrong in this for loop
nextstuffff = (int(input("so how much of\n" + nextstufff + "would you like:")))
f.write(str(stuff + "\n") + str(nextstuff) + str(nextstufff))
f.close()
It would be difficult to cleanly answer your question(s) -- so I'll focus specifically on the looping over ingredients question. This should get you pointed in the right direction.
def read_items(prompt):
items = []
while True:
answer = raw_input('%s (blank to end): ' % prompt)
if not answer:
return items
items.append(answer)
ingredients = read_items('enter ingredients')
counts = []
for item in ingredients:
cnt = raw_input('how much of %s:' % item)
counts.append(int(cnt))
print zip(ingredients, counts)
it's not print ("ingredient") + (nextstufff), change it to print ("ingredient:", nextstufff).
Or you can use string formatting:
print ("ingredient: %d"%nextstufff)

Categories

Resources