This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 2 years ago.
I'm basically trying to create something of an mad libs generator. When it runs through all the random variables, and I try to get it to save as a variable, and then print that variable I get "none"
I'm a novice so I apologize if this is painfully dumb. Link to colab notebook where you can see it: https://colab.research.google.com/drive/1Eh0-ACUJOduxjRbsql7ut_VgZEE4PBWW?usp=sharing
This is the code
import random
#Word Buckets
list = ("Todd", "Jill","Mary")
secondlist = ("hot","cold","run" )
thirdlist = ('pizza','pasta',"wine" )
#Create Define random choices
def def1 ():
d=random.choice(list)
a=random.choice(secondlist)
r=random.choice(thirdlist)
c=random.choice(list)
print(d,a, (r+"'s"),c)
def def2 ():
d=random.choice(list)
a=random.choice(secondlist)
f=random.choice(thirdlist)
fv=random.choice(thirdlist)
print(fv, "Because of",(d+"'s"),f)
titletype = (def1, def2)
#random.choice(titletype)()
message=random.choice(titletype)()
print(message)
And that will return
None
def2 and def1 should return instead of print
Related
This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 2 years ago.
I'm making a basic editing software.
A simplified version of parts of the code are below (and they still produce the same result as with the actual program):
File named mod.py:
from mod2 import toptext
cmdtext = "Edit video: tt=test,"
presentCommands = ['tt=']
def initCommands(presentCommands, cmdtext):
vidfilter = []
if 'tt=' in presentCommands and 'bt=' not in presentCommands:
vidfilter = toptext(cmdtext, vidfilter)
print("Top text vidfilter is", vidfilter)
else:
print('no')
initCommands(presentCommands, cmdtext)
File named mod2.py:
import re
def toptext(cmdtext, vidfilter):
vidfilter = vidfilter
texts = (re.findall(r'tt=(.*?),', cmdtext))
text = texts[0]
print(text)
vidfilter = vidfilter.append("subtitles=/example/file/path/toptext.srt:force_style='Fontname=Impact,Fontsize=30,Alignment=6'")
print("The vidfilter is:", vidfilter)
return vidfilter
The output of running mod.py is this:
test
The vidfilter is: None
Top text vidfilter is None
As you can see, vidfilter is printed as None, when I want it to be ["subtitles=/example/file/path/toptext.srt:force_style='Fontname=Impact,Fontsize=30,Alignment=6'"] instead. Is append() not working or something?
Can anyone please help me fix this and let me know why it's happening? Please note I'd like to keep mod.py and mod2.py as separate files.
list.append() works in place (and thus return None). You assign it back to vidfilter on this line:
vidfilter = vidfilter.append("subtitles=/example/file/path/toptext.srt:force_style='Fontname=Impact,Fontsize=30,Alignment=6'")
Also note that I am not sure what you think this like is doing:
vidfilter = vidfilter
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()
This question already has answers here:
Reverse / invert a dictionary mapping
(32 answers)
Closed 6 years ago.
I have made my own Morse Code translator where you can enter the code and the corresponding letter prints out. However, what I want to do is that whenever I enter a letter, the code prints out. Here's my code:
MorseCode = {'.-':'A',
'-...':'B',
'-.-.':'C',
'-..':'D',
'.':'E',
'..-.':'F',
'--.':'G',
'....':'H',
'..':'I',
'.---':'J',
'-.-':'K',
'.-..':'L',
'--':'M',
'-.':'N',
'---':'O',
'.--.':'P',
'--.-':'Q',
'.-.':'R',
'...':'S',
'-':'T',
'..-':'U',
'...-':'V',
'.--':'W',
'-..-':'X',
'-.--':'Y',
'--..':'Z',
'.----':1,
'..---':2,
'...--':3,
'....-':4,
'.....':5,
'-....':6,
'--...':7,
'---..':8,
'----.':9,
'-----':0
}
print "Type 'help' for the morse code."
print "Type 'end' to exit the program.\n"
while True:
code = raw_input("Enter code:")
if code in MorseCode:
print MorseCode[code]
So the question is: Is there a way to somehow invert this dictionary so whenever I enter 'A', '.-' will print out? I'm only studying python for two weeks now so I'm still mastering the basics before I move on to the more advanced levels. Thank you!
You can use dictionary comprehension (assuming you are using Python 2.6+) to easily create a new, inverted dictionary:
letters_to_morse = {char: code for code, char in MorseCode.items()}
letters_to_morse['A']
>> '.-'
This question already has answers here:
How to overwrite the previous print to stdout?
(18 answers)
Closed last month.
I have a loop:
for i in range(10):
print i
and it print :
1
2
...
8
9
OK
but I'm searching to make a unique line which actualize for each iteration like this :
for i in range(10):
magic_print "this is the iteration " + i + " /10"
with a result like:
"this is the iteration <i> /10"
<i> changing dynamically
Thanks !
As I understand your question, you would like to overwrite previous prints and count up. See this answer: https://stackoverflow.com/a/5419488/4362607
I edited the answer according to PM 2Ring's suggestions. Thanks!
import sys
import time
def counter():
for x in range(10):
print '{0}\r'.format(x),
sys.stdout.flush()
time.sleep(1)
print
counter()
the solution is the format function from the str object
for i in range(10):
print "this is the iteration {} /10".format(i)
This question already has answers here:
Length of generator output [duplicate]
(9 answers)
How to look ahead one element (peek) in a Python generator?
(18 answers)
How to print a generator expression?
(8 answers)
Closed 8 years ago.
Yesterday I have been implementing a small Python scripts that checks difference between two files (using difflib), printing the result if there is any, exiting with code 0 otherwise.
The precise method, difflib.unified_diff() is returning a generator on the diffs found. How can I test this generator to see if it needs to be printed? I tried using len(), sum() to see what was the size of this generator but then it is impossible to print it.
Sorry to ask such a silly question but I really don't see what is the good practice on that topic.
So far this is what I am doing
import difflib
import sys
fromlines = open("A.csv").readlines()
tolines = open("B.csv").readlines()
diff = difflib.unified_diff(fromlines, tolines, n=0)
if (len(list(diff))):
print("Differences found!")
# Recomputing the generator again: how stupid is that!
diff = difflib.unified_diff(fromlines, tolines, n=0)
sys.stdout.writelines(diff)
else:
print("OK!")
You're already converting your generator to a list, so you don't need to rebuild it.
diff = list(difflib.unified_diff(fromlines, tolines, n=0))
if diff:
...
sys.stdout.writelines(diff)
else:
...
You don't even need to convert the generator to a list if you don't want by using a simple flag:
diff = difflib.unified_diff(fromlines, tolines, n=0)
f = False
for line in diff:
if not f:
print("Differences found!")
f = True
sys.stdout.write(line)
if not f:
print("OK!")
You could convert the generator into a list.
diff = list(difflib.unified_diff(fromlines, tolines, n=0))
I think you can't, and the proper way is probably to generate all data until you raise StopIteration and then get the length of what you have generated.
What's wrong with :
import difflib
import sys
fromlines = open("A.csv").readlines()
tolines = open("B.csv").readlines()
diff = difflib.unified_diff(fromlines, tolines, n=0)
difflines = list(diff)
if len(difflines) :
sys.stdout.writelines(difflines)
else:
print("OK!")