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
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 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,
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
Note: I cannot use any of the built in functions to solve this.
This is the question:
Given a function that returns a random integer number between 1 and 5, create a function that creates a random integer between 1 and 7.
As it has been answered in Adam Rosenfield's solution a while ago you may try to use an algoritm similar to this one below:
int i;
do
{
i = 5 * (rand5() - 1) + rand5(); // i is now uniformly random between 1 and 25
} while(i > 21);
// i is now uniformly random between 1 and 21
return i % 7 + 1; // result is now uniformly random between 1 and 7
EDIT: Translation to python:
def rand7():
i = 0;
while True:
i = 5 * (rand5() -1) + rand5()
if i > 21:
break
return i % 7 + 1
Apparently the following doesn't work. See the linked answer and the other responses as well.
Well, here is an approach I am thinking of. It could be wrong. I am going with the assumption that the result should be randomly distributed within the larger range.
Generate 7 random numbers using the given random functions (that generates numbers [1,5]) and calculate their sum.
This will result in a value between 7 (1 * 7) and 35 (5 * 7).
Because this value is evenly divisible by the target range and randomly distributed, then it seems like it would be valid to collapse the intermediate range [7,35] back to [1,7] without losing uniformity.
Or maybe that's not quite it - but it seems like exploiting a common multiple between the numbers is key.
import random
def winningFunc():
return originalFuncReturning1to5() + random.randint(0,2)
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
Basically, the user will enter a probability of getting success p = .34, so how do I determine the number of trials it takes to get success?
I know that I could get the number of trial by making a counter like n+= 1 but not sure how to use this probability value. Help will be greatly appreciated.
You can use random() from the random module to generate a floating point value in the range [0,1]. Then you can compare that value to the user-inputted probability. If the random value is less than the user's given probability, you have a success.
Once you understand that, all you need is a simple while loop that will keep generating numbers until you get a success.
Here is an example of a function that might do what you want:
import random
# The function you wanted
def run_trials(p):
'''only accepts int or float in range [0.0, 1.0]'''
# Count trials
num_trials = 1
while True:
r = random.random()
if r <= p:
print "This took", num_trials, "trial(s) to get a success."
break
else:
num_trials += 1
#Input
while True:
p = input("Please enter a probability: ")
if isinstance(p, float) or isinstance(p, int):
if 0 <= p <= 1:
break
run_trials(p) # pass it to the function