how to connect user input and lists - python

in my program, I am taking user input (integers 1-9) and having the user keep typing in numbers until they type 0 to exit. once they type 0 I want to print the sum of the integers and then exit. Im new to python so any help would be appreciated. Im getting an invalid syntax error when using the > and < symbol not sure why.
def createList():
myList=[]
return myList
def fillList(myList):
for number in myList:
if number >=1 and <= 9:
number=int(input(" enter a number 1-9, and 0 to quit"))
myList.append(number)
return myList
def printList(myList):
for number in myList:
print ( " the sum is" ,sum(myList))
print(number)
if number ==0:
exit()
def main():
myList = createList()
fillList(myList)
printList(myList)
main()

You're only missing a word, try this:
if number >=1 and number <= 9:
So close!

_sum = 0
looping = True
while looping:
num = input("Enter a number (1-9) or 0 to exit.")
if num.isdigit() and 0 <= int(num) <= 9:
_sum += num
if num is 0:
looping = False
print("Sum is", _sum)

if number >=1 and number <= 9:
You need to place the variable on both sides of the and since they are two separate conditions.
Also, since you're initially creating an empty list, you will never get to the part where you get user input. To fix this you should use a while loop.
while number != 0:
The full program might look like this:
def createList():
myList=[]
return myList
def fillList(myList):
number = 5
while number != 0:
if number >=1 and number <= 9:
number=eval(input(" enter a number 1-9, and 0 to quit"))
myList.append(number)
return myList
def printList(myList):
for number in myList:
print ( " the sum is" ,sum(myList))
print(number)
if number ==0:
exit()
def main():
myList = createList()
fillList(myList)
printList(myList)
main()

Related

How to print only the last result of an array of sum in python

I want to calculate the sum of the natural numbers from 1 up to an input number. I wrote this code:
number=int(input("enter a natural number"))
if number<0:
print("The number is not positive")
else:
n=0
for i in range (1,number+1):
n+=i
print(n)
But it prints multiple numbers instead. For example, if the user puts five, the program should print 15, but I get this:
1
3
6
10
15
How can I fix the code so that only 15 appears?
You have all the steps because your print statement is in your for loop.
Change it like this:
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
result = 0
for i in range(1, number + 1):
result += i
print(result) # We print after the calculations
There's also a mathematical alternative (see here):
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
print(number * (number + 1) / 2)
As I've pointed out and suggested earlier in comments, you could move the print statement out of for-loop to print the final sum.
Or you could try to use generator expression to get all number's total (sum), because we don't care the intermediate sums.
This simple sum of all up to the number in one shot.
number=int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
# exit or try again <---------
else:
print(sum(range(1, number + 1))) # given 5 -> print 15
Something like this?
number = int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
else:
n = 0
for i in range (1,number + 1):
n += i
print(n)
The answer to your question is that you are printing the n every time you change it. You are looking for the last answer when you run the code. This code should solve it.
number = int(input("enter a natural number"))
if number < 0:
print("The num < 0")
else:
n = 0
l = []
for i in range (0, number+1):
n+=i
l.append(n)
print(l[len(l)-1])

Verify if two indices from a list add up to a target number

I am looking to see if any 2 indices add up to the inputed target number, and print the combination and index location of the respective pair. I honestly am not too sure how to approach this, my first reaction was using a for loop but due to inexperience i couldn't quite figure it out.
def length():
global lst_length
break_loop = False
while break_loop == False:
lst_length = int(input("Enter the length: "))
if lst_length >= 10 or lst_length <= 2:
print("Invalid list")
elif lst_length >= 2 and lst_length <= 10:
print('This list contains', lst_length, 'entries')
break_loop == True
break
def entries():
i = 0
x = 0
global lst
lst = []
while i < lst_length:
number = float(input("Enter the entry at index {0}:".format(x)))
if i < 0:
print('Invalid entry')
else:
lst = []
lst.append(number)
i += 1
x += 1
def target():
target_num = int(input("Enter the target number: "))
length()
entries()
target()
If I understand your question correctly, you want the user to insert numbers, and when finally two numbers match the wanted result, print them?
well, my code is pretty basic, and it gets the job done, please let me know if you meant something else.
for indices, I suppose you can fill in the gaps.
def check(wanted):
numbers_saved = []
checking = True
while checking:
x = float(input("enter a number: "))
if x < 0:
print("only numbers bigger than 0")
else:
for num in numbers_saved:
if num + x == wanted:
print(num, x)
checking = False
return
numbers_saved.append(x)

How to loop a function def in python until I write the number 0

I'm trying to do a def function and have it add the digits of any number entered and stop when I type the number "0", for example:
Enter the number: 25
Sum of digits: 7
Enter the number: 38
Sum of digits: 11
Enter the number: 0
loop finished
I have created the code for the sum of digits of the entered number, but when the program finishes adding, the cycle is over, but what I am looking for is to ask again for another number until finally when I enter the number "0" the cycle ends :(
This is my code:
def sum_dig():
s=0
num = int(input("Enter a number: "))
while num != 0 and num>0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
if num>0:
return num
sum_dig()
Use list() to break the input number (as a string) into a list of digits, and sum them using a list comprehension. Use while True to make an infinite loop, and exit it using return. Print the sum of digits using f-strings or formatted string literals:
def sum_dig():
while True:
num = input("Enter a number: ")
if int(num) <= 0:
return
s = sum([int(d) for d in list(num)])
print(f'The sum of the digits is: {s}')
sum_dig()
In order to get continuous input, you can use while True and add your condition of break which is if num == 0 in this case.
def sum_dig():
while True:
s = 0
num = int(input("Enter a number: "))
# Break condition
if num == 0:
print('loop finished')
break
while num > 0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
sum_dig()
A better approach would be to have sum_dig take in the number for which you want to sum the digits as a parameter, and then have a while loop that takes care of getting the user input, converting it to a number, and calling the sum_digit function.
def sum_dig(num): # takes in the number as a parameter (assumed to be non-zero)
s=0
while num > 0: # equivalent to num != 0 and num > 0
r = num % 10
s = s + r
num = num // 10
return s
while True:
num = int(input("Enter a number: "))
if num == 0:
break
print("The sum of the digits is: " + sum_dig(num))
This enables your code to adhere to the Single-Responsibility Principle, wherein each unit of code has a single responsibility. Here, the function is responsible for taking an input number and returning the sum of its digits (as indicated by its name), and the loop is responsible for continuously reading in user input, casting it, checking that it is not the exit value (0), and then calling the processing function on the input and printing its output.
Rustam Garayev's answer surely solves the problem but as an alternative (since I thought that you were also trying to create it in a recursive way), consider this very similar (recursive) version:
def sum_dig():
s=0
num = int(input("Enter a number: "))
if not num: # == 0
return num
while num>0:
r= num %10
s= s+r
num= num//10
print("The sum of the digits is:",s)
sum_dig()

ValueError: could not convert string to float: 'F' python

I'm trying to write a small python code that prints out a sum of data provided by a user. More specifically I need the code to be able to calculate it when the number of data is not known in advance. To achieve that I need the code to recognize that the user did not indicate the size of the list and to know what is the last entry to be included by typing in "F". The problem I encountered with my code (see below) is that when I use "F" instead of "-1" the code crashes with the following message "ValueError: could not convert string to float: 'F' python". Can anyone help me to understand what am I doing wrong, so I can fix it.
numberList = []
count = int(input("Enter the list size :"))
stopList = False
F = -1
mysum = 0
num = 0
if count >= 0:
for i in range(0, count):
item = int(input("Enter number :"))
numberList.append(item)
mysum = sum(numberList)
print("The sum is", mysum)
if count < 0:
while stopList is False:
nextnum = float(input("Enter number :"))
if nextnum == F:
stopList = True
if stopList is False:
num += 1
mysum += nextnum
print("The sum is", mysum)
I will address only the problematic part of your code, which is everything after if count < 0:.
You should first take the input as-is and check if it is 'F' and only then convert if to float, if necessary:
while stopList is False:
nextnum = input("Enter number :")
if nextnum == 'F':
stopList = True
if stopList is False:
num += 1
mysum += float(nextnum)
print("The sum is", mysum)
As a side note, don't use the condition like this for the loop, I would use it like that:
while True:
nextnum = input("Enter number :")
if nextnum == 'F':
break
num += 1
mysum += float(nextnum)
print("The sum is", mysum)

Calculating average from raw_input data in a while loop

Fellow python developers. I have a task which I can't seem to crack and my tutor is MIA. I need to write a program which only makes use of while loops, if, elif and else statements to:
Constantly ask the user to enter any random positive integer using int(raw_input())
Once the user enters -1 the program needs to end
the program must then calculate the average of the numbers the user has entered (excluding the -1) and print it out.
this what I have so far:
num = -1
counter = 1
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
counter += anyNumber
answer = counter + anyNumber
print answer
print "Good bye!"
Try the following and ask any question you might have
counter = 0
total = 0
number = int(raw_input("Enter any number: "))
while number != -1:
counter += 1
total += number
number = int(raw_input("Enter another number: "))
if counter == 0:
counter = 1 # Prevent division by zero
print total / counter
You need to add calculating average at the end of your code.
To do that, have a count for how many times the while loop runs, and divide the answer at the end by that value.
Also, your code is adding one to the answer each time because of the line - answer = counter + anyNumber, which will not result in the correct average. And you are missing storing the first input number, because the code continuously takes two inputs. Here is a fixed version:
num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
counter += 1
answer += anyNumber
anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1
else:
print answer/counter #print average
print "Good bye!"
There's another issue I think:
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
The value of the variable anyNumber is updated before the loop and at the beginning of the loop, which means that the first value you're going to enter is never going to be taken in consideration in the average.
A different solution, using a bit more functions, but more secure.
import numpy as np
numbers = []
while True:
# try and except to avoid errors when the input is not an integer.
# Replace int by float if you want to take into account float numbers
try:
user_input = int(input("Enter any number: "))
# Condition to get out of the while loop
if user_input == -1:
break
numbers.append(user_input)
print (np.mean(numbers))
except:
print ("Enter a number.")
You don't need to save total because if the number really big you can have an overflow. Working only with avg should be enough:
STOP_NUMBER = -1
new_number = int(raw_input("Enter any number: "))
count = 1
avg = 0
while new_number != STOP_NUMBER:
avg *= (count-1)/count
avg += new_number/count
new_number = int(raw_input("Enter any number: "))
count += 1
I would suggest following.
counter = input_sum = input_value = 0
while input_value != -1:
counter += 1
input_sum += input_value
input_value = int(raw_input("Enter any number: "))
try:
print(input_sum/counter)
except ZeroDivisionError:
print(0)
You can avoid using two raw_input and use everything inside the while loop.
There is another way of doing..
nums = []
while True:
num = int(raw_input("Enter a positive number or to quit enter -1: "))
if num == -1:
if len(nums) > 0:
print "Avg of {} is {}".format(nums,sum(nums)/len(nums))
break
elif num < -1:
continue
else:
nums.append(num)
Here's my own take on what you're trying to do, although the solution provided by #nj2237 is also perfectly fine.
# Initialization
sum = 0
counter = 0
stop = False
# Process loop
while (not stop):
inputValue = int(raw_input("Enter a number: "))
if (inputValue == -1):
stop = True
else:
sum += inputValue
counter += 1 # counter++ doesn't work in python
# Output calculation and display
if (counter != 0):
mean = sum / counter
print("Mean value is " + str(mean))
print("kthxbye")

Categories

Resources