I am new to coding and my spelling is not the best but I need help with something, I am trying to loop a formula to make a sequence that is stored in a list. Here is my code so far;
for i in range(list):
number1 = number63*number99
number2 = number1*number33
number3 =(number2*number34)+(number64*number35)
total = number1 + number2 + number3
don't worry about the variables they are completely irrelevant as they only make sense to me but i just was to know how i could do this.
Is this what you want to do?
for i in range(list):
number1 = number63*number99
number2 = number1*number33
number3 =(number2*number34)+(number64*number35)
total += [number1] + [number2] + [number3]
This will make total a list which adds the three numbers to it each loop iteration
An alternative is to use extend:
total.extend([number1, number2, number3])
Please note that for both of these methods, you need to initialize total somewhere earlier in your code, e.g.
total = []
Additionally, you are using the range function wrong. If you want to iterate the length of a list, do range(0,len(lst)). Please also note that using the variable name list is ill-advised as it is a built-in function in Python.
Related
This question already has answers here:
How to append multiple values to a list in Python
(5 answers)
Closed 7 months ago.
Begginer Question, So i have this problem where i receive a lot of inputs in different lines like:
Inputs:
1
2
0
2
1
And i want to sum them or store them in any kind of list to Sum them latter, how can i do this?
I mean, i could store a variable for each one of them like:
a1 = int(input())
a2 = int(input())
ax = int(input())
....
and then
result = a1+a2+ax...
print(result)
but that's not pratical. Someone can explain me on how to store and sum them in a list?
i think that i could do something like this too
x = int(input())
and use
x += x
Just use python lists:
inputlist = []
for i in range(5):
inputlist.append(int(input))
result = sum(inputlist)
Note, I just put a 5 there to ask for 5 values. Ask however many inputs you want.
you could use a while loop, or a for loop for it. If you are provided the number of inputs in advance in a variable x, you can start with a for loop.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
answer = 0
for i in range(x):
answer += int(input())
print("Answer is", answer)
If you do not know the amount of inputs in advance, you can implement a while loop that will take input until a non-integer input is given.
answer = 0
while True:
x = input()
try:
x = int(x) # Tries to convert the input to int
except ValueError: # If an error occurs, ie, the input is not an integer.
break # Breaks the loop and prints the answer
# If all goes fine
answer += x
print("Answer is", answer)
And obviously, we also have a classic alternate to all this, which is to use python list, these can store numbers and we can process them later when printing the answer. Although, I would have to say if the number of input is large, then the most efficient manner is to use either of the above solution due to their memory footprint.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
inputs = []
for i in range(x):
inputs.append(int(input()))
print("Answer is", sum(inputs))
I'm also a beginner, but here's a solution I came up with:
new_list = []
for entry in range(10):
new_list.append(int(input()))
print(sum(new_list))
The following Python script raises syntax error:
def main(number, number2, equation):
if equation == 1:
number + number2 = answer
SyntaxError: cannot assign to operator is the raised error. Please help.
You must assign (=) operation (number + number2) to variable answer in this direction.
answer = number + number2
Variable name is on right side and value, expression, object, etc. is on the left.
In python you set variables to be equal to the their result instead of the result to be equal to the variable.
So where you have put
number + number2 = answer
You need to do
answer = number + number2
As what you are doing is making the sum of number and number2 equal to answer which is not possible
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to the field. simple program, all I need to do is to find the smallest number.
number1 = input ('')
number2= input('')
number3 = input('')
number1 = input ('')
number2= input('')
number3 = input('')
if (number1<number2) and (number1<number3):
smallest=number1
elif (number2<number1) and (number2 < number3):
smallest=number2
else:
smallest=number3
print(smallest)
This occurs because input() returns a string:
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Because of this, all checks amongst the input values won't be between integers, as you want, but strings, leading to comparisons being based upon lexicographical ordering rather than value. This can be solved by converting the inputs to integers:
number1 = int(input(''))
number2 = int(input(''))
number3 = int(input(''))
if (number1 < number2) and (number1 < number3):
smallest = number1
elif (number2 < number1) and (number2 < number3):
smallest = number2
else:
smallest = number3
print(smallest)
simply use min() and max()
n1,n2,n3 = 1,2,3
print("min:", min(n1,n2,n3) )
print("max:", max(n1,n2,n3))
output:
> min: 1
> max: 3
When you enter "7", "15", and "3", your program compares those three values as strings, which means that it will find the one that is "smallest" alphabetically -- the first character is compared first, which makes "15" come first in the ordering (then "3", then "7").
To fix this, you need to convert the values to ints:
number1 = int(input())
You may be getting blank strings ("") in some cases because you copied and pasted the input lines, which means you're getting prompted six times and only the last three times count.
Overall the fixed version of your code would look like:
number1 = int(input())
number2 = int(input())
number3 = int(input())
if number1 < number2 and number1 < number3:
smallest = number1
elif number2 < number3:
smallest = number2
else:
smallest = number3
print(smallest)
Note that you don't need to pass an empty string to input() (it defaults to an empty string), and you don't need the parentheses around your comparison operations (because < already takes precedence over and).
A shortened version of this code that uses min and a loop would be:
print(min(int(input()) for _ in range(3)))
In this line of code, the expression int(input()) for _ in range(3) generates three inputs (one per number in range(3)), and the min function finds the minimum value from that generator. The nice thing about using a loop like this is that you can easily make it work for any number of inputs without having to write a bunch more if ... < ... checks!
When you use input(''), it takes the number from terminal (at the running time), so your code is OK, just to understand how it works, run your modified code below, some added strings can help you find your problem better.
number1 = input('Please insert the first number ?')
number2 = input('Please insert the second number ?')
number3 = input('Please insert the third number ?')
if (number1 < number2) and (number1 < number3):
smallest = number1
elif (number2 < number1) and (number2 < number3):
smallest = number2
else:
smallest = number3
print("result is : ", smallest)
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
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)