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].
Related
I am solving the following Codewars problem: https://www.codewars.com/kata/56dbe0e313c2f63be4000b25/train/python
there are a few examples are on the website too.
I have written the following code:
def vert_mirror(str1):
x = str1.split()
temp_1 = []
for i in x:
temp_1.append(i[::-1])
y = "\\n".join(temp_1)
return print("'"+str(y)+"'")
def hor_mirror(str1):
x = str1.split()
temp_2 = []
for i in range(1, len(x) + 1):
temp_2.append(x[(-i)])
y = "\\n".join(temp_2)
return print("'"+str(y)+"'")
def oper(fct, s):
if fct is vert_mirror:
vert_mirror(s)
elif fct is hor_mirror:
hor_mirror(s)
Now, when you type this code into the website, and you test it for the vert_mirror test, you get the exact output that they expect, but for some reason the test fails? Any idea why?
I have tested it on my IDE and it seems to produce the right output, but for some reason when I run the test with the above code on the website it fails.
Try the following and it should work:
Change line return print("'"+str(y)+"'") to return str(y) . This does two things, in your code you are returning the return value of print function which is None, so instead of returning that we want to return a string. Second, you don't want to append ' to the answer. Make this change in both the functions.
In your oper function add return keyword before vert_mirror(s) and hor_mirror(s). Currently your oper function is not returning(explicitly) anything, which leads to the default return value of None(the default return value of a function in python).
Change \\n to \n.
This will pass the tests.
Feel free to accept this as answer if it helps.
Im new to python and cant figure out how to get these functions to call themselves. It asks for an input but no matter what gives 0 as the output. Can someone help debug?
userinput = input("Enter three numbers: ")
userinput = userinput.split(',')
finalsum = 0
finaldata = []
def formatinput(x):
sqrdata = []
for element in x:
sqrdata.append(int(element))
return(sqrdata)
def findsquare(x):
return (x*x)
def sumthesquares(y):
for element in y:
temp = findsquare(element)
finaldata.append(int(temp))
finalsum = finalsum + temp
return finalsum
def findthesquares(userinput):
finalsum = sumthesquares(formatinput(userinput))
print(finalsum)
Have you actually tried running your code? From what you've posted, it looks like you never actually call your functions...
They're defined, but you're missing the actual calls, like formatinput(userinput).
For future reference, if you put something like print("Got here!") into your functions, you can test that they're being called.
I am trying to write a function that shows me the multiplication table of a number:
def tabellina(n):
for i in range (1,11):
print(n*i)
If I write the function in this way, it works fine.
If I put 4 instead of n, it prints:
4,8,12,16,20,24,28...40
But if I use return instead of print, it does not work anymore, and it just returns me the n value.
I have to use the return and I can’t use the print
What should I do? (I MUST use return NOT print)
The reason it returns the n value if you use return is because the loop doesn't run fully. When you use return, it returns the value, which exits the function. The rest of the loop never executes.
What you want instead is to return an array. The easiest way is probably a list comprehension:
def tabellina(n):
return [n*i for i in range(11)]
you could save the output in a string and then return that. for example:
def tabellina(n):
table = ''
for i in range (1,11):
table += ((n*i) + ' ')
return table
you could replace ' ' with any devider (like ',') as you want.
Try the following script:
def tabellina(n):
joint = ""
for i in range (1,11):
joint = joint + (" %s" % n*i)
return joint
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 am not sure why it is giving me this error... the part it says is giving me the error is the previousFirst + previousSecond = previousSecond. If you are wondering the goal is to print out as many fibonnaci numbers that the user wants to print out.
def fibbonaci():
fibbNumber = input("How many Fibonacci numbers should I print for you?")
fibbNumber = int(fibbNumber)
global counter
counter = 0
global previousFirst
previousFirst = 0
global previousSecond
previousSecond = 1
global previousSaved
previousSaved = 1
while (counter < fibbNumber):
previousSaved = previousSecond
previousFirst + previousSecond = previousSecond
print (previousFirst)
print (previousSecond)
counter += 1
fibbonaci()
1. You have the assignment turned around. The format is
<i>variable</i> = <i>new value</i>
so make that:
previous_second = previous second + previous_first
2. A more normal (non-Python) way to do this is:
next = current + previous
previous = current
current = next
where "next" is a temporary variable to compute the next in sequence.
3. Python has the ability to do multiple assignments, eliminating the need for temporary variables in this an many other cases. You can do all of the above with:
current, previous = current+previous, current
Both computations on the right are done before any assigning happens. The new value of current is the sum of the old values current+previous, and the new value of previous is the old value of current. Put that in a "for xyz in range(n):" loop, after initializing current=0, previous=1, and you get a loop that works for all non-negative n (including 0). The final value of current is your result.
4. Its "Fibonacci", not "Fibbonaci", and the guy's real name was Leonardo.
The left hand side of an assignment statement must be a valid name, not an expression. (The + is an operator, which means its included in expressions)
This is the line of the culprit,
previousFirst + previousSecond = previousSecond
Also, your code does have a little bit of formatting issues, namely the indentation is bad for the first function. Normally you can get away with this, but being Python, it's part of the language syntax. It also might just be how you copied and pasted it to Stack, take a look at the tips in How to Edit and How to Format bars, when editing your post.
The line should be
previousSecond = previousFirst + previousSecond
That's the problem
UPDATE:
There are some logic error to calculate fibbonaci number, the while part coule be:
while (counter < fibbNumber):
previousSaved = previousSecond
previousSecond = previousFirst + previousSecond
previousFirst = previousSaved
print (previousFirst)
print (previousSecond)
counter += 1