I'm trying to learn python and am attempting to create a simple formula that converts miles to kilometers and returns some text with the conversion.
Here's what I have:
def mile(x):
z = x * 1.609344
print "%.2f" % z
x = float(raw_input("How many miles are you traveling? "))
z = mile(x)
print "That's about % kilometers." % z
Can someone explain why this doesn't work? I could definitely set up the mile function to print a sentence with the conversion, but I didn't want to do that.
Your function needs to return the result.
def mile(x):
z = x * 1.609344
return z
You have a couple of problems. The first is that your function does not return a value. When the line z = mile(x) is run, the mile(x) part will be replaced by whatever is returned by mile. The code you want is:
def mile(x):
z = x * 1.609344
return z
Note that it is irrelevant what variable you assign this to; it doesn't have to match the variable that is being returned. For example, both y = mile(x) and z = mile(x) will assign to the given variable properly.
Second, your string formatting won't work. This is that part that looks like "That's about % kilometers." % z. The string formatting replaces %<identifier> with the given variable, where <identifier> tells what type the variable is (and possibly some info about how to display it). You will need the identifier f or, like in the earlier print statement, .2f, giving "That's about %.2f kilometers." % z
As way of an explanation:
You need to return the value of your computation/conversion from the function so that the result can be assigned to variable z. You can then print it out.
Before, you were printing the value inside your function, and not returning anything, which resulted in z getting assigned None which is why your print at the bottom didn't work.
In general it's best to do your work/computations inside the function and then return a value that you can decide how to use.
#wim shows the correct code for the function. If you now do
z = mile(x)
print "That's about %.2f kilometers." % z
you'll get the result you were expecting. (note the correct formatting as pointed out by #Aaron Dufour, you'll get 2 numbers past behind the decimal point when you print your result) Incidentally, your first print statement was correct, only the 2nd one was missing the complete formatting directive.
Related
I've been at this for hours and hours. I think my problem is I need to use a return in my first function so that I can use this function as an argument in my second function. However, it seems that if I use a return, the data is somehow not being passed properly to the second function. I say that because I can't seem to format it properly if i comment out my print statement and only use a return (the return statement won't let me include the end = '' so it comes out vertically instead). Then the second function just spits out the first digit of my first function's return. I'm so lost and i need to get some sleep now I guess. Been up all night with this. Is there some way I can return the data int he first function and make it be a nice horizontal string like it would be if I used my print statement instead? (Or does that not matter and I'm way off track?) Please let me know if I can clarify something. Just a nudge in the right direction would help.
Instructions: Write a program that takes in a positive integer as
input, and outputs a string of 1's and 0's representing the integer in
binary. For an integer x, the algorithm is:
As long as x is greater than 0
Output x % 2 (remainder is either 0 or 1)
x = x // 2
Note: The above algorithm outputs the 0's and 1's
in reverse order. You will need to write a second function to reverse
the string.
Ex: If the input is:6
the output is:
110
The program must define and call the following two functions.
Define a function named int_to_reverse_binary() that takes an integer
as a parameter and returns a string of 1's and 0's representing the
integer in binary (in reverse).
Define a function named
string_reverse() that takes an input string as a parameter and returns
a string representing the input string in reverse. def
int_to_reverse_binary(integer_value) def string_reverse(input_string)
My code:
Define your functions here.
def int_to_reverse_binary(int_number):
while int_number > 0:
#print (int_number % 2, end='')
return int_number % 2
int_number = int_number // 2
def string_reverse(input_string):
for i in reversed(str(input_string)):
print(i,end='')
if __name__ == '__main__':
# Type your code here.
# Your code must call int_to_reverse_binary() to get
# the binary string of an integer in a reverse order.
# Then call string_reverse() to reverse the string
# returned from int_to_reverse_binary().
x = int(input())
int_to_reverse_binary(x)
string_reverse(int_to_reverse_binary(x))
1: Compare output
0 / 2
Output differs. See highlights below.
Input
6
Your output
0
Expected output
110
2: Unit test
0 / 2
Convert 19 to binary using int_to_reverse_binary() and string_reverse()
Your output
1
Test feedback
string_reverse(user_input) did not return a value.
Your function may be missing a return statement.
3: Unit test
0 / 3
Convert 255 to binary using int_to_reverse_binary() and string_reverse()
Your output
1
Test feedback
string_reverse(user_input) did not return a value.
Your function may be missing a return statement.
The return statement in Python also acts as the ending point of the function. i.e. no statement will be executed once a return statement is encountered in a function. So, when the while loop is being executed, the interpreter sees a return statement and stops executing any further. If you wish to return multiple values from the function you can do 2 things,
Instead of using a while loop in s function, use the function in the while loop:
Sample Code:
def foo(num):
return num % 2
i = 0
while i< 10:
print(foo(i))
i += 1
Use a list to return all values at once. Sample Code:
def foo(num):
a = []
i = 0
while i < num:
a.append(i)
i+=1
print(foo(10))
Code With corrections:
def int_to_reverse_binary(int_number):
# print('i', int_number)
a = []
while int_number > 0:
a.append(int_number % 2)
int_number = int_number // 2
# print('a', a)
return a
def string_reverse(input_string):
print(''.join([str(i) for i in input_string])[::-1])
if __name__ == '__main__':
x = int(input())
# a = int_to_reverse_binary(x)
string_reverse(int_to_reverse_binary(x))
You seem to have made this unnecessarily complex. f-string formatting will give you the binary representation of your integer then reverse the string with a slice as follows:
def int_to_reverse_binary(int_number):
return f'{int_number:b}'[::-1]
print(int_to_reverse_binary(100))
Output:
0010011
I am currently studying Software Development as a beginner and I have a task in my programming class to calculate and display a factorial using a loop. I've been given the pseudo-code and have to translate it into true code and test it in the REPL to make sure it returns the expected results.
I almost have it but I've run into two issues that I just can't seem to resolve.
1) The function is returning an extra line of "None" after the calculation and
2) The answer is displaying over multiple lines when I want it to display on a single line.
My current code (which does return the correct answer) is as follows:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
When I test, using 3 for example, the REPL returns the following:
>>> print(calcFactorial(3))
3! = 3
x 2
x 1
= 12
None
So I have the correct answer but with an extra line of "None" which I would like to remove (I believe it has something to do with the print function?) and I don't know how to format it correctly.
Any help would be much appreciated.
your function calcFactorial(3) prints already, so you shouldn't call it with
print(calcFactorial(3))
just call it with
calcFactorial(3)
without the print function.
you might think about calling the function calc_and_print_factorial() in order to make it clear, that this function does already the printing
Regarding your second question:
Blockquote
2) The answer is displaying over multiple lines when I want it to display on a single line.
You can fix it by using a single print statement:
def calcFactorial(number):
factorial = 1
string = str(number) + "! = " + str(number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*(number-count)
string = string + " x " + str(number-count)
factorial = factorial * number
print(string + " = " + str(factorial))
This will give you:
IN: calcFactorial(3)
OUT: 3! = 3 x 2 x 1 = 6
On a side note: you might want to think of how to implement this recursively. Maybe that comes later in your class but this would be one of the first go-to examples for it.
Adding to the blhsing's answer, you should choose between these built-in ways to print the "returned" value.
First way:
def calcFactorial(number):
... # <- Your function content
return factorial
Then, call your function with a print() to get the explicitly returned value, as you can see in the return factorial line. See this reference for more details:
print(calcFactorial(3))
Second way:
Having the same function definition with its return statement, just call the function with its instance statement:
calcFactorial(8)
By default, python will print the returned value without a print()
Third way:
Just call the function (without the explicit return statement, this will return a "None" (null-like) value by default), using the print() method. Do NOT use print() inside another print().
Your calcFactorial function does not explicitly return a value, so it would return None by default, so print(calcFactorial(3)) would always print None.
You should make the calcFactorial function return factorial as a result at the end:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
return factorial
So I have the correct answer but with an extra line of "None" which I would like to remove
You are printing the return value from your function. In this case, you haven't specified a return value with a return statement so the function automatically returns None.
To fix the problem, you should return a value from your function. Note that you don't need to call print() for final answer because the REPL already does this for you.
Note that the REPL will automatically print the return value for you, so you can just type calcFactorial(3) instead of print(calcFactorial(3)).
Additionally, you are not getting the correct answer. You should get 6 instead of 12. It looks like you are trying to count down from number and multiplying each number together. You can get the same result by counting up from 1. This will lead to much simpler code and avoid the error.
If you want to understand why your code isn't doing the correct thing, look closely at factorial = factorial*number-count and think about the order of operations that are used to calculate the result here.
I thought of creating a function which will give a range of an input at the same time change the value if a certain condition is met.
def num(u) :
for x in range(1,u):
if (x) %2==0:
x ='love'
print x
print num(10)
output :
1
love
3
love
5
love
7
love
9
'Wow this was great' (i thought). Then I decided to add more conditions to make my program look mature. Well it wasn't as I thought!!!
def num(u) :
for x in range(1,u):
if (x) %2==0:
x ='love'
print x
if (x) %3==0:
x ='fux'
if (x) %5==0:
x ='buzz'
On printing I got :
output :
/data/data/org.qpython.qpy/files/bin/qpython.sh "/storage/sdcard0/qpython/scripts/.last_tmp.py" && exit
python/scripts/.last_tmp.py" && exit <
Traceback (most recent call last):
File "/storage/sdcard0/qpython/scripts/.last_tmp.py", line 8, in <module>
print num (10)
File "/storage/sdcard0/qpython/scripts/.last_tmp.py", line 5, in num
if (x) %3==0:
TypeError: not all arguments converted during string formatting
1|u0_a115#g150_g:/ $
How can I pass in more conditions at this point.
This is due to the way you've set up your conditional statements. Think about what happens after one of the cases is true. After x % 2 == 0 passes, you change the value of x to "love". Any of the subsequent conditions will now be referencing the new value of x, and of course trying to use the modulus operation on a string doesn't make any sense, thus causing the error.
To fix this, use a different variable to store the resulting string, or simply print it directly, rather than overwriting the value of x.
An alternative would be to change the chain of if statements to an if/elif/else sequence, to guarantee that only one of the blocks of code will execute.
If two of the ifs are entered, x will be assigned a string, and no longer be an int, so you can't use the modulu operator on it (in fact, % is interpreted as the string format operator). You can clean up the code by just printing the strings you want without assigning them to x:
def num(u) :
for x in range(1,u):
if (x) %2==0:
print 'love'
if (x) %3==0:
print 'fux'
if (x) %5==0:
print 'buzz'
I am not sure what exactly you are trying to achieve but error is every simple. you can not perform mathematical operation on string, it has to be integer. Also, your code is not pythonic :)
def num(u):
for x in range(1, u):
if x % 2 == 0:
x = 'love'
print x
# Following code will throw error as now x is not INT
if x % 3 == 0:
x = 'fux'
if x % 5 == 0:
x = 'buzz'
I'm trying to make the following function output the correct answer, but the 'rightSide' variable is being made as an integer, and doesn't have any decimals.
def G(mass1, mass2, radius, force):
rightSide=(mass1*mass2)/(radius**2) #I want this to be a float
print rightSide
if rightSide==0:
print("The operation resulted in a zero, error!")
else:
answer=force/rightSide
print(str(answer)+" is the gravitation constant (G)!")
I just want all the variables to be floats, but the problem starts with 'rightSide'.
I tried the following with no success:
float(rightSide)=(mass1*mass2)/(radius**2)
--
rightSide=(float(mass1)*float(mass2))/(float(radius)**2)
Any tips? Thanks!
Nevermind, I just re-ran the second code that I hand typed in the question and it worked -_-
In general
x = float(2)
Or
y = 10
x = float(y)
In your case,
rightSide=float((mass1*mass2)/(radius**2))
You need to make one of the inputs a floating point value. Try changing 2 to 2.0. E.g.:
>>> x=10
>>> x**2
100
>>> x**2.0
100.0
Note that in Python 3 division automatically returns a floating point, and the new // operator explicitly does integer division.
Try this:
def G(mass1, mass2, radius, force):
rightSide = (float(mass1)*mass2) / (radius**2) #I want this to be a float
print rightSide
if rightSide==0:
print("The operation resulted in a zero, error!")
else:
answer=force/rightSide
print(str(answer)+" is the gravitation constant (G)!")
The problem
I want get_scores to take tests and use it as an int for x > 0 but be able to print tests. I've tried fiddling around for awhile and I can't get what I want.
What I've tried
My problem is that I want the get_scores method to print "What percentage are tests weighted". Tests is assigned to an int so it can't print anything unless I do this which prints an int which I don't want it to do:
int(input("What percentage are" + str(x) + "weighted?"
I've tried a couple different things such as:
get_initial_input function ( like this: testsp = get_scores("tests") )
This makes it so x > 0 can't be processed because x is a string. I also tried:
int(x) > 0
... to see if it was as simple as changing it back to an int (didn't work).
The code
def main():
tests = get_initial_input("tests")
assignments = get_initial_input("assignments")
exercises = get_initial_input("exercises")
labs = get_initial_input("labs")
finals = get_initial_input("finals")
testsp = get_scores(tests)
assignmentsp = get_scores(assignments)
exercisesp = get_scores(exercises)
labsp = get_scores(labs)
finalsp = get_scores(finals)
def get_initial_input(x):
val = int(input("How many "+ x + " were there? "))
return val
def get_scores(x):
if x > 0:
xp = int(input("What percentage are "+ str(x) + " weighted?"))
return xp
main()
Is there anyway to get what I want?
Thanks for your help in advance.
You could have get_scores take two arguments: one being a string giving the type of the assignment, and therefore what to print, and the other being the number of such assignments:
def get_scores(x, kind):
if x > 0:
xp = int(input("What percentage are "+ kind + " weighted?"))
return xp
Which you'd call like:
testsp = get_scores(tests, 'tests)
But it might make more sense to write the function without the if, and do the checking before you call it.
I may be a little confused, but it sounds like you are trying to use the variable tests to represent both an integer value and a string at the same time. You could turn tests into a string, and then use string indexing to get what you want:
tests = ["tests"]
Now you can get the second value into the list by using:
tests.append(get_initial_input(tests))
Now when you want to print the string, just use print tests[0] and when you want to print the number of tests, use print tests[1].