Python 3.4.2 Output Formatting - python

I have written a code in Python that includes a loop that provides 100 answers pertaining to one variable. So for example the output looks like this when I run it in the shell: (top to bottom)
1
2
3
4
5
etc...
How do I format this to show 10 outputs per line: (left to right)
1 2 3 4 5
Here is my code:
def main():
n = 0
while n <= 100:
if getPentagonalNumber(n):
n += 1
number = (n * (3*n - 1)) / 2
print (format(number, "5.0f"), end = ' ')
def getPentagonalNumber(n):
for n in range (1, 100):
if n > 100:
return False
return True
main()

try the following
print(i, end=' ')
EDIT: If you want to print 10 numbers per line, you can do something like this
if i%10==0:
print('')
This will add a new line after every 10 numbers. (Note: This is assuming that i is the loop variable which is incremented once in every iteration)

Related

Get a number as many as the user inputed

I have a task to make an output program like this
if input : 5
then output : 2,6,10,14,18
Output must as many of total number as the input
My previous code like this
n = 5
num = 2
i = 1
while i <= n:
if num % 2 == 0:
if num % 4 != 0:
print(num)
i = i+1
num = num+1
But my output was just 2 numbers, i should get 5 numbers.
2,6
Can anyone help me?
Put the i+1 under the second if condition
if num % 4 != 0:
print(num)
i = i + 1
As you can see your output is following the Arithmetic progression
#### first number
a = 2
#### diffrence between the seq numbers
d = 4
#### number of terms in sequence
n = 5
### running loop n times
### a + (n-1) * d ( geeting the nth didgit in AP `enter code here`)
for i in range(1, n+1):
print(2 + (i-1)*d , end=',')

Loop while basics in python 3

I am reading a python basics book and there is one function which I don't understand how it works. How is is possible that output looks like pow function even there are not any ** or pow operation? Would be nice if anyone can help because I am getting more and more frustrated
loop while
summary = 1
number = 1
while number <= 6:
i = 1
p = number
while i < 5:
p *= number
i += 1
print(number, "to 5", p)
summary += p
number += 1
print("sum of fifth powers of numbers from 1 to 6 is", summary)
output
1 to 5 1
2 to 5 32
3 to 5 243
4 to 5 1024
5 to 5 3125
6 to 5 7776
sum of fifth powers of numbers from 1 to 6 is 12202
Let me explain this code briefly,
first we are defining,
> summary = 1
> number = 1
Here we are defining and initialising the two variables summary and number.
> while number <= 6:
> i = 1
> p = number
In above code we are starting a while loop which will run while the value of number variable is less than or equal to 6. So, the loop will run from 1 to 6. we are taking a variable i = 1 and p = number here.
> while i < 5:
> p *= number
> i += 1
> print(number, "to 5", p)
> summary += p
> number += 1
> print("sum of fifth powers of numbers from 1 to 6 is", summary)
Now, we are having an another nested while loop and this will run for the values 1 to 4 of i variable. As we can see in the loop, the variable p will be multiplied with itself for 4 times so we will get the 5th power of the particular number. then we are increasing value of number by 1 and adding the value of 5th power in variable summary and lastly we are printing that.
Let me explain with an example
when number=2 (i.e after finding fifth power of 1)
value of p=2 and i=1
then inner loop i.e
while i<5 :
p* = number //i.e p = p*number
i+= 1 //i.e i=i+1
goes like this,
iteration 1: p= 2*2 i.e p=4
i=1+1 i.e i=2 which is less than 5
iteration 2: p= 4*2 i.e p=8
i=2+1 i.e i=3 which is less than 5
iteration 3: p= 8*2 i.e p=16
i=3+1 i.e i=4 which is less than 5
iteration 4: p= 16*2 i.e p=32
i=4+1 i.e i=5 which is equal to 5, so it comes out of loop
therefore, 2 to 5=32
this is how we get fifth power of a number

Looping a function that changes it's output every iteration

I'm new to python and I'm trying to create something that if the number is odd for example 7 it does this (7 * 3+1) and if it is even for example 6 it does this (6/2) but the problem is that I want to loop this but it updates the number every output from the example earlier 7 I want this to turn to (22/2) and so on and if the number 1 is reached it stops.
output = []
number = 7
def mat(self):
if (self % 2) == 0:
even = self / 2
return even
else:
odd = self * 3 + 1
return odd
while mat(number) != 1:
output.append(mat(number))
output.append(mat(mat(number))
print(output)
this part doesn't work because it will never reach 1 and it only has 1 output (22) starting from the number 7 :
while mat(number) != 1:
output.append(mat(number))
output.append(mat(mat(number))
To update number, you need to assign it:
number = mat(number)
The best place to do this is in the while loop:
while number != 1:
number = mat(number)
For an exercise like this, it makes sense to just print the value on each iteration rather than trying to create an array of results:
while number != 1:
print(number)
number = mat(number)
Just update the value
For while loop:
a = 0
while a<10:
print("Hello World")
a = a + 1
For for loop:
a = 0
for i in range(10):
print("Hello World")
a = a + 1
if a >= 10:
break

Don't understand why code for digit sum isn't working

I tried to do the codewars Sum of Digits/Digital Root problem, where you have to:
Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
So passing through 52 would return 7, as 5 + 2 is 7 and passing through 942 would return 6, as 9 + 4 + 2 = 15 and then 1 + 5 = 6.
I came up with this code:
def digital_root(n):
n_str = str(n)
digit_total = 0
while len(n_str) != 1:
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
But it only works for 2 digit numbers and it won't work for higher digit numbers, it just endlessly runs. This code is probably a bad way to do it and I've looked over other people's answers and I get their solution but I just don't get why this won't work for higher digit numbers.
You have got your program almost right. The only challenge I see is with resetting the variable digit_total = 0 after each iteration.
def digital_root(n):
n_str = str(n)
while len(n_str) != 1:
digit_total = 0 #move this inside the while loop
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
print (digital_root(23485))
The output for print (digital_root(23485)) is 4
2 + 3 + 4 + 8 + 5 = 22
2 + 2 = 4
If the digit_total = 0 is not inside the while loop, then it keeps getting added and you get a never ending loop.
While you have a lot of code, you can do this in a single line.
def sum_digits(n):
while len(str(n)) > 1: n = sum(int(i) for i in str(n))
return n
print (sum_digits(23485))
You don't need to create too many variables and get lost in keeping track of them.
Alex,
running a recursive function would always be better than a while loop in such scenarios.
Try this :
def digital_root(n):
n=sum([int(i) for i in str(n)])
if len(str(n))==1:
print(n)
else:
digital_root(n)

Sum of all the multiples of 3 or 5 below 1000

Beginner here- trying to make a simple python program that will compute/answer this problem:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Currently this is what I have:
a = 0
b = 0
while a < 1000:
a = a + 3
print (a)
while b < 1000
b = b + 5
print (b)
This will print all the numbers being considered. I just need to add them together and that's my answer.
I would like one of two things to happen, instead of the code that I have written:
I would like all of this to happen internally, and therefore not have to use the "print" function. The just print the sum of all of those multiples.
I would like all of this stuff to print, but then I want to be able to print the sum of all of them too. Is there a way to make the computer take the value of everything it has printed?
Actually this problem can be solved in O(1) instead of O(N) without using any loops or lists:
The required sum is the sum of all multiples of 3 plus sum of all multiples of 5 minus the sum of multiples of (3*5=15) below the given number 1000 (LIMIT=999). The sums are calculated as a sum of arithmetic series.
It can be calculated in following way:
LIMIT=999
# Get the upper bounds for the arithmetic series
upper_for_three = LIMIT // 3
upper_for_five = LIMIT // 5
upper_for_fifteen = LIMIT // 15
# calculate sums
sum_three = 3*upper_for_three*(1 + upper_for_three) / 2
sum_five = 5*upper_for_five*(1 + upper_for_five) / 2
sum_fifteen = 15*upper_for_fifteen*(1 + upper_for_fifteen) / 2
# calculate total
total = sum_three + sum_five - sum_fifteen
# print result with Python 3
print(int(total))
The result is:
>>>
233168
It is possible to do this in one line in Python using a generator expression:
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0))
The range(1000) produces all the integers from 0 to 999 inclusive. For each one of those integers, if it is divisible by 3 or divisible by 5, then it is included in the result. The sum(...) function adds up all those numbers, and finally print(...) prints the result.
I would use a for loop to iterate over each number in your selected range. Then you can check if the modulus % is equal to 0, meaning it has no remainder when divided by those values, if so, add it to the total.
total = 0
for num in range(1000):
if num % 3 == 0 or num % 5 == 0:
print(num)
total += num
>>> total
233168
While a for loop would work, you could also use a generator expression and sum:
sum(n for n in range(1000) if n % 3 == 0 or n % 5 == 0)
def sum_multiply (n):
data = []
for num in range (1, n):
if num % 3 == 0 or num % 5 == 0:
data.append(num)
return sum(data)
sum_multiply(1000)
total=0
i=0
while i<1000:
if i%3==0 or i%5==0:
print(num)
total+=i
i+=1
print("Total is: ")
**with python**
print(sum([i for i in range(1,1000) if i%3==0 or i%5==0 ]))

Categories

Resources