So I'm writing some code for my class and have to have a list of floats that are input by a user and print them out with normal iteration and reverse iteration, and I have basically all of it done. But when it should ask multiple times for the user input, it only asks one time then prints everything out and finishes without asking multiple times.
Any help would be appreciated as to why it isnt asking multiple times for input even though I have a for loop?
Is there an easier way to get a list of floats from user input that I don't know about?
Thanks
emptyList = []
userInput = high = low = total = float(input("Input a float > "))
emptyList.append(userInput)
for y in range(len(emptyList)-1):
userInput = float(input("Input a float > "))
emptyList.append(userInput)
total += emptyList
if userInput > high:
high = userInput
if userInput < low:
low = userInput
avg = total / len(emptyList)
above_avg = below_avg = 0
for y in range(len(emptyList)):
if emptyList[y] > avg:
above_avg += 1
if emptyList[y] < avg:
below_avg += 1
I checked your logic and according to that you are running your first for loop to the length of emptyList-1 so, after adding one element your emptylist's length becomes 1 and 1-1=0 so, your for loop will work only to 0th index and after that it will break.
I tried this
a=[]
b = []
t=0
count = 0
total = 0
for i in range(0,5):
x= float(input())
count = count + 1
total = total+ x
a.append(x)
print(count)
for i in range(count-1,-1,-1):
print('Aya')
print (i)
b.append(a[i])
for i in range(0,count-1):
for j in range(i,count):
if(a[i]>a[j]):
t=a[i]
a[i]=a[j]
a[j]=t
print(a)
print(b)
print(total)
print(total/count)
print(a[0])
and found it working perfectly fine for me and my for loop is taking values on every iteration.
You may try like this:
n = int(input("Number of inputs: "))
emptyList = []
while n:
userInput = float(input("Enter a Float > "))
emptyList.append(userInput)
n-=1
print(emptyList)
Related
i have to write a program with a loop that asks the user to enter a series of positive numbers. the user should enter a negative number to signal the end of the series, and after all positive numbers have been entered, the program should display their sum.
i don't know what to do after this, or whether this is even right (probably isn't):
x = input("numbers: ")
lst = []
for i in x:
if i > 0:
i.insert(lst)
if i < 0:
break
you should use input in the loop to enter the intergers.
lst = []
while True:
x = int(input('numbers:'))
if x > 0:
lst.append(x)
if x < 0:
print(sum(lst))
break
def series():
sum1 = 0
while True:
number = int(input("Choose a number, -1 to quit:"))
if number>=0:
sum1+=number
else:
return sum1
series()
while True means that the algorithm has to keep entering the loop until something breaks it or a value is returned which ends the algorithm.
Therefore, while True keep asking for an integer input , if the given integer is positive or equal to zero, add them to a sum1 , else return this accumulated sum1
You can use a while loop and check this condition constantly.
i, total = 0, 0
while i>=0:
total+=i
i = int(input('enter number:'))
print(total)
Also, don't use:
for loop for tasks you don't know exactly how many times it is going to loop
while loop as while True unless absolutely necessary. It's more prone to errors.
variable names that have the same name as some built-in functions or are reserved in some other ways. The most common ones I see are id, sum & list.
do you want that type of code
sum_=0
while True:
x=int(input())
if x<0:
break
sum_+=x
print(sum_)
Output:
2
0
3
4
5
-1
14
if you want a negative number as a break of input loop
convert string to list; input().split()
convert type from string to int or folat; map(int, input().split())
if you want only sum, it is simple to calculate only sum
x = map(int, input("numbers: ").split())
ans = 0
for i in x:
if i >= 0:
ans += i
if i < 0:
break
print(ans)
I'm really new to coding (as in about 3 weeks in), and I'm writing a code where the user is asked to input a number between 0 and 100 and then this number is added to a list. Once the list reaches a length of 10 numbers, it should print the list. I'm using a function to this.
I can get it so it prints a list, but it's only printing the first number that is input. For example if I enter 5, it'll still ask for the other numbers, but it prints the list as [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]. Also if I enter a number outside the range of 0-100 it does ask you to input a different number, but then it stops and prints the list as 'None'.
Below is my code:
def getUser(n):
mylist = []
while 0 < n < 100:
mylist.append(n)
int(input("Please enter a number between 0 and 100: "))
if len(mylist) == 10:
return(mylist)
else:
int(input("This number is not in the range of 0-100, please input a different number: "))
n = int(input("Please enter a number between 0 and 100: "))
print("The numbers you have entered are: ", getUser(n))
I'm guessing its to do with the while/else loop but as I said I'm new to this and it all feels so overwhelming, and trying to google this just seems to bring about super complicated things that I don't understand!! Thanks
First : Why you get [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] :
int(input("Please enter a number between 0 and 100: "))
You should give this to n first :
n=int(input("Please enter a number between 0 and 100: "))
Then, it gets out of the loops because you go in the else, and then you don't go back in the while. Then your function ended, without return, so none
To be honest, I don't understand why your code gets out of the while loop if you give a number out of the range, as the value is not given to n. If someone could explain in comment, that would be great !
I would do it like that :
def getUser():
mylist = []
while len(mylist) < 10:
n = int(input("Please enter a number between 0 and 100: "))
if (0 < n < 100):
mylist.append(n)
else:
print('This is not between 0 and 100 !')
return mylist
print("The numbers you have entered are: ", getUser())
Then you will be asked number from 0 to 100 (excluded) until you get a size of 10.
So here's what you were doing wrong
def getUser(n):
mylist = []
while 0 < n < 100:
mylist.append(n)
n = int(input("Please enter a number between 0 and 100: "))
if len(mylist) == 10:
return(mylist)
else:
int(input("This number is not in the range of 0-100, please input a different number: "))
n = int(input("Please enter a number between 0 and 100: "))
print("The numbers you have entered are: ", getUser(n))
You notice any difference in the edited code?
You were never re-assigning the value of the variable n
So you would just add whatever value you passed to getUser every time (and it would be the same value every time)
Don't be afraid to ask for help if you're stuck!
P.S.
You can also move a line somewhere to somewhere else to make it behave a bit better if you're up to the challenge ;)
def getUser(n):
mylist = []
t = True
while t:
n =int(input("Please enter a number between 0 and 100: "))
if n >0 and n<=100:
mylist.append(n)
if len(mylist) == 10:
return(mylist)
t = False
elif n < 0 or n >100:
print('This number is not in the range of 0-100, please input a different number:')
Ok, you are trying to use while instead of if.
Here is what I would do - I will explain it soon:
def get_user():
mylist = []
for i in range(5):
n = int(input("Please enter a number between 0 and 100: "))
if n <= 100 and 0 <= n:
mylist.append(n)
else:
print("This is not between 0 and 100 !")
i = i - 1
return mylist
Going through the code
for i in range(5)
Here we use the for to iterate through a range
of numbers (0 - 5). for will assign i to the smallest
number in the range and constantly add 1 to i every iteration until
i is out of the range. See this for more info on range
if n <= 100 and 0 <= n:
Here and checks if 2 expressions are true.
In this case, if n is less than or equal to hundred and more than or equal to 0.
You could use and any number of times you want like this:
if 1 < 100 and 100 > 200 and 20 < 40:
print("foo!")
Now look at the else :
else:
i = i - 1
Here, we subtract 1 from i and thus, decreasing our progress by one.
Also note that my function is called get_user() and not getUser().
In python, we use snake case and not camel case.
I hope this answer helps. I have given small hints in my answer.
You should google them! I also am not directly giving you the logic.
Try to figure it out! That way you would have a good understanding of what I did.
What this is supposed to do is:
To ask the user for numbers using while loop until they enter 0
when 0 is pressed we need to print the average of the numbers entered so far.
(Kindly help)
import statistics as st
provided_numbers = []
while True:
number = int(input('Write a number'))
if number == 0:
break
else:
provided_numbers.append(number)
print(f'Typed numbers: {provided_numbers}')
print(f'The average of the provided numbers is {st.mean(provided_numbers)}')
Take each number and print the average so far and stop it when input is zero, right?
s = 0
count = 0
while True:
num = int(input('Write a number: '))
if num == 0:
break
s += num
count += 1
print("Average so far:",(s/count))
Could you add a piece of code you have tried or sample input and output too?
My task is to:
"Write a program that will keep asking the user for some numbers.
If the user hits enter/return without typing anything, the program stops and prints the average of all the numbers that were given. The average should be given to 2 decimal places.
If at any point a 0 is entered, that should not be included in the calculation of the average"
I've been trying for a while, but I can't figure out how to make the programs act on anything I instruct when the user hits 'enter' or for it to ignore the 0.
This is my current code:
count = 0
sum = 0
number = 1
while number >= 0:
number = int(input())
if number == '\n':
print ('hey')
break
if number > 0:
sum = sum + number
count= count + 1
elif number == 0:
count= count + 1
number += 1
avg = str((sum/count))
print('Average is {:.2f}'.format(avg))
You're very close! Almost all of it is perfect!
Here is some more pythonic code, that works.
I've put comments explaining changes:
count = 0
sum = 0
# no longer need to say number = 1
while True: # no need to check for input number >= 0 here
number = input()
if number = '': # user just hit enter key, input left blank
print('hey')
break
if number != 0:
sum += int(number) # same as sum = sum + number
count += 1 # same as count = count + 1
# if number is 0, we don't do anything!
print(f'Average is {count/sum:.2f}') # same as '... {:.2f} ...'.format(count/sum)
Why your code didn't work:
When a user just presses enter instead of typing a number, the input() function doesn't return '\n', rather it returns ''.
I really hope this helps you learn!
Try this:
amount = 0 # Number of non-zero numbers input
nums = 0 # Sum of numbers input
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
nums+=int(number)
amount += 1
print(round(nums/amount,2)) # Print out the average rounded to 2 digits
Input:
1
2
3
4
Output:
2.5
Or you can use numpy:
import numpy as np
n = []
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
n.append(int(number))
print(round(np.average(n),2)) # Print out the average rounded to 2 digits
A list can store information of the values, number of values and the order of the values.
Try this:
numbers = []
while True:
num = input('Enter number:')
if num == '':
print('Average is', round(sum(numbers)/len(numbers), 2)) # print
numbers = [] # reset
if num != '0' and num != '': numbers.append(int(num)) # add to list
Benefit of this code, it does not break out and runs continuously.
This code needs to calculate an average to retrieve an integer between 0-100. Any suggestions would be great.
Prompt the user for the number of points they expect to receive
for engagement at the end of class. This number should not be
adjusted by the program (engagement is a total of 302).
Calculate the final based on an average of the quiz scores to
date.
Prompt the user for the various scores. -1 = no more scores, 0 -
zero for that assignment. Keep looping for the grade until the user
enters a -1.
Here is my code, I definitely do not understand lists very well. Probably clearly.
list1 = []
g=1
totalnum = 0
total=0
tot = int(input("Total Points? :"))
list1.append(tot)
eng = int(input("How many points do you expect to get in engangement, out of 302?: "))
list1.append(eng)
while g !=0:
num = int(input("Please enter a grade"))
if num == -1:
break
totalnum+=1
total= total+num
list1.append(num)
average= tot/eng+num
counter=0
while counter<totalnum:
print(list1[counter])
counter+=1
print("your average is",average)
If you can use built ins you can just use sum(your_list) / len(your_list) for the average.
If len(your_list) is zero, you will get a ZeroDivisionError, because you just broke math.
It's not clear to me that this is what you're trying to accomplish, but if you just want an average of all the values in the list, you can just do:
average = sum(list)/len(list)
This would return an integer, if you don't want it rounded you could do:
average = sum(list)/float(len(list))
As an aside, you have this:
counter=0
while counter<totalnum:
print(list1[counter])
counter+=1
Which could be made simpler, like:
for e in list1:
print e
Python will do the counting for you. :)
list1 = []
g=1
totalnum = 0
total=0
tot = int(input("Total Points? :"))
eng = int(input("How many points do you expect to get in engangement, out of 302?: "))
list1.append(eng)
while g !=0:
num = int(input("Please enter a grade"))
if num == -1:
break
else:
list1.append(num)
totalnum+=1
total= (num+eng)/tot
print(len(list1))
average = (sum(list1)/tot)*100
counter=0
for e in list1:
print (e)
print("your average is",average)
This is more what I was looking for. Thanks to #Tommy, #SQLnoob, and #Slayer for the tips that I have implemented into the code.