Regarding formatting of printed outputs (python) [closed] - python

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!

Related

How to turn 1000 into 1e3? [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 1 year ago.
Improve this question
I want to convert a given number with 0's to be converted to the format with 'e' ex : 1000000 >> 1e6 so far i use this
def test(number: int):
number, zeros = str(number), 0
for i in number:
if i == '0': zeros += 1
return number[0] + 'e' + str(zeros)
You can do that by iterating over stringified number. Code below iterates from end to start of the stringified number and counts the number of zeros.
Then it converts it to form you want. It also works with numbers like 234000.
def test(number:int):
zeros=0
for i in str(number)[::-1]:
print(i)
if i=='0':
zeros += 1
else:
break
return str(number)[:-(zeros)]+'e'+str(zeros)
You are only reproducing the first non-zero digit. There can be more of them.
Also, you shouldn't count zeroes that are not part of the trailing series of zeroes, so start your loop from the end and break out of the loop.
Change:
for i in number:
if i == '0': zeros += 1
return number[0] + 'e' + str(zeros)
to:
for i in reversed(number):
if i == '0':
zeros += 1
else:
break
if zeros:
return number[:-zeros] + 'e' + str(zeros)
return number
If you are OK with using a regular expression then you can replace the loop like this:
import re
def test(number: int):
number = str(number)
zeros = len(number) - re.search(r"0*$", number).start()
if zeros:
return number[:-zeros] + 'e' + str(zeros)
return number

Indexerror:::: list index out of range [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
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.

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

Looking for Clarification on how this "For-Loop" works

I'm a complete beginner to programming so forgive me for my naivete.
I wanted to make a program in Python that lets me print a given N number of prime numbers, where N is inputted by the user. I searched a little on "for/while" loops and did some tinkering. I ran a program I saw online and modified it to suit the problem. Here is the code:
i = 1
print("Hi! Let's print the first N prime numbers.")
nPrimes = int(input("Enter your N: "))
counter = 0
while True:
c = 0 #another initialization
for x in range (1, (i + 1)):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
if c == 2:
print(i, end = " ")
counter = counter + 1
if counter > = nPrimes: #if it reaches the number input, the loop will end.
break
i = i+1
print(": Are your", nPrimes, "prime number/s!")
print()
print("Thanks for trying!")
This should be able to print the amount of prime numbers the user so likes. It is a working code, though I am having difficulty trying to understand it. It seems that the variable c is important in deciding whether or not to print the variable i (which in our case is the supposed prime number during that interval).
We do c + 1 to c every time our variable a has a remainder of 0 in a = i % x. Then, if c reaches 2, the current variable i is printed, and variable c re-initializes itself to 0 once a prime number has been found and printed.
This I can comprehend, but I get confused once the numbers of i get to values 4 and onwards. *How is 4 skipped by the program and not printed when it has 2+ factors in the range that makes its remainder equal to zero? Wouldn't c == 2 for 4 and thus print 4? *And how would the program continue to the next number, 5? (Given that variable N is a large enough input).
Any clarifications would be greatly appreciated. Thank you so much!
From Wikipedia we know:
A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
So to find a prime, is to find a natural number, aka an integer, which can only be exactly divided by 1 or itself. This is called Approach of Definition to find primes.
Hence, the following loop traverses through all integers from 1 to i,
and it counts how many times the integer i can be exactly divided by them.
for x in range (1, (i + 1)):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
And later you judge if the integer i can only be exactly divided by 1 and itself.
If true, you got a prime;
otherwise you just keep on.
if c == 2:
print(i, end = " ")
counter = counter + 1
if counter > = nPrimes: #if it reaches the number input, the loop will end.
break
Meanwhile, you can improve this prime searching algorithm a little bit by changing i = 1 to i = 2 in the beginning and adding an if statement:
# Start from 2 instead of 1
# and end at `i - 1` instead of `i`
for x in range (2, i):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
# Abandon the loop
# because an integer with factors other than 1 and itself
# is unevitably a composite number, not a prime
if c > 0:
break
if c == 0:
print(i, end = " ")
counter = counter + 1
if counter >= nPrimes: #if it reaches the number input, the loop will end.
break
This twist improves the efficiency of your program because you avoid unnecessary and meaningless amount of work.
To prevent potential infinite loop resulting from while expression,
you should replace while True: with while counter < nPrimes:. And the code turns out to be like this:
#if it reaches the number input, the loop will end.
while counter < nPrimes:
c = 0 #another initialization
# Start from 2 instead of 1
# and end at `i - 1` instead of `i`
for x in range (2, i):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
# Abandon the loop
# because an integer with factors other than 1 and itself
# is unevitably a composite number, not a prime
if c > 0:
break
if c == 0:
print(i, end = " ")
counter = counter + 1
i = i + 1
If you want to read more about how to improve your program's efficiency in finding primes, read this code in C language. :P
c in this case is used to count the number of numbers that divide evenly into i.
for example, if i = 8: 8 is divisible by 1, 2, 4, and 8. so c = 4 since there are 4 things that divide evenly into it
if i = 5: 5 is divisible by 1 and 5. so c = 2 since there are 2 numbers that divide evenly into it
if i = 4 (where you seem to be confused): 4 is divisible by 1, 2, and 4. so c = 3, not 2.

Python == Function to Count All Integers Below Defined Variable, Inclusive [duplicate]

This question already has answers here:
Python Memory Error while iterating to a big range
(3 answers)
Closed 6 years ago.
Sorry I have to ask such a simple question, but I've been trying to do this for a while with no luck, despite searching around.
I'm trying to define a function that will get user input for X, and then add every integer from 0 to X, and display the output.
For example, if the user inputs 5, the result should be the sum of 1 + 2 + 3 + 4 + 5.
I can't figure out how to prompt the user for the variable, and then pass this variable into the argument of the function. Thanks for your help.
def InclusiveRange(end):
end = int(input("Enter Variable: ")
while start <= end:
start += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, start))
Just delete argument "end" from function header and use your function.
InclusiveRange()
or define code in other way:
def InclusiveRange(end):
while start <= end:
start += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, start))
end = int(input("Enter Variable: ")
InclusiveRange(end)
Here's an itertools version:
>>> from itertools import count, islice
>>> def sum_to_n(n):
... return sum(islice(count(), 0, n + 1))
>>>
>>> sum_to_n(int(input('input integer: ')))
input integer: 5
15
You should take the user input out of the function, and instead call the function once you have received the user input.
You also need to store the sum in a separate variable to start, otherwise you're only adding 1 each iteration. (I renamed it to index in this example as it reflects it's purpose more).
def InclusiveRange(end):
index = 0
sum = 0
while index <= end:
sum += start
index += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, sum))
end = int(input("Enter Variable: "))
InclusiveRange(end)
Demo
Instead of using a loop, use a range object, which you can easily send to sum(). Also, you're never actually using the passed end variable, immediately throwing it away and binding end to a new value. Pass it in from outside the function.
def inclusive_range(end):
num = sum(range(end+1))
print("The total of the numbers, from 0 to {}, is: {}".format(end, num))
inclusive_range(int(input("Enter Variable: ")))
You can also use a math formula to calculate the sum of all natural numbers from 1 to N.
def InclusiveRange(end):
''' Returns the sum of all natural numbers from 1 to end. '''
assert end >= 1
return end * (end + 1) / 2
end = int(input("Enter N: "))
print(InclusiveRange(end))

Categories