A way to get python to receive input and sum it? [duplicate] - python

This question already has answers here:
Loop that adds user inputted numbers and breaks when user types "end"
(4 answers)
How to sum numbers from input?
(2 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
sorry for the stupid question, but I can't get out of this thing in any way, I'm a beginner.
I need to write a code that asks the user to write a series of int one at the time using a while function. When the user has inserted all the numbers, to stop the series he'll write a specific string. When it's done, I need the code to print the sum and the average of all the numbers inserted.
The user can't insert them all in one time, he needs to enter one at the time.
I tried something like this: but there's no way it'll work. Implementing items in a list and then operate on the list is possible, but I had no idea on how to do that more easily than summing every element each time.
(my initial code:)
count = 0
total = 0
while():
new_number = input('> ')
if new_number == 'Done' :
break
count = count + 1
total = total + number
print(total)
print(total / count)
Don't mind about data being a string or an int, as long as it's just an error that IDLE would tell me. I just would like to know what's logically wrong in my code.
Thank you in advance.

You were really close, I made a couple of changes - firstly I changed while(): to while True:, so that the loop runs until break is hit. Secondly I altered total = total + number to total = total + int(new_number) - corrected variable name and convert string returned by input() to an int. Your logic is fine.
Corrected Code:
count = 0
total = 0
while True:
new_number = input('> ')
if new_number == 'Done' :
break
count = count + 1
total = total + int(new_number)
print(total)
print(total / count)

Using a list is actually not that hard. Here's how:
Firstly make the corrections from CDJB's answer.
Create an empty list. Add each new_number to the list. Use sum() and len() to get the total and count.
nums = []
while True:
new_number = input('> ')
if new_number == 'Done':
break
nums.append(int(new_number))
total = sum(nums)
count = len(nums)
print(total)
print(total / count

Related

how to ask for user input over again in a recursive function [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
num_length = int(input('Enter the length of the sequence:\n'))
nomlist=[]
count = 0
for i in range (num_length):
num = int(input('Enter number '+str(i+1)+ ':\n'))
nomlist.append(num)
this is a part of the solution for my homework, but now I need to rewrite it in a recursive form and I am not sure how I am supposed to change the above code in a recursive function. The above code basically asks the user to input a number and based on that number the program repeatedly asks the user for input and appends it into the list. Please help me.
num_length = int(input('Enter the length of the sequence:\n'))
nomlist=[]
def rec(l, count, num_length):
if count <= 0:
return
else:
num = int(input('Enter number '+str(num_length-count+1)+ ':\n'))
l.append(num)
rec(l, count-1, num_length)
rec(nomlist, num_length, num_length)
print(nomlist)
Here's a recursive function that makes use of default parameter values and conditional expressions to minimize the amount of code required:
def get_nums(length, numbers=None, entry=1):
numbers = [] if not numbers else numbers
numbers.append(input(f' Enter number {entry}: '))
return numbers if entry == length else get_nums(length, numbers, entry+1)
length = int(input('Enter the length of the sequence: '))
nomlist = get_nums(length)
print(nomlist)

Python - script counts wrong, but why?

I'm just at the beginning to learn Python.
As an exercise I wrote this little script:
Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number,
detect their mistake using try and except and print an error message and skip to the next number.
It does what it should in general, but: When I played with it a little I noticed one strange behavior: As it takes several (int) numbers after the prompt it won't - and shouldn't - take characters. So far so good, but then I tried a float as input. The script won't take it as valid input but would count it and put the truncated number into the total.
Code:
total = float(0) # sum of items
count = int(0) # number of items
avrg = float(0) # average of items
input_in = True
while input_in:
try:
line = input('Enter a number: ')
if line == 'done':
print('total:', str(total),' count:', str(count),' average:', str(avrg))
break
print(line)
for itervar in line:
total = total + float(itervar)
count = count+1
avrg = total / count
except:
print('Invalid input')
Output:
Enter a number: 1.5
1.5
Invalid input
Enter a number: 5
5
Enter a number: 5
5
Enter a number: 5
5
Enter a number: done
total: 16.0 count: 4 average: 4.0
What I tried - and didn't work: Assign the variables line and/or itervar as float().
I tried the included Debugger but I'm not able to understand it.
I have no clue how this could work.
Your line:
for itervar in line:
Is walking over each character of the input, which for your first input (1.5) results in three iterations:
1
.
5
So for the first iteration, your total is increased by 1, and for the second iteration, you're trying to use . as a number, and failing. (Hence why your final value, after adding 5 + 5 + 5, is 16)
Instead of using a for loop to iterate over your input, you should look into converting the entire input string into a number.
And as an added bonus...
Consider whether you actually need to be recalculating your average each loop. Since you have the total, and the count, I'd recommend instead calculating your average value on-demand, as a result of those two numbers.
As you've already figured out, input() returns a string.
When you iterate through a string with a for loop, you iterate over each character individually. This means that, when you enter '1.5', you get three iterations:
itervar = '1'
itervar = '.'
itervar = '5'
Due to how you wrote your code, the first one goes correctly, but then when it tries to convert '.' to a float, it produces an error.
Why not just consider the entire input as a whole, instead of character-by-character?
line = input('Enter a number: ')
if line == 'done':
print('total:', str(total),' count:', str(count),' average:', str(avrg))
break
print(line)
total = total + float(line)
count = count+1
avrg = total / count

Finding the next entity in a list python

I am relatively new to python and I have searched the web for an answer but I can't find one.
The program below asks the user for a number of inputs, and then asks them to input a list of integers of length equal to that of the number of inputs.
Then the program iterates through the list, and if the number is less than the ToyValue, and is less than the next item in the list the variable ToyValue increments by one.
NoOfToys=0
ToyValue=0
NumOfTimes=int(input("Please enter No of inputs"))
NumberList=input("Please enter Input")
NumberList=NumberList.split(" ")
print(NumberList)
for i in NumberList:
if int(i)>ToyValue:
ToyValue=int(i)
elif int(i)<ToyValue:
if int(i)<int(i[i+1]):
NoOfToys=NoOfVallys+1
ToyValue=int(i[i+1])
else:
pass
print(NoOfVallys)
Here is an example of some data and the expected output.
#Inputs
8
4 6 8 2 8 4 7 2
#Output
2
I believe I am having trouble with the line i[i+1], as I cannot get the next item in the list
I have looked at the command next() yet I don't think that it helps me in this situation.
Any help is appreciated!
You're getting mixed up between the items in the list and index values into the items. What you need to do is iterate over a range so that you're dealing solidly with index values:
NoOfToys = 0
ToyValue = 0
NumOfTimes = int(input("Please enter No of inputs"))
NumberList = input("Please enter Input")
NumberList = NumberList.split(" ")
print(NumberList)
for i in range(0, len(NumberList)):
value = int(NumberList[i])
if value > ToyValue:
ToyValue = value
elif value < ToyValue:
if (i + 1) < len(NumberList) and value < int(NumberList[i + 1]):
NoOfToys = NoOfVallys + 1
ToyValue = int(NumberList[i + 1])
else:
pass
print(NoOfVallys)
You have to be careful at the end of the list, when there is no "next item". Note the extra check on the second "if" that allows for this.
A few other observations:
You aren't using the NumOfTimes input
Your logic is not right regarding NoOfVallys and NoOfToys as NoOfVallys is never set to anything and NoOfToys is never used
For proper Python coding style, you should be using identifiers that start with lowercase letters
The "else: pass" part of your code is unnecessary

Need help shortening program (python beginner)

In response to the following task, "Create an algorithm/program that would allow a user to enter a 7 digit number and would then calculate the modulus 11 check digit. It should then show the complete 8-digit number to the user", my solution is:
number7= input("Enter a 7 digit number")
listnum= list(number7)
newnum=list(number7)
listnum[0]=int(listnum[0])*8
listnum[1]=int(listnum[1])*7
listnum[2]=int(listnum[2])*6
listnum[3]=int(listnum[3])*5
listnum[4]=int(listnum[4])*4
listnum[5]=int(listnum[5])*3
listnum[6]=int(listnum[6])*2
addednum= int(listnum[0])+int(listnum[1])+int(listnum[2])+int(listnum[3])+int(listnum[4])+int(listnum[5])+int(listnum[6])
modnum= addednum % 11
if modnum== 10:
checkdigit=X
else:
checkdigit=11-modnum
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
print(strnewnum)
(most likely not the most efficent way of doing it)
Basically, it is this: https://www.loc.gov/issn/check.html
Any help in shortening the program would be much appreciated. Thanks.
It might be worth it to do some kind of user input error checking as well.
if len(number7) != 7:
print ' error '
else:
//continue
Using a while loop for that top chunk might be a good starting point for you. Then you can sum the list and take the modulus in the same step. Not sure if you can make the rest more concise.
number7= input("Enter a 7 digit number: ")
listnum= list(number7)
newnum=list(number7)
count = 0
while count < 7:
listnum[0+count] = int(listnum[0+count])*(8-count)
count += 1
modnum= sum(listnum) % 11
if modnum== 10:
checkdigit=X
else:
checkdigit=11-modnum
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
print('New number:', strnewnum)
EDIT:
If you want it to print out in ISSN format, change your code after your if-else statement to this:
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
strnewnum = '-'.join([strnewnum[:4], strnewnum[4:]])
print('ISSN:', strnewnum)
You can convert the list to contain only int elements right after the input
number7 = int(input())
Then you can perform those operations in a loop.
for i in range(len(listnum)):
listnum[i] *= (8-i)
also the sum function does the trick of performing the addition of every element in the list (if possible)
EDIT:
addedNum = sum(listNum)

Python: How to use a Variable Integer to Call a Specific Part of a String

Ok, so I've got a couple issues with a program (for school again) that I'm using to add up all the digits of a number. I've got some of the program down, except 2 things. First, how to use a variable (thelength below) in replacement of a number to call a specific digit of the input (I'm not sure if this is even possible, but it would be helpful). And second, how to add up different numbers in a string. Any ideas?
Here's what I have so far:
number = str(int(input("Please type a number to add up: ")))
length = len(number)
thelength = 0
total = 0
thenumbers = []
while thelength < length:
#The issue is me trying to use thelength in the next two lines, and the fact that number is now a string
total += number[thelength]
thenumbers.append(number[thelength])
thelength += 1
for num in thenumbers:
print(num[0])
print("+")
print("___")
print(total)
Thanks for any help I can get!
I don't know what "call a specific digit of the input" means, but the error in your code is here:
total += number[thelength]
total is an int, and you're trying to add a string to it, convert the digit to an integer first.
total += int(number[thelength])
Result:
1
2
3
+
___
6
import re
import sys
INPUT_VALIDATOR = re.compile("^[0-9]+$")
input_str = input("Please type a natural number to add up: ")
if INPUT_VALIDATOR.match(input_str) is None:
print ("Your input was not a natural number (a positive whole number greater or equal to zero)!")
print ("This displeases me, goodbye puny human.")
sys.exit(1)
total = 0
for digit_str in input_str:
print(digit_str)
total += int(digit_str)
print("+")
print("___")
print(total)
If you don't need to print the digits as you go, it's even easier:
# (Add the same code as above to get and validate the input string)
print(sum(int(digit_str) for digit_str in input_str))
number = int(input("Please type a number to add up: "))
total = 0
while number > 0:
total += number % 10
total /= 10
print(total)
num % 10 pretty much gets the last digit of a number
then we divide it by 10 to truncate the number by its last digit
we can loop through the number as long as it's above 0 and take the digital sum by using the method outlined above
Every thing that you need is convert the digits to int and sum them :
>>> s='1247'
>>> sum(map(int,s))
14
But as you get the number from input it could cause a ValueErorr , for refuse that you can use a try-except :
try :
print sum(map(int,s))
except ValueErorr :
print 'please write a valin number :'
Also if you are using python 2 use raw_input for get the number or if you are using python 3 just use input because the result of both is string !

Categories

Resources