Indexerror:::: list index out of range [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
hi this is my code and I don't know why I received this type of error
x = int(input())
n = [int(i) for i in input().split()]
middle = n[int((x - 1) / 2)
even = 0
odd = 0
for number in n:
if number % 2 == 0:
even += number
else:
odd += number
answer = even * odd + middle ** 2
print("{} x {} + {}^2 = {}".format(even, odd, middle, answer))

It produces an error as such IndexError: list index out of range because n has the minimum number of list values entered by the user.
Since your intention was for n to have more values than the minimum number of digits entered by the user, I added .range() to the list iteration.
Here is the modified code:
x = int(input("Put in a number: "))
n = [int(i) for i in range(int(input("Put in another number: ")))]
middle = n[int((x - 1) / 2)]
even = 0
odd = 0
for number in n:
if number % 2 == 0:
even += number
else:
odd += number
answer = even * odd + middle ** 2
print("{} x {} + {}^2 = {}".format(even, odd, middle, answer))
If you have any questions or need clarification, please do not hesitate to ask.

Related

How to print just the final sum of odd and even integers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Built a program that allows the user to input a number, then calculates the sum of all the odd integers and all the even integers between 1 and the input. How do I only print the final sum of the odd and even integers rather than the sum between each addition? Thank you!
#Allow user to enter a number
n = input("Enter a number: ")
n = int(n)
n >= 1
total = 0
#sum of even numbers
for n in range(1, n+1):
if n % 2 == 0:
total += n
print("Sum of even numbers: ", total)
#sum of odd numbers
total2 = 0
for n in range(1, n+1):
if n % 2 == 1:
total2 += n
print("Sum of odd numbers: ", total2)
As mentioned before, you need to modify your indentation. Your code should look like that:
n = input("Enter a number: ")
n = int(n)
total = 0
#sum of even numbers
for n in range(1, n+1):
if n % 2 == 0:
total += n
print("Sum of even numbers: ", total)
#sum of odd numbers
total2 = 0
for n in range(1, n+1):
if n % 2 == 1:
total2 += n
print("Sum of odd numbers: ", total2)
Instead of making 2 different loops, you can do it in one single loop too. Like the one below:
num = input("Enter a number: ")
num = int(num)
even = [] # Appends all the even integers present in the user-accepted input
odd = [] # Appends all the odd integers present in the user-accepted input
for n in range(1, num+1):
if n % 2 == 0:
even.append(n)
else:
odd.append(n)
print("Sum of Even integers : ", sum(even))
print("Sum of Odd integers : ", sum(odd))

How to increment fraction/denominator in loop? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to develop a Python 3 program that will allow the user to choose a denominator and evaluate an equation. For Example:
The user selects 5 to be the denominator
The equation will increment until the given denominator
(1/1) + (1/2) + (1/3) + (1/4) + (1/5)
The output should be (2.283333)
My code:
d = input ("Select a denominator")
for i in range(d)
d += (1/d)
print(d)
So far I'm only able to ask the user for the input/denominator. I tried putting it in a loop but I am doing something wrong. This is what prints out:
5.2
5.392307
5.577757
5.757040
5.930740
final_denominator = int(input("Select a denominator: "))
total = 0
for i in range(1, final_denominator + 1):
total += 1 / i
print(total)
You need to convert the inputted string to an integer with int()
Use a different variable for the total and the final denominator.
range(x) goes from 0 to x - 1, to go from 1 to x you need range(1, x + 1).
You need to add 1 / i rather than 1 / final_denominator to the total.
Alternatively, this is a good use for a generator expression:
final_denominator = int(input("Select a denominator: "))
total = sum(1 / i for i in range(1, final_denominator + 1))
print(total)

Finding the sum of numbers from x to y and the program prints the answer as "x+(x+1)....+y= (sum of # from x to y)" [closed]

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
For example, the sum of numbers from 1 to 3 would be printed as 1+2+3=6; the program prints the answer along with the numbers being added together. How would one do this? Any help is greatly appreciated as nothing I've tried has worked. I have been trying to use the sum formula to get the answer and a loop to get the numbers being added together... but with no success. Although the hint is to use for loops, but I'm not sure how to incorporate that into the program. The practice prompt also says that I can't use sum or .join functions :(, I know that would make things so much easier. Omg I'm so sorry for forgetting to mention it.
Try using this
x = 3
y = 6
for i in range(x, y+1):
opt_str += str(i) + "+"
sum += i
print(opt_str[:-1] + "=" + str(sum))
Output:
3+4+5+6=18
You can use join and list comprehension to assemble the string.
n1 = 1
n2 = 3
li = str(n1)+"".join(["+"+str(i) for i in range(n1+1,n2+1)])+"="+str(sum(range(n1,n2+1)))
print (li)
Output:
1+2+3=6
you can try this
def problem1_3(n):
return n + problem1_3(n-1) if n > 1 else 1
or try below
n = 0
sum = 10
for num in range(0, n+1, 1):
sum = sum+num
print("SUM of first ", n, "numbers is: ", sum )
output
SUM of first 10 numbers is: 55
An interesting way to do this is to print a little bit at a time. Use end='' in your prints to avoid newlines:
num = 3
sum = 0
for i in range(1,num+1):
sum += i
if i>1:
print ("+", end='')
print(i, end='')
print("=%d" % sum)
1+2+3=6
The simplest way would be using for loops and print() function
def func(x,y):
sum = 0
#Loop for adding
for i in range(x,y+1):
sum+=i
#Loop for printing
for i in range(x,y+1):
if i == y:
print(i,end = '')
else: print(i," + ",end = '')
print(" = ",sum)
The end argument to the print() function specifies what your printed string is going to terminate with, instead of the default newline character.
So for your example here,
func(1,3) Will output : 1 + 2 + 3 = 6
Here is the code:
print("Finding the sum of numbers from x to y")
print("Please specify x & y(x<=y):")
x = int(input(" x:"))
y = int(input(" y:"))
numbers = [x]
result = f"Sum: {x}"
for i in range(1,y-x+1):
numbers.append(x+i)
result += f"+({x}+{i})"
print(f"{result} = {sum(numbers)}")
output:
Finding the sum of numbers from x to y
Please specify x & y(x<=y):
x:1
y:10
Sum: 1+(1+1)+(1+2)+(1+3)+(1+4)+(1+5)+(1+6)+(1+7)+(1+8)+(1+9) = 55
output2:
Finding the sum of numbers from x to y
Please specify x & y(x<=y):
x:2
y:6
Sum: 2+(2+1)+(2+2)+(2+3)+(2+4) = 20

list index out of range with if condition [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
num_array = list()
num = int(raw_input("Enter how many elements you want:"))
print 'Enter numbers in array: '
for i in range(int(num)):
n = raw_input("num :")
num_array.append(int(n))
print 'ARRAY: ',num_array
b = 0
count = 0
while b< num -1 or b>0:
count = count+1
if num_array[b]!= 0:
b = b + num_array[b]
else:
b = (b + num_array[b])*2
print count
i am trying to get an array as an input anD storing a index value in a variable which is updating its values. But i am getting an error of list out of range
Please help me
Your condition while b < num-1 or b>0 does not make sense. The or b>0 part makes it True for all values larger than num-1. Instead, you should use and:
while b < num-1 and b > 0:
Or shorter, using comparison chaining:
while 0 < b < num-1:
Also, note that array indices go from 0 to num-1 (num being the length), so actually the condition should probably be (not tested, though):
while 0 <= b < num:

Regarding formatting of printed outputs (python) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been working on the program that lists out the products (with their cost and quantity) , and they are separately stored in 3 different lists.
However, what I can't figure out how to do is , aligning of the printed outputs
while valid ==1 :
if user_choice == 's':
user_product = str(input("Enter a product name: "))
valid = 2
elif user_choice == 'l':
print ("Product" + " " + "Quantity" +" "+ "Cost")
c = 0
while c < len(product_names):
print (product_names[c] + " " + str(product_costs[c]) + " "+ str(quantity[c]))
c +=1
valid = 0
break
valid = 0
So basically I am not sure on how to actually make output on line 6 and
line 9 be aligned together because I'll be getting a disorganized output because the product names differ in length, cost and quantity differ in length too.
Can anybody teach me how to actually align them all properly so that they might
look like a table?
Thanks so much!
Here is what you wanted, exactly by the prescribed order.
n = -1 # Intentionally an incorrect value
# Ask user for the number while he/she doesn't enter a correct one
while n < 10:
n = int(input("Enter an integer number greater or equal 10: "))
# Preparation for Sieve of Eratosthenes
flags_list = ["P"] # 1st value
flags_list = flags_list * (n + 1) # (n + 1) values
flags_list[0] = "N" # 0 is not a prime number
flags_list[1] = "N" # 1 is not a prime number, too
# Executing Sieve of Eratosthenes
for i in range(2, n + 1):
if flags_list[i] == "P":
for j in range(2 * i, n + 1, i):
flags_list[j] = "N"
# Creating the list of primes from the flags_list
primes = [] # Empty list for adding primes into it
for i in range(0, n + 1):
if flags_list[i] == "P":
primes.append(i)
# Printing the list of primes
i = 0 # We will count from 0 to 9 for every printed row
print()
for prime in primes:
if i < 10:
print("{0:5d}".format(prime), end="")
i = i + 1
else:
print() # New line after the last (10th) number
i = 0
=========== The answer for your EDITED, totally other question: ===========
=========== (Please don't do it, create a new question instead.) ===========
Replace this part of your code:
print ("Product" + " " + "Quantity" +" "+ "Cost")
c = 0
while c < len(product_names):
print (product_names[c] + " " + str(product_costs[c]) + " "+ str(quantity[c]))
c +=1
with this (with the original indentation, as it is important in Python):
print("{:15s} {:>15s} {:>15s}".format("Product", "Quantity", "Cost"))
for c in range(0, len(product_names)):
print("{:15s} {:15d} {:15d}".format(product_names[c], quantity[c], product_costs[c]))
(I changed your order in the second print to name, quantity, cost - to correspond with your 1st print.)
Probably you will want change 15's to other numbers (even individually, e. g. to 12 9 6) but the triad of numbers in the first print must be the same as in the second print().
The explanation:
{: } are placeholders for individual strings / integers listed in the print statements in the .format() method.
The number in the placeholder express the length reserved for the appropriate value.
The optional > means the output has be right aligned in its reserved space, as default alignment for text is to the left and for numbers to the right. (Yes, < means left aligned and ^ centered.)
The letter in the placeholder means s for a string, d (as "decimal") for an integer - and may be also f (as "float") for numbers with decimal point in them - in this case it would be {:15.2f} for 2 decimal places (from reserved 15) in output.
The conversion from number to string is performed automatically for symbols d or f in the placeholder, so str(some_number) is not used here.
Addendum:
If you will have time, please copy / paste your edited version as a new question, then revert this question to its original state, as people commented / answered your original one. I will find your new question and do the same with my answer. Thanks!

Categories