This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 6 years ago.
Just a little project i'm working on to improve my knowledge.
Curious as to why the program always returns failure, even if the captcha is correctly entered. I assume it has something to do with the results not being stored in memory?
import string
import random
def captcha_gen(size=7, chars=string.ascii_letters + string.digits):
return ''.join(random.SystemRandom().choice(chars) for _ in range(size))
results = print(captcha_gen())
user_input = input("Please enter the captcha code as you see it: ")
if user_input == results:
print("success")
elif user_input != results:
print("failure")
else:
print("error")
Thanks!
results = print(captcha_gen())
print() returns None - it is used to print stuff to the screen. In this case, it is grabbing the output of captcha_gen() and printing it to the screen.
All functions in Python return something - if they don't specify what they return, then it is an implicit None
You want
results = captcha_gen()
Related
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 11 months ago.
I'm new to python programming, and as a beginner I want to start by using a code editor,
I choose sublime text 4 but I face this problem,
So help me please !
This is the code :
def return_string(your_string):
if len(your_string) >= 4:
new_string = your_string[0:2] + your_string[-2:]
return new_string
elif len(your_string) == 2:
new_string = your_string * 2
return new_string
elif len(your_string) < 2:
new_string = ""
return new_string
return_string("welcome")**
the expected output is "weme" but I get nothing in sublime text output (when I click Ctrl + B).
When I change return to print the code is executed properly.
By the way the code above works in vscode without any problem.
Python doesn't print outside the REPL normally, unless you explicitly tell it to. Add a call to print on your last line:
print(return_string('welcome'))
This is why adding an explicit print in your function works.
You can store the value into a variable first if you want to use it elsewhere:
result = return_string('welcome')
print(result)
Because "return string" returns a string, you must first save the data in a variable, which you may then use later in the program.
result_string = return_string("welcome")
print(result_string)
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
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I've done this before but i think this error is showing up because I'm not looping the code, the code works only once then on the second attempt is shows an error.
My Code:
import string
import time
def timer(x):
for n in range(x,0,-1):
time.sleep(1)
print(n)
print("Times Up"+"\n")
ask("Time for: ")
def ask(a):
x=int(input(str(a)))
print("\n"+"Clock's Ticking")
timer(x)
try:
ask("Time for: ")
except ValueError:
ask("Enter a number to time: ")
I want my code to not error when i put in something that isnt a integer for the time but dont know how to loop the exception code until the user enters a integer.
Move the exception handling to ask function:
import string
import time
def timer(x):
for n in range(x,0,-1):
time.sleep(1)
print(n)
print("Times Up"+"\n")
ask("Time for: ")
def ask(a):
x = None
while x is None:
try:
x=int(input(str(a)))
except ValueError:
print('Enter a number to time!')
timer(x)
ask("Time for: ")
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'm learning Python and can't work out why the following doesn't work.
Can anyone advise? code below
thanks
# Make sure that the_flying_circus() returns True
print "What is your number?"
num = input()
print "What is bla?"
bla = input()
def the_flying_circus():
if num ==4 and bla=="bla": # Start coding here!
return True
print "Well done!"
# Don't forget to indent
# the code inside this block!
elif num == 2 or bla== zog:
print "OK"
# Keep going here.
# You'll want to add the else statement, too!
else:
print "Bad luck!"
the_flying_circus()
The return True is probably not what you want to have on the top of the if block. Try removing it.
The only condition that will return True is num==4 and bla=='bla'. Otherwise, the return value is None. However, 'Well done!' will never be printed since the return statement occurs first.
Couple of things...
1) return True should be moved to the end of the function (as mentioned by others)
2) watch how you collect input... use raw_input for your string, use input for the number.
This works for me:
def the_flying_circus():
if a==4 and b=='bla':
print "Well done!"
elif a==2 or b=="zog":
print "OK"
else:
print "Bad luck!"
return 1
a = input("What is your number? ")
b = raw_input("What is bla? ")
the_flying_circus()
This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Why am I getting "IndentationError: expected an indented block"? [duplicate]
(6 answers)
Closed 25 days ago.
for the following code:
if __name__ == '__main__':
min_version = (2,5)
current_version = sys.version_info
if (current_version[0] > min_version[0] or
current_version[0] == min_version[0] and
current_version[1] >= min_version[1]):
else:
print "Your python interpreter is too old. Please consider upgrading."
config = ConfigParser.ConfigParser()
config.read('.hg/settings.ini')
user = config.get('user','name')
password = config.get('user','password')
resource_name = config.get('resource','name')
server_url = config.get('jira','server')
main()
i get error:
else:
^
IndentationError: expected an indented block
You don't have anything in the if side of your if statement. Your code skips directly to the else, while python was expecting a block (an "indented block", to be precise, which is what it is telling you)
At the very least, you need a block with just a 'pass' statement, like this:
if condition:
pass
else:
# do a lot of stuff here
In that case, though, if you really don't ever want to do anything in the if side, then it would be clearer to do this:
if not condition:
# do all of your stuff here
The if must contain one or more statements, e.g.:
if (current_version[0] > min_version[0] or
current_version[0] == min_version[0] and
current_version[1] >= min_version[1]):
pass # <-------------------------------------ADDED
else:
# ...
The pass statement is a placeholder statement that does nothing.