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 3 years ago.
Improve this question
Functions are confusing me majorly.
What is wrong with my code here, I'm sure there are plenty things, but elaborate on what I'm doing wrong, please.
2000 steps is 1 mile, input is number of steps, output is miles walked.
def steps_to_miles(user_steps):
steps = input();
mile = steps / 2000
return user_steps
print('%0.2f' % user_steps)
Problems
Input returns a string, which you cannot do arithmetic on
Python doesn't use semicolons as line terminators
You're returning the number of steps, not the number of miles
You're not calling the function in the print statement
Your conversion function shouldn't ask for input
Try this
def steps_to_miles(user_steps):
miles = int(user_steps) / 2000
return miles
Example
>>> steps = input()
4321
>>> print( '%0.2f' % steps_to_miles( steps ) )
2.16
for calculating steps code will be like this:
def steps_to_miles():
steps = int(input('Enter Steps: '));
mile = steps / 2000
return mile
print('You Walked',steps_to_miles(),'miles')
The input() function waits for user input - if you feed it no arguments in your code it will show no message and wait for your input.
It does not represent the function input - that is already represented by user_steps parameter.
The user_steps is defined only within the scope of your function (the indented part) so the user_steps variable in your print statement is not the same variable.
I think you meant to write it like this
def steps_to_miles(steps):
return steps / 2000
user_steps = input("Please enter the number of steps walked:\t")
print("You have walked %0.2f miles !" % steps_to_miles(user_steps))
Your code should be like
def steps_to_miles():
steps = input();
mile = steps / 2000
return mile
print('%0.2f' %steps_to_miles())
This should work.
Related
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 1 year ago.
Improve this question
I'm trying to make a dice roller in Python for Warhammer 40,000, and the end goal is for the user to input their Ballistic Skill (and any modifiers), the number of attacks, their Strength, the opponent's Toughness, and other stats. The program will use these stats and complete the following.
Generate a number of random integers equal to the number the user specified as the number of attacks.
Compare these to the Ballistic Skill. Any integers that are greater than or equal to the BS are passed.
Test these against the target's Toughness (this will be summarized in a later question).
Test the successes against the target's save.
Calculate damage.
Right now, I have this smidgen of code.
ballistic: int = input("What is your Ballistic Skill? Please answer in this format: '3'.")
shots: int = input('How many shots will your weapon be firing? Answer as a number.')
print("Rolling dice to hit now. Please wait...")
hits = random.randint(1, 6)
Note the declaration of the variable "hits"- this is important.
The question is: How do I run the random.randint function a number of times equal to the variable "shots"?
Jakub pointed out that in Python a for loop is typically what you would use to repeat an operation a specified number of times. Here is a very basic implementation to give you a feel for how that works.
EDIT 1: Updated Example 1 to print hits only if the value is equal to or greater than the ballistic value.
EDIT 2: Didn't modify the code, but modified the inputs (bumped number of shots up from 10 to 20) to better illustrate the relationship between ballistics and hits.
Example 1:
import random
ballistic = int(input("Enter Ballistic Skill: "))
shot_count = int(input("Enter number of shots: "))
for shot in range(shot_count):
hits = random.randint(1, 6)
if hits >= ballistic:
print(hits)
Output:
Enter Ballistic Skill: 3
Enter number of shots: 20
3
4
5
6
5
4
5
6
4
4
3
One problem with the simple approach is that the value of hits is lost at the end of the loop. That may be okay for what you are doing, but sometimes you want to build a list of something and keep it around for use after the loop. To do that, there is a more advanced technique called list comprehension that is often used, but for illustration purposes we can just build out the example above.
Example 2:
import random
shot_count = int(input("Enter number of shots: "))
hits_list = []
for shot in range(shot_count):
hits = random.randint(1, 6)
hits_list.append(hits)
print(hits_list)
Output:
Enter number of shots: 3
[1, 4, 5]
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 3 years ago.
Improve this question
So basically I want to calculate the average of (x) test marks. So far this is what I have:
for i in range(3):
testmark = int(input("Enter one test mark: "))
print("Calculating...")
average = (testmark + testmark + testmark) / (i + 1)
print("Your average is", average, "percent.")
However, I want it so that the average variable add ALL the inputs together. Right now, I made it so that it only calculates 3. I want it something like:
for i in range(7):
testmark = int(input("Enter one test mark: "))
print("Calculating...")
average = (**[sum of all test marks]**) / (i + 1)
print("Your average is", average, "percent.")
That's a good start. However, You can do it in a better way like this:
iters = int(input("How many numbers do you have?\n"))
sum = 0
for number in range(iters):
sum += int(input("Give a number: "))
print(f"The average of those inputs is {sum/iters}") # I'm assuming you have Python >= 3.6
Lets start by taking a look at the issues you encountered and how you can address them;
for i in range(3):
testmark = int(input("Enter one test mark: "))
print("Calculating...")
average = (testmark + testmark + testmark) / (i + 1)
print("Your average is", average, "percent.")
You override testmark every iteration, meaning you only ever store ONE value
You attempt to call i outside of the for loop, which will fail if i is not defined prior
We can adjust you code to be more resilient and provide the end-user more ability to modify the functions, such as how may iterations we test and the testmarks we would like to calculate.
test_marks = []
tests = int(input('How many tests are there? '))
#How many tests are there? 5
for i in range(tests):
test_marks.append(int(input("Enter one test mark: ")))
#Enter one test mark: 5
#Enter one test mark: 10
#Enter one test mark: 56
#Enter one test mark: 99
#Enter one test mark: 1
print(f"The average test mark is: {sum(test_marks) / len(test_marks)}")
#The average test mark is: 46.5
Declare an empty list to store marks in as test_marks
Prompt the user to define the total tests being entered
Iterate over the total tests and prompt the user for a mark
Calculate and print the average (This is Python 3.6+ Syntax!)
This is a good opportunity to dive a little deeper to bolster your understanding of some core workings on Python, i have included a few links for your learning!
Iterating over lists in Python
Appending & extending lists
Python 3.6 f-strings
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 3 years ago.
Improve this question
Create a function called format_currency which takes in a float as input and returns a string containing the number with a $ in front of it, with 2 decimal places.
i got no idea what i have done
def format_currency()
format("format_currency")
format_currency = float(input("Enter amount"))
print ("$" , format_currency)
Here you go
pi = 3.1415926535
def format_currency(f):
return '$%.2f' % f
print(format_currency(pi)) # $3.14
It's important that you validate whether the number is a float or not. Expanding on E. Dogan's answer:
def format_currency(amount):
try:
float(amount)
return '$%.2f' % float(amount)
except ValueError:
return "Not a number"
print(format_currency(3)) # $3.00
print(format_currency(3.123)) # $3.12
print(format_currency("not a number")) # Not a number
print(format_currency("3")) # $3.00
Also check: How do I check if a string is a number (float)?
You can do that something like this
def formatCurrency(amount):
return "${0:.2f}".format(amount)
amount = float(input())
print(formatCurrency(amount))
when i understand your question correct you need this
def format_currency(amount): # input argmuents are in the braces ()
if type(amount) is float
return f'${amount:.2f} # with return we can return values from a function
else:
raise ValueError("Amount must be a float")
# to use the function
money = format_currency(3.1234) # input arguments are passed in the braces ()
print("i have", money)
the f'' part is called f strings and is special syntax for format strings in Python 3.x.
The thing in curly braces {} is evaluated after the double dot : you can give a format specification so here its .2f which means only 2 decimal places
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 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
Below are the guidelines for the problem. My class is using Python 3.5. Thank you so much!
Write a program that approximates the value of pi by summing the terms of the Gregory Leibniz
series:
-4/1 – 4/3 + 4/5 – 4/7 + 4/9 – 4/11 + 4/13 …
-The program must prompt the user for the number of terms to sum, then display the iteration number, approximation of pi, and the absolute value of the difference between pi from the math library and your approximation each time a new term is included in the series.
This is what I have so far:
def main():
n = int(input("Please enter a value for N:"))
for i in range(1,n,7):
total = ((1.0/(i+i+1))-(1.0)/(i+i+2))+(1.0)/(i+i+4)
value = 4*(1-total)
print(value)
main()
There are 3 things wrong with your code:
You're incrementing i by 7 in range(1, n, 7).
Every second term in the Leibniz series is negative, yours is not.
You are not adding the terms to total, you are only storing the last value into total.
Editing your code, this will give you what you want:
def main():
n = int(input("Please enter a value for N:"))
total=0
for i in range(1,n):
total += (-1)**(i+1)*((1.0/(i+i+1)))
value = 4*(1-total)
print(value)
main()
Now giving a value of 1000 for N, you would get 3.1405926538397924.
Oups!
You made great efforts to make as many mistakes in so few lines of code :-)
As every second term in Leibniz series is negative, you should process numbers stepping by 2:
def main():
n = int(input("Please enter a value for N:"))
total = 0
for i in range(0,n,2):
total += ((1.0/(i+i+1))-(1.0)/(i+i+3))
value = 4*total
print(value)
But Leibniz series has a very slow convergence. For n=10000 you still only get 3.14149265359 ...