I'm trying to find the average of a list by using a for loop. I've done it with a while loop.
Is it possible to convert this into a for loop?
List_1 =[]
while (True):
val_1 = float( input("Enter a number: "))
List_1.append (val_1)
if len(List_1)>=5:
List_sum = sum(List_1)
List_avg = (List_sum / len(List_1))
print("AVG:",List_avg)
break
This is what I've come up with:
val_1 = int(input("Enter a number: " ))
List_1 = []
List_1.append (val_1)
List_sum = 0
List_len = 0
List_avg = 0
for i in range (List_1):
List_sum = sum(numbers)
List_len = len(numbers)
if len(numbers) >=5:
List_avg = List_sum / List_len
print (List_avg)
L = []
for _ in range(5):
L.append(float( input("Enter a number: ")))
print("The length is", len(L))
print("The total is", sum(L))
print("The average is", sum(L)/len(L))
Instead of checking for the end of the list (a length of 5 in your example) within the loop, loop over a range of that length (a list isn't an appropriate argument for the range function), and print the result afterward. You don't need to use a list, either.
list_len = 5
result = 0
for i in range(list_len):
result += float(input('Enter a number: '))
print(result/list_len)
Related
For school we have to make a code which shows the average of a certain list into another list but for some reason my list which should show the smaller numbers is empty, I don't know if it is possible but I tried using an extra variable which counts +1 to itself
from random import randint
kleiner = []
list = []
teller = 0
aantal = int(input("Hoeveel random getallen wilt u? "))
veelvoud = int(input("Welke veelvoud? "))
while len(list) < aantal:
getal = randint(1, 100)
if getal % veelvoud == 0:
list.append(getal)
gemiddelde = sum(list) / len(list)
while len(list) < aantal:
if list[teller] < gemiddelde:
kleiner.append(list[teller])
teller += 1
print(list)
print(list[::-1])
print(kleiner)
help is appreciated in advance.
2 things:
don't name a variable list as list is also a python type
the second while loop causes the issue, as the length of the list is by default equal to aantal as the list has already been created. So whatever is in the while loop is never executed. Rather you could just iterate over the list in a simple for loop
That makes:
from random import randint
kleiner = []
list_ = []
teller = 0
aantal = int(input("Hoeveel random getallen wilt u? "))
veelvoud = int(input("Welke veelvoud? "))
while len(list_) < aantal:
getal = randint(1, 100)
if getal % veelvoud == 0:
list_.append(getal)
gemiddelde = sum(list_) / len(list_)
for i in list_:
if i < gemiddelde:
kleiner.append(i)
print(list_)
print(list_[::-1])
print(kleiner)
Once you have the average (gemiddelde), you can build the resulting list using a list comprehension:
kleiner = [n for n in list_ if n < gemiddelde ]
If you want a list of random numbers that are a multiple of veelvoud <= 100, you can get that using the choices() function:
list_ = random.choices(range(velvoud,100,velvoud), k=aantal)
I created a code to print the largest number from a given input(string) but it is only valid for inputs containing distinct digits and gives an error 'string index out of range' when the input consists of repetitive digits. Why so?
Note: "The concept of list cannot be used"
My code is as follows:
def largest_num(num):
nums = ""
length = len(num)
while length:
max_num = num[0]
for i in num:
if i > max_num:
max_num = i
num = num.replace(max_num,"")
nums = nums + max_num
length-=1
return nums
x = input("Entered number: ")
a = largest_num(x)
print(a)
Output:
Output of above code
#Husnian Mehdi - the original code has error in the line - "num.replace(max_num, ""). You could put print statement after that to see what's happening when you input a number with duplicated digits: such as '454'. I also change some variable names to make it more descriptive. [Hint: that num.replace() statement has removed both duplicated digits....!]
def largest_num(num):
ans = ""
size = len(num)
while size:
max_digit = num[0]
for n in num[1:]:
if n > max_digit:
max_digit = n
ans = ans + max_digit
num = num.replace(max_digit, "")
print(f' num is: {num} now ...')
size -=1
print(f' len: {size}')
return ans
x = input("Entered number: ")
It's more straightforward to take the advantage of the fact that the input is a string, and string can be sorted easily. Please try the code next:
from functools import cmp_to_key
def largestNum(num):
num = [str(n) for n in num]
num.sort(key=cmp_to_key(lambda b, a: ((a+b)>(b+a))-((a+b)<(b+a)) ))
return ''.join(num).lstrip('0') or '0'
x = input("Entered number: ")
#a = largest_num(x)
print(largestNum(x))
Demo:
>>>Entered number: 321895
985321
>>>Entered number: 10957
97510
>>>Entered number: 4576889
9887654
>>>
Or simply do the sorting directly (you can convert this to function):
1. num = list(num). # num is string input of number
2. num = num.sort(reverse=True)
3. largest = int(‘’.join(num)) # answer
I have this code and I'm trying to print only one message with all the results, but instead is printing each message with the result which is getting awful.
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
for i in range(a, b + 1):
print('The Numbers in Ascending Order Are: ', i)
else:
for i in range(a, b - 1, -1):
print('The Numbers in Descending Order Are: ', i)
Don't print each item in a loop then.
Write instead.
Code
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
print(f'The Numbers in Ascending Order Are: {list(range(a, b+1))}')
else:
print(f'The Numbers in Descending Order Are: {list(range(a, b-1, -1))}')
Output
Another approach with for loop
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
temp = []
for i in range(a, b + 1):
temp.append(i)
print('The Numbers in Ascending Order Are: ', temp)
else:
temp = []
for i in range(a, b - 1, -1):
temp.append(i)
print('The Numbers in Descending Order Are: ', temp)
Output
First of all, print the order message before each for loop. Secondly, you can use range in the following way:
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
print('The Numbers in Ascending Order Are: ')
for i in range(a,b + 1): # adding 1 to include b
print(i)
else:
print('The Numbers in Descending Order Are:')
for i in range(a , b - 1, -1): # reducing 1 to include b
print(i)
Input:
First Integer: 1
Second Integer: 5
Output:
1
2
3
4
5
Input:
First Integer: 5
Second Integer: 1
Output:
5
4
3
2
1
To avoid repeating the message, take it out of the for loop, like this:
a = int(input("First Integer:"))
b = int(input("Second Integer:"))
if (a < b):
print("The numbers in ascending order are:")
for number in range(a, b + 1):
print(number)
else:
print("The numbers in descending order are:")
for number in range(a, b - 1, -1):
print(number)
Sample outputs:
First Integer:5
Second Integer:2
The numbers in descending order are:
5
4
3
2
First Integer:2
Second Integer:4
The numbers in ascending order are:
2
3
4
You can sort them:
a = int(input("First Integer"))
b = int(input("Second Integer"))
c = [a,b]
if a < b:
sorted(c)
else:
sorted(c,reverse=True)
You need to correct your second loop and each message should be issued with the result of the loop instead of per item.
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
asc = ", ".join([str(i) for i in range(a, b + 1)])
desc = ", ".join([str(i) for i in range(b, a - 1, -1)])
if a < b:
print(f'The Numbers in Ascending Order Are: {asc}')
print(f'The Numbers in Descending Order Are: {desc}')
I need to create a function that will print the smallest, largest,and average of n amount of numbers inputed by user.
My function, so far, can print the average and largest value of n amount of numbers entered by user but I'm stuck on finding the smallest value.
This is what I have so far:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=0
l_v=0
while counter<n:
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x>l_v:
l_v=x
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
As #Padraic mentioned, the answer that your posted to your question doesn't work for positive values, since your if-statement only checks if the min value is less that 0.
To fix this, you could just assign the first inputted value to all the variables. This way you wouldn't have to use positive and negative inf variables:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=0
f_v = l_v = s_v = total =int (input("enter first value")) #first value
while counter<(n-1):
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x<s_v: #find minimum
s_v=x
elif x>l_v: #find maximum
l_v=x
print ("the smallest value is {0}".format(s_v))
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
Now your code will run without any issues:
how many?5
enter first value-1
enter next number7
enter next number0
enter next number3
enter next number2
the smallest value is -1
the largest value is 7
('the average is ', 2.2)
You could add the items to a list while the user inputs data.
When the user is done, just use min(), max(), and sum() (and maybe len()) on the list.
Keep track of the lowest number also, set the start value to float(inf) for the min and float(-inf) for the max:
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm, counter = 0, 0
while counter < n:
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
counter += 1
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
You can also use a for loop with range:
n = int(input("how many?"))
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm = 0
for i in range(n):
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
Or using a list comp:
n = int(input("how many?"))
if n > 0:
nums = [int(input("enter next number")) for _ in range(n)]
print ("the largest value is {0}".format(min(nums)))
print("the average is ", sum(nums)/ n)
print("the min value is {}".format(min(nums)))
else:
print("What? it is not possible to find the average, sorry ")
sm += x is augmented assignment which the same as doing sm = sm + x.
When verifying user input and casting you should really use a try/except to catch any exceptions:
def get_num():
while True:
try:
n = int(input("enter next number"))
# user entered valid input, return n
return n
except ValueError:
# could not be cast to int, ask again
print("Not an interger")
while True:
try:
n = int(input("how many?"))
break
except ValueError:
print("Not an interger")
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm, counter = 0, 0
while counter < n:
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
counter += 1
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
This is what I ended up doing... Just kind of worked it out myself through trial and error.
I really appreciate the answers! Gives me a different way of looking at the problem!
Answer:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=1
l_v=0
s_v= 0
f_v = int (input("enter first value"))
while counter<n:
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x<f_v:
s_v=x
elif x>l_v:
l_v=x
print ("the smallest value is {0}".format(s_v))
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
Decided to help out with doing a lab for my buddy, first time ever doing this so please don't make fun of my code lol. I have to get a number "num" of how many numbers to add to array, then a total number. Then from that I want to add user defined numbers from the size of the array. Then if any of those numbers adds up to the total then print them out, else print sorry. Can't understand why it doesn't work :(
EXTRA EDIT: Problem is, my script does not show the numbers that add up to the total value, only the print('sorry')
edit: I learned prior to this java and C, couldn't figure out the foor loops or how variable types are instantiated.
num = int(input('Please enter the amount of numbers you wish to use: '))
total = int(input('Please the total wild card number: '))
hasValue = int(0)
ar = []
i = int(0)
j = int(0)
k = int(0)
l = int(0)
m = int(0)
while (i < num):
j = i + 1
inNum = input('Please enter number %d:' %j)
ar.append(inNum)
i = i + 1
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
if (hasValue == 0):
print('sorry, there no such pair of values')
As I got it, your current script is looking for two consequent numbers where sum equal to total, but should search for any pair in array, right? So if we have
ar = [1, 2, 3]
and
total = 5
program should display 2, 3 pair. But it will not find 1+3 for total=4.
Here are some general advices:
There is error in print invocation, where pair is printed (string should go first in str+int concatenation). Use format
print('%d, %d'.format(ar[k], ar[k])
or print result as tuple
print(ar[k], ar[l])
Use for k in range(num) instead of while
hasValue is better to be boolean value
Well, here is my solution (python2.7)
num = int(input("Array size: "))
sum = int(input("Search for: "))
a = []
found = False
# Fill array
for i in range(num):
a.append(int(input("Enter number #{}: ".format(i+1))))
# More effective algorithm - does not check same numbers twice
for i in range(num):
for j in range(i+1, num):
if a[i] + a[j] == sum:
print "{}, {}".format(a[i], a[j])
found = True
if not found:
print "Sorry..."
This is how to do for-loops in python:
for x in range(10):
# code for the for loop goes here
This is equivalent to:
for (int x = 0; x < 10; x++) {
// code for the for loop goes here
}
... in C++
(Notice how there is no initializing the variable 'x'. When you do a for loop, python automatically initializes it.
Here is what I think you wish to do:
def main():
num = int(input("Enter the amount of numbers: "))
total = int(input("Enter the total: "))
array = []
counter, elem = 0, 0
for user_numbers in range(num):
array.append(int(input("Please enter number: ")))
for each_element in array:
counter += each_element
elem += 1
if counter == total:
print(array[:elem])
break
if counter != total:
print("sorry...")
main()
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
Apart from the fact that the loops are not "pythonic", you need to initialize l = 0 within the k loop.
while (k < num):
l = 0
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
or slightly more python way:
for num1 in ar:
for num2 in ar:
if num1+num2==total:
print(num1 +' , '+ num2) # not sure about this syntax. I am a python beginner myself!
hasValue = hasValue + 1