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
square = 0
number = 1
while number < 10:
square = number ** 2
print(square)
number += 1
It's my answer for this question :" Print all squares from 0 to 99(1,4,..,81)Use number variable in while loop."
Pycharm says it doesn't match with its answer.
I think i should print those numbers in a single line but i couldn't deal with it.How can i do that ?
Your code will print each number in a newline, because, in Python, the call to print() comes with an implicit newline (see the end argument per the documentation).
Next, you're making an assumption about output formatting. As I see it, there are two primary issues with this assumption:
1) Calls to functions (e.g. print()) in a while loop "execute" when they're called -- there's no delay to see if a future pass through the loop will provide extra data to the function.
2) You're assuming that the Python interpreter will guess that printed numbers (in a while loop) are desired to be returned in a comma separated list. Computers are machines that do what you tell them to do -- if you don't write logic to explain what you need, the machine cannot give you this.
You can express your desired output in the following ways:
1) Collect the numbers (as strings) in a list, then output them after you're done looping:
square = 0
number = 1
# think of this as a result container
number_result_list = []
while number < 10:
square = number ** 2
# place that number at the end of your container:
number_result_list.append(str(square))
number += 1
# join all your number strings together, using a comma
print(",".join(number_result_list))
# prints 1,4,9,16,25,36,49,64,81
2) Specify that you want to use a comma in the call to print. Make special note of the trailing comma -- you now know why this happens:
square = 0
number = 1
while number < 10:
square = number ** 2
print(square, end=",")
number += 1
# prints 1,4,9,16,25,36,49,64,81,
Related
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 1 year ago.
Improve this question
Why my output result doesn't show 0 when it's supposed to show exact number in reverse order in Python.Without changing the parameter variable to string.
parameter = int(input())
sum = 0
while parameter > 0:
digit = parameter % 10
sum = sum * 10 + digit
parameter = parameter // 10
print(sum)
A couple of things are going on here. First, you're converting the input to an int. This means that when reversing the number you'll lose all trailing 0s. This is because for an int there is no reason to show a leading 0. Instead, you can simply print out each digit in reverse. Another thing to note is you shouldn't use sum as a variable since it will overwrite the built in sum function.
parameter = int(input())
while parameter > 0:
digit = parameter % 10
print(digit, end='')
parameter = parameter // 10
print("")
You can do this by printing the output right-justified in a field of the same width as the original number. This doesn't really avoid the fact that string manipulation is required, but at least it allows you to store the number as a number and not a string:
from math import ceil, log10
...
digits = ceil(log10(parameter + 1)) or 1
...
print(f'{sum:>0{digits}}')
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I want to loop with an index that starts at 1 and ends at 3.
This is what I'm doing now:
for number in list(range(3)):
print(number)
The output is:
0
1
2
What I want:
1
2
3
How can this be concisely done in Python?
give range start and end number, that is range(start, end, step)
start:- Optional. An integer number specifying at which position to start. Default is 0
end :- Required. An integer number specifying at which position to stop (not included).
step:- Optional. An integer number specifying the incrementation. Default is 1
for number in list(range(1, 4)):
print(number)
You are looking for this:
for number in range(1,4):
print(number)
Note: the list(range(...)) is redundant. You don't need to pass the range iterator to the list constructor.
This will work. The range() function has a start : Which number to begin with, then stop : at which number to stop, and step which means which how much increment.
for number in range(1,4):
print(number)
well you can easily specify the range for example range(1,4) will give you 1,2,3
I'm doing a little project and I essentially need to figure out the middle 5 digits of a number (e.g. 123454321 would return 34543). If the number is 4 digits (e.g. 1234) it will return the middle two (in the case of 1234 this would be 23). If the number is 3 digits, it will return the middle number (e.g. 123 would return 2), and if the number is 1 or 2 digits the code won't accept the input.
I've tried doing some research about this online, but haven't really managed to find anything other than the "Middle-square method" but the implementation for python they have doesn't seem to work.
num = 730945296 #Random number for testing
num_len = len(str(num))
print(num*num) #debug
print(str(num*num).zfill(num_len)) #debug
num = int(str(num*num).zfill(num_len)[round(num_len/4):round((num_len/4)*3)])
print(num)
is my representation of the implementation for python but as I stated above, this doesn't seem to work.
In this case the output was 9452 but I expected 09452.
I'm aware I'm not doing extra checks like whether output is more than 5 digits or how long input is but I figured I should concentrate on getting the middle digits first.
Hint: The reason you are not getting 0 at the beginning of the answer, is that you are storing the value as int. Try using string as a number and the problem will be a piece of cake.
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
I have 2 questions I need to ask for help with. One question I don't entirely understand so if someone could help me to that would be great.
Question One (the one I don't entirely understand):
One definition of e is
Formula for e
This can be calculated as my_e = 1/math.factorial(0) + 1/math.factorial(1) + 1/math.factorial(2) + 1/math.factorial(3) + …
Let n be the input number of the math.factorial() function. n successively takes on 0, 1, 2, 3 and so on. Find the smallest n such that the absolute value of (my_e – math.e) is less than or equal to 10-10. That is, abs(my_e - math.e) <= (10 ** -10).
I just don't entirely understand what I am being asked to do. Clarification would be great. Thanks!
Question 2:
Ask the user to type in a series of integers. Sum them up and print out the sum and the number of integers the user has entered.
My code
So what should happen is after I enter the numbers I want to enter and hit the enter key, it should calculate and print out "sum = 25 count = 3". The screenshot shows what error message I am getting.
Any help you have is welcomed and greatly appreciated.
As far as you first question goes:
>>> import math
>>> math.e
2.718281828459045
>>> sum(1.0/math.factorial(i) for i in range(5))
2.708333333333333
>>> abs(sum(1.0/math.factorial(i) for i in range(5)) - math.e) < 10**-10
False
>>> abs(sum(1.0/math.factorial(i) for i in range(30)) - math.e) < 10**-10
True
So, somewhere between n == 5 and n == 30 you get 10 decimal places for e. Create the sum term by term in a while-loop (instead of by using the sum function as I have, since you are unlikely to have seen that syntax yet). At each pass through the loop, compare the sum with math.e. Stop when you get the target accuracy. Return the final n.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is my problem ? I want act inverse number--example : 123 ==>321
def loop(a):
i=0
while(a>=1)
print(a%10)
s=s/10
i=i+1
Your solution has a few problems, aside from the indentation and the missing colon.
First of all your are using print which automatically adds a line break, so that might not be what you want the result to look like. You could store the result in a string which you append the latest character to and then print it once at the end.
Further, you are using a variable s which was never used before. In thise case it should be a as you want to strip off the last digit using an integer division by 10. Note that in this case, this will only work like that in Python 2, as Python 3 will use a float division there (e.g. 15 / 10 == 1.5). You can prevent that by explicitly using the integer division there (this will also make your intend more clear): s = s // 10 (note the two slashes).
Lastly, you are incrementing the variable i without ever using it, so you can just get rid of it.
In the end, it might look like this:
def reverse (a):
rev = ''
while a > 1:
rev += str(a % 10)
a = a // 10
A shorter solution, utilizing the fact that you can just reverse strings:
>>> num = 123
>>> rev = int(str(num)[::-1])
>>> rev
321
If you leave out the int(), you can even keep trailing/leading zeros and get a string instead:
>>> num = 3210
>>> str(num)[::-1]
'0123'
Few issues:
Your indentation does not match. PEP 8 suggests 4 spaces for indentation.
You're missing a colon after while(a>=1)
Although this isn't an issue, you don't need the parentheses in the while loop, it can just be while a >= 1
s = s/10 might not return what you expect. For example, 12/10 == 1 (unless you're dealing with floats here).
This can all be simplified using slicing:
>>> print int(str(123)[::-1])
321
It is important to indent correctly. (And don't mix tabs and spaces.)
def loop(a):
i = 0
while a >= 1:
print(a % 10)
a = a / 10
i = i + 1
You were also missing a colon after the while condition.