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))
Related
I'm new to Python, so please bear with me. I'm trying to write a program involving a function that takes a number K as an input, reads K names one at a time, stores them into a list, and then prints them.
Not sure whether or not I should use a "for" or "while" loop, so I'm trying with "while" loop first.
k = input ("How many names?\n")
def names():
lst = []
while True:
name = input("Enter name:")
if = int(k)
break
return lst
names()
What I'm hoping to see is a list of names, and that list would be cut off after K number of names.
I've been receiving this error message:
File "<ipython-input-21-24a26badc1b5>", line 7
if = int(k)
^
SyntaxError: invalid syntax
The difference between while and for loops is thus:
If you want to do something a specific number of times, or once for every element in some collection, use a for loop.
If you want to do something an indefinite number of times, until a certain condition is met, use a while loop.
The way to implement what you want using a for loop is this:
k = input("How many names?\n")
def names():
lst = []
for i in range(int(k)): # creates a list `[0, 1, 2, ..., k-1]` and iterates through it, for `k` total iterations
name = input("Enter name:")
lst.append(name)
return lst
names()
Now, you could do this using a while loop - by setting a variable like x=0 beforehand, and increasing it by one for every iteration until x == k, but that's more verbose and harder to see at a glance than a for loop is.
#Green Cloak Guy explained very well why a for loop would be appropriate for your task. However if you do want to use a while loop you could do something like this:
def get_names(num_names):
names = []
i = 1
while i <= num_names: # equivalent to `for i in range(1, num_names + 1):`
current_name = input(f"Please enter name {i}: ")
names.append(current_name)
i += 1
return names
def main():
num_names = int(input("How many names are to be entered? "))
names = get_names(num_names)
print(f"The names are: {names}")
if __name__ == '__main__':
main()
Example Usage:
How many names are to be entered? 3
Please enter name 1: Adam
Please enter name 2: Bob
Please enter name 3: Charlie
The names are: ['Adam', 'Bob', 'Charlie']
Equality comparisons in Python are done with a
==
You also need some sort of thing to compare int(k) to. If you're trying to count loops you could do something like
x = 0
while True:
name = input("Enter name:")
lst.append(name)
x+= 1
if x== int(k)
break
That's exactly what a for loop is for - looping "for" a certain number of times. A while loop is for indefinite loops where you keep looping until something is no longer true.
Still, it might be instructive to see both, so you can better understand the difference. Here's the for loop. It will loop k times. See the Python wiki for more details.
k = int(input ("How many names?\n"))
def names():
lst = []
for i in range(k):
name = input("Enter name:")
lst.append(name) # I'm assuming you want to add each name to the end of lst
return lst
names()
And here's the same thing as a while loop. The loop continues until the loop condition is not true, so you just need to come up with a conditional that is true for the first k loops, and not thereafter. This will do:
k = int(input ("How many names?\n"))
def names():
lst = []
i = 0
while i < k:
name = input("Enter name:")
lst.append(name) # I'm assuming you want to add each name to the end of lst
i += 1
return lst
names()
Notice how in a while loop you have to initialise and increment the iterator (i) yourself, which is why a for loop is more suitable.
Finally, notice how neither example uses break. break is a fine way to end a loop, but if it's not necessary then you're better off not using it - generally it is only used to end a loop by exception (that is, for some reason that is not the main loop conditional). Using it for normal loop endings leads to less logical code that is harder to follow.
Hello friends of the internet,
I just began working in Python a few days ago and I am trying to create a starter program. All I am looking to do is create something that can take an input set of numbers (non-negative), from the user, and print the value of the highest number in the set.
I have read a few things about recursion functions that may be able to accomplish this task, but like I said, I'm a newby! If any of you professionals can show me something that can do just that I would be incredibly grateful.
def Max(list):
if len(list) == 1:
return list[0]
else:
m = Max(list[1:])
return m if m > list[0] else list[0]
def main():
list = eval(raw_input(" please enter a list of numbers: "))
print("the largest number is: ", Max(list))
main()
You have few issues in the code:
Don't use Python keywords like list as variable names
Don't use eval() when taking input from user
You can use built-in max() unless you want to create the function for educational purposes
So heres a better version of your code:
def main():
my_list = raw_input(" please enter a list of numbers: ").split()
my_list = map(int, my_list) # convert each item to int
print("the largest number is: ", max(my_list))
main()
If you are using Python3 change raw_input() to input() and if you are using Python2 change print('item1', 'item2') to print 'item1', 'item2'
EDIT:
You can use a generator expression with max() to do that too as the following:
def main():
my_list = raw_input(" please enter a list of numbers: ").split()
max_num = max(int(x) for x in my_list)
print("the largest number is: {}".format(max_num))
main()
Single line answer:
print (max(list(map(int,input().split()))))
Explanation:
a=raw_input() #Take input in string.
b=a.split() #Split string by space.
c=map(int,b) # Convert each token into int.
d=max(c) #Evalute max element from list using max function.
print (d)
Edit:
print (max(map(int,input().split())))
I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.
Just wondering how I would store the inputs for an average sum of square roots problem.
The user can input as many numbers as they until they type 'end'
here is what i have for that
while(True):
x = input("Enter a number please:")
if x == 'end':
break
You can append these values to a list. Sum and then divide by the length for the average.
nums = []
while True:
x = input("Enter a number:")
if x == 'end':
avg = sum(nums) / len(nums)
print("And the average is....", avg)
break
elif x.isdigit():
nums.append(int(x))
else:
print("Try again.")
The next thing you'd want to learn about is a data structure such a list. You can then add items to the list on the fly with list.append.
However, it's noteworthy that where ever you're learning Python from will certainly go over lists at one point or another.
If you mean that you want to store all the x values given, just use a list. l = [] l.append(x).
I am using python version 3.
For homework, I am trying to allow five digits of input from the user, then find the average of those digits. I have figured that part out (spent an hour learning about the map function, very cool).
The second part of the problem is to compare each individual element of the list to the average, then return the ones greater than the average.
I think the "if any" at the bottom will compare the numbers in the list to the Average, but I have no idea how to pull that value out to print it. You guys rock for all the help.
#Creating a list
my_numbers = [input("Enter a number: ") for i in range(5)]
#Finding sum
Total = sum(map(int, my_numbers))
#Finding the average
Average = Total/5
print ("The average is: ")
print (Average)
print ("The numbers greater than the average are: ")
if any in my_numbers > Average:
#Creating a list
my_numbers = []
r = range(5)
for i in r:
try:
my_numbers.append(int(input("Enter a number: ")))
except:
print( 'You must enter an integer' )
r.append(i)
#Finding sum
Total = sum(my_numbers)
#Finding the average
Average = Total/5
print ("The average is: ")
print (Average)
print ("The numbers greater than the average are: ")
print ([x for x in my_numbers if x>Average])
I'm sure that you would finally have succeeded in your code even if nobody hadn't answered.
My code is in fact to point out that you should foresee that entries could be non-integer and then to put instruction managing errors of entry.
The basic manner here is to use try except
Note the way I add i to r each time an error occurs in order to make up for the element of r that has been consumed.
Unfortunately, "if any" doesn't work. Take a look at the docs for the any function to se what it does. It doesn't do what you want even if your syntax had been correct. What you want is only the numbers greater than the average. You could use a list comprehension: [number for number in my_numbers if number > Average]. Or you could use a loop.
What you need to do is iterate through the list and print out the numbers above the average:
for i in my_numbers:
if int(i) > Average:
print(i)
To make things easier, you might also want to have the my_numbers list actually start out as a list of integers:
my_numbers = [int(input("Enter a number: ")) for i in range(5)]
Now we can get rid of the map function (don't worry, the hour did not go to waste, you'll find it very useful in other situations as well). You could also go straight to calculating the average without calculating the total, since you won't need the total again.
Average = sum(my_numbers) / 5
This means you can change the for loop so that you can replace int(i) with i.
You could also create a list with a list comprehension, and then print out the values in that list.
aboveAverage = [i for i in my_numbers if i > Average]
for i in aboveAverage:
print i