Functions: printing blank lines (Python) - python

Page 27 of "How to think like a computer scientist: Learning with Python" reads:
"As an exercise, write a function called nineLines that uses threeLines to print nine blank lines. How would you print twenty seven lines?"
I wrote:
def newLine():
print
def threeLines():
newLine()
newLine()
newLine()
def nineLines():
threeLines()
threeLines()
threeLines()
print 1
print nineLines()
print nineLines()
print nineLines()
print 2
The result was:
1
None
None
None
2
Why those "none" there? I suppose I don't want them there. Was my reasoning correct? Thanks.

Your reasoning is correct, except that the print is redundant. nineLines is going to print the lines anyway. What your print statement is printing is the return value of the function, which since it isn't explicitly returning anything is None.

def threeLines():
for i in range(3):
print '\n'
def nineLines():
for i in range(3):
threeLines()
for i in range(3):
nineLines()

Related

how to use conditionals (multiple IF and ELSE statements) in a function using PYTHON [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 6 months ago.
I'm new to programming and i'm taking a course on edx.org.
i'm having issues with using conditionals in a function. each time i call the function it gives me the output i desire but also shows "NONE" at the end. is there any way i can use return keyword in the code? below is the question and my code.
###create a functions using startswith('w')
###w_start_test() tests if starts with "w"
# function should have a parameter for test_string and print the test result
# test_string_1 = "welcome"
# test_string_2 = "I have $3"
# test_string_3 = "With a function it's efficient to repeat code"
# [ ] create a function w_start_test() use if & else to test with startswith('w')
# [ ] Test the 3 string variables provided by calling w_start_test()
test_string_1='welcome'.lower()
test_string_2='I have $3'.lower()
test_string_3='With a function it\'s efficient to repeat code'.lower()
def w_start_test():
if test_string_1.startswith('w'):
print(test_string_1,'starts with "w"')
else:
print(test_string_2,'does not start with "w"')
if test_string_2.startswith('w'):
print(test_string_2,'starts with "w"')
else:
print(test_string_2,'does not starts with "w"')
if test_string_3.startswith('w'):
print(test_string_3,'starts with "w"')
else:
print(test_string_3,'does not start with "w"')
print(w_start_test())
There are a number of questions here, I'll try to answer them.
For some reason, you are attempting to print out your function, this will just attempt to return the type of the function which is None. That won't return anything.
From my understanding you are wanting to compare many different strings, there are a few ways you can do that but here's my solution:
You take your 3 strings, and put them into a list like so:
test_strings = ['welcome'.lower(),'I have $3'.lower(),'With a function it\'s efficient to repeat code'.lower()]
We create our function as you have done so already but include parameters instead:
def w_start_test(test_string_list):
for string in test_string_list:
if string.startswith('w'):
print(string,'starts with "w"')
else:
print(string,'does not start with "w"')
return
This function takes a parameter, test_string_list and loops through all objects within this list and does the comparisons you have provided. We then return nothing because I am not sure what you want to return.
Let's say you wanted to return 'Completed', you would do this:
test_strings = ['welcome'.lower(),'I have $3'.lower(),'With a function it\'s efficient to repeat code'.lower()]
def w_start_test(test_string_list):
for string in test_string_list:
if string.startswith('w'):
print(string,'starts with "w"')
else:
print(string,'does not start with "w"')
return 'Completed Test'
def __main__():
ValueOfTest = w_start_test(test_strings)
print(ValueOfTest)
Functions are slightly complicated. The solution which you are looking for is as below:
def w_start_test(alpha):
if alpha.lower().startswith("w"):
print("The word starts with 'w'")
else:
print("The word doesn't start with 'w'")
w_start_test(test_string_1)
w_start_test(test_string_2)
w_start_test(test_string_3)
I was trying to discover the right answer. I think I did so.
Here it's my variant of the problem solution.
test_string_1 = "welcome"
test_string_2 = "I have $3"
test_string_3 = "With a function it's efficient to repeat code"
# [ ] create a function w_start_test() use if & else to test with startswith('w')
# [ ] Test the 3 string variables provided by calling w_start_test()
if test_string_1.lower().startswith('w'):
print('this string starts with \'w\'')
else:
pass
if test_string_2.lower().startswith('w'):
print('this string starts with \'w\'')
else:
print('this string doesn\'t start with \'w\'')
if test_string_3.lower().startswith('w'):
print('this string starts with \'w\'')
else:
pass

I keep getting None returned from my python program

The code is as followed
# Cristmas Quiz
import time
from time import *
score = 1
quiz_q = [
'how many turtle doves',
'how many French Hens',
'how many gold rings',
'how many Lords a leaping?'
]
quiz_a = [2,3,5,10]
for n in range(4):
question = input(print(quiz_q[n]))
if quiz_a[n] == question:
score += 1
else:
print("your score was ",score-1)
time.sleep(5)
quit()
which returns this:
how many turtle doves
None
I had a look around, but all the other qustion seemed to be refering about functions and the use of return vs print()
any help would be appreciated
As suggested in the comments, I'm reformatting my comment as an answer. I will attempt to elaborate on my explanation.
You are calling the print function, which outputs the text, then returns None. This may not be intuitive, but None is returned from any function that doesn't return anything else.
The None is then passed to the input function as a parameter, which transforms it into text, outputs that and then waits for input.
The "input()" call should only take a string as an argument, not a print function:
for n in range(4):
question = input(quiz_q[n])
# ...

Why does my return statement ignore the rest of my code in a function in python?

In my function, I type in a raw_input after my return statement and then I proceed to call my function. When I call my function the raw_input is totally ignored and only the return statement works.
def game():
#This selects 5 community cards from the pick_community function
community = pick_community(5)
card_4 = community[3]
card_5 = community[4]
first_3 = community[0:3]
return first_3
river = raw_input("If you are done with the round hit enter:" )
try:
if river =="":
return card_4
except:
print "Dont cheat man"
exit()
That:
return first_3
returns and therefore ends the function.
The remaining code is just ignored, because you will never get past the return.
Because a return statement gets out of the function, so the rest of the code wont execute
If you want to return first 3 values and then continue in code you can do it using yield. It basically inserts values into generator, then in the end return the whole generator.
https://pythontips.com/2013/09/29/the-python-yield-keyword-explained/
more here, or google for even more :)

Function breaks all code that come after it

I've started working on a small game. I've created a function that breaks all the code that follows it. Here's the full function:
def printBoard(currentBoard):
#Prints out the game board
for x in range(5):
#prints out 50 character line x
print (' '.join(str(currentBoard[x*50:(x+1)*50]))
although it still works with just this:
def printBoard(currentBoard):
print (' '.join(str(currentBoard[x*50:(x+1)*50]))
even things like:
print("Hello")
won't work after it. I've tried switching around variable names and such but the error the error still remains.
Looks like you are missing a closing ")"
Your indentation is wrong, change the function to this:
def printBoard(currentBoard):
#Prints out the game board
for x in range(5):
#prints out 50 character line x
print (' '.join(str(currentBoard[x*50:(x+1)*50]))

Function returns None unexpectedly

Ok. So I finished this piece of code I have been working on, but I have a major problem. I doesn't return correctly.
if is_word(wordlist, decodedText):
print 'entered if statement'
print answer
return answer
this is the piece of code that isn't working. The rest of the program isn't necessary. The line about entering the if statement was just a debug, so I would actually know that it did enter. The next print statement was to make sure that my variable answer actually was assigned to something, like it was elsewhere in the program.
Now, this is what the code is giving me:
entered if statement
[(0, -6), (3, -18), (12, -16)]
None
I also tried using type(answer) to make sure that I didn't have some weird bug I wasn't seeing, but it was just saying it was a list.
So, why am I getting a None return??
answer = []
def find_best_shifts_rec(wordlist, text, start):
"""
Given a scrambled string and a starting position from which
to decode, returns a shift key that will decode the text to
words in wordlist, or None if there is no such key.
Hint: You will find this function much easier to implement
if you use recursion.
wordlist: list of words
text: scambled text to try to find the words for
start: where to start looking at shifts
returns: list of tuples. each tuple is (position in text, amount of shift)
"""
global answer
for shift in range(27):
decodedText = apply_shift(text[start:], -shift)
if is_word(wordlist, decodedText):
print 'entered if statement'
print answer
return(answer)
split = decodedText.split()
if is_word(wordlist,split[0]) == True:
answer.append((start, -shift))
find_best_shifts_rec(wordlist, decodedText, (start+(len(split[0])+1)))
break
print find_best_shifts_rec(wordlist, "JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?", 0)
This is the rest of my function. Let me know if there is something else you need to see.
the problem was you were not returning your recursive result ....
if is_word(wordlist,split[0]) == True:
answer.append((start, -shift))
return find_best_shifts_rec(wordlist, decodedText, (start+(len(split[0])+1)))

Categories