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)
Related
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.
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
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!
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 6 years ago.
Improve this question
Instructions: Simulate rolling 2 die with 6 sides each 100 times and count these 3
cases
-The dice sum equals 7
-The 2 die are doubles (same number)
-The dice sum is 10,11, or 12 (greather than or equals to 10)
What I have:
from random import randint
def rolldie():
return randint(1, 7) + randint(1, 7)
n=10
for j in range(n):
print(str(j) + ". Outcome: " + str(rolldie()))`
Overall I don't know if this is correct. Looking for more help. Thank you.
You need to return the values of both dice, not their sum, so you can compare whether they were each the same value.
def roll_dice():
return (random.randint(1,6), random.randint(1,6))
equal_7 = 0
doubles = 0
ten_or_more = 0
for i in range(100):
d1, d2 = roll_dice()
if d1 + d2 == 7:
equal_7 += 1
if d1 == d2:
doubles += 1
if d1 + d2 >= 10:
ten_or_more += 1
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 8 years ago.
Improve this question
else:
while int(n2) - 1 != 0:
a = int(n) + int(n)
print("" + str(a))
I need this part of code to times n by n2 without using '*' or '/' and I'm not sure how to change this so that it will work. What do I need to change/add to make this work?
Something like this:
lowest, highest = a, b
if b < a: lowest, highest = b, a
total = 0
for _ in range(lowest):
total += highest
print "a x b = %s" % total
You can use a for loop to add n to ans exactly n2 times:
n = 30
n2 = 2
ans = 0
for i in range(n2):
ans += n
print(ans)
If you need to operate on strings (as in your question), you could use the following example:
n = '30'
n2 = '2'
ans = 0
for i in range(int(n2)):
ans += int(n)
print(str(ans))