I'm making an interpreter, and I have a function called parse(). The parse function returns some output.
I'm making a command that prints two command's outputs on the same line instead of on separate lines.
I have the following code:
def print_command2(command):
command = command.split("_") # The underscore separates the two commands
command[0] = command[0].strip("! ") # The command is !
print(parse(command[0])), # This should print the output of the first command
print(parse(command[1])) # And this should print the second
I typed in the following command to test it:
! p Hello_p World
(p is the equivalent of Python's print command.)
But it outputs the following:
Hello
World
I want it to print this:
HelloWorld
What's wrong?
EDIT: The answer from this question prints the following:
Hello
World
So it doesn't work as wanted.
EDIT: Here's the parse function. Please don't mind the terrible code.
def parse(command):
"""Parses the commands."""
if ';' in command:
commands = command.split(";")
for i in commands:
parse(i)
if '\n' in command:
commands = command.split('\n')
for i in commands:
parse(i)
elif command.startswith("q"):
quine(command)
elif command.startswith("p "):
print_command(command)
elif command.startswith("! "):
print_command2(command)
elif command.startswith("l "):
try:
loopAmount = re.sub("\D", "", command)
lst = command.split(loopAmount)
strCommand = lst[1]
strCommand = strCommand[1:]
loop(strCommand, loopAmount)
except IndexError as error:
print("Error: Can't put numbers in loop")
elif '+' in command:
print (add(command))
elif '-' in command:
print (subtract(command))
elif '*' in command:
print (multiply(command))
elif '/' in command:
print (divide(command))
elif '%' in command:
print (modulus(command))
elif '=' in command:
lst = command.split('=')
lst[0].replace(" ", "")
lst[1].replace(" ", "")
stackNum = ''.join(lst[1])
putOnStack(stackNum, lst[0])
elif command.startswith("run "):
command = command.replace(" ", "")
command = command.split("run")
run(command[1])
elif command.startswith('#'):
pass
elif command.startswith('? '):
stackNum = command[2]
text = input("input> ")
putOnStack(text, stackNum)
elif command.startswith('# '):
stackNum = command[2]
print(''.join(stack[int(stackNum)]))
elif command.startswith("."):
time.sleep(2)
else:
print("Invalid command")
return("")
TL;DR: I'm calling two functions. I want their output to print on the same line.
the print() function has extra arguments you can pass to it. You are interested in end.
def test1():
print('hello ', end='')
def test2():
print('there', end='')
test1()
test2()
>>>
hello there
>>>
It doesn't matter how many functions this comes from
Related
I have trouble understanding Python Scope. If you can help, I'll be thankful.
This is my code:
def msgCmd(x):
if x[0] == '/':
cmd = x[1:len(x)]
print(cmd)
def Cmd(x):
if x == "hello":
print("Hi how can I help you?")
elif x == "music":
print("Let's rock!")
while 1:
inp = input()
cmd = ''
msgCmd(inp)
Cmd(cmd)
I am essentially trying to type in a command using /command and get two results. One being only the command name following slash and the other being a result of what it did. Say, I enter /music. I am expecting 'music' as the first result and 'Let's rock!' as the next. But, somehow I am failing to retrieve the second desired result, possibly due to a Python Scope problem.
Also, please explain why this code works as it should when I add global cmd at the top of the function msgCmd(x) like this:
def msgCmd(x):
global cmd
if x[0] == '/':
cmd = x[1:len(x)]
print(cmd)
And, why doesn't it run as desired when global cmd added here outside function:
global cmd
def msgCmd(x):
if x[0] == '/':
cmd = x[1:len(x)]
print(cmd)
or here within the while loop:
while 1:
inp = input()
cmd = ''
msgCmd(inp)
global cmd
Cmd(cmd)
return the value of msgCmd first:
def msgCmd(x):
if x[0] == '/':
cmd = x[1:len(x)]
return cmd # right here
then get the value of that function so you can pass that value to another function:
...
cmd_str = msgCmd(inp)
Cmd(cmd_str)
I have written a python function which takes multiple arguments and i want it to run from terminal but it's not working. what am I doing wrong?
counting.py script:
def count (a, b):
word = False
a = " " + a + " "
b = " " + b + " "
result = 0
for i in range (len (a)-1):
if a[i] == " " and a[i+1] != " ":
word = True
result += 1
else:
word = False
for i in range (len (b)-1):
if b[i] == " " and b[i+1] != " ":
word = True
result += 1
else:
word = False
return result
if __name__ == "__main__":
count (a, b)
terminal command:
python counting.py count "hello world" "let's check you out"
useing sys model,
add this code, the sys.argv first parameter is this file name
import sys
if __name__ == "__main__":
a = sys.argv[1]
b = sys.argv[2]
count(a,b)
terminal command:
python counting.py "hello word" "let's check you out"
ex:
import sys
def count(s1, s2):
print s1 + s2
print sys.argv
count(sys.argv[1], sys.argv[2])
out:
python zzzzzzz.py "hello" "word"
['zzzzzzz.py', 'hello', 'word']
helloword
a and b are the arguments of count. You cannot use them outside that scope. You could instead use sys.argv to access the commandline arguments:
from sys import argv
if __name__ == "__main__":
print(count (argv[1], argv[2]))
As suggested by others using sys:
from sys import argv
def count(a, b):
return len(a.split(" ")) + len(b.split(" "))
if __name__ == "__main__":
a = argv[1]
b = argv[2]
word_count = count(a, b)
print(word_count)
Or, you could use the built-in module argparse. In case you ever have a more complex script taking arguments from the console.
import argparse
def count(a, b):
return len(a.split(" ")) + len(b.split(" "))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Word Count")
parser.add_argument("-a", type=str, help="First Sentence")
parser.add_argument("-b", type=str, help="Second Sentence")
args = parser.parse_args()
word_count = count(args.a, args.b)
print(word_count)
Execute your script with python counting.py -a "hello world" -b "let's check you out".
And if you execute python counting.py -h, you'll get a nicely formatted help for the users:
usage: counting.py [-h] [-a A] [-b B]
Word Count
optional arguments:
-h, --help show this help message and exit
-a A First Sentence
-b B Second Sentence
I have Python code like:
x = sys.argv[1]
y = sys.argv[2]
i = sofe_def(x,y)
if i == 0:
print "ERROR"
elif i == 1:
return str(some_var1)
else:
print "OOOps"
num = input("Chose beetwen {0} and {1}".format(some_var2, some_var3))
return str(num)
After I must execute this script in shell script and return string in shell variable, like:
VAR1="foo"
VAR2="bar"
RES=$(python test.py $VAR1 $VAR2)
Unfortunately it doesn't work. The way by stderr, stdout and stdin also doesn't work due to a lot of print and input() in code. So how I can resolve my issue? Thank you for answer
That isn't even valid Python code; you are using return outside of a function. You don't wan't return here, just a print statement.
x, y = sys.argv[1:3]
i = sofe_def(x,y)
if i == 0:
print >>sys.stderr, "ERROR"
elif i == 1:
print str(some_var1)
else:
print >>sys.stderr, "OOOps"
print >>sys.stderr, "Choose between {0} and {1}".format(some_var2, some_var3)
num = raw_input()
print num
(Note some other changes:
Write your error messages to standard error, to avoid them being captured as well.
Use raw_input, not input, in Python 2.
)
Then your shell
VAR1="foo"
VAR2="bar"
RES=$(python test.py "$VAR1" "$VAR2")
should work. Unless you have a good reason not to, always quote parameter expansions.
Just use print instead of return - you bash snippet expects result on STDOUT.
I have written an application in Python to work with strings, i made a menu prompt from which i can select an operation to do, i tested all the functions, they work well, except the menu and main functions, that when i enter my choice nothing happens. Here's the code:
import re
import os
def searchInFile(searched, file):
try:
f = open(file)
except IOError.strerror as e:
print("Couldn't open the file: ", e)
else:
sea = re.compile(searched, re.IGNORECASE)
for line in f:
if re.search(sea, line):
print(line, end='')
def validateWithPattern(string):
patt = re.compile('([a-z0-9-_.])+#([a-z]+.)([a-z]{2,3})', re.IGNORECASE)
if re.search(patt, string):
print("Valid")
else:
print("Not valid!")
def menu():
print("|================MENU=================|\n", end='')
print("|0- Exit the program |\n", end='')
print("|1- Validate mail address |\n", end='')
print("|2- Search a string in a file |\n", end='')
print("|=====================================|\n", end='')
b = input("->")
return b
def main():
b = 10
while b != 0:
b = menu()
if b == 1:
a = input('Enter you mail address: ')
validateWithPattern(a)
elif b == 2:
a = input('Enter the file name: ')
c = input('Enter the string: ')
searchInFile(c, a)
elif b == 0:
os.system("PAUSE")
else: print("Choice error")
if __name__ == "__main__":
main()
Your b variable you are returning from menu function is a string, not an integer, so you can't compare it with numbers (input is automatically saved as string). If you use return int(b) instead of return b, it will be ok.
Also, I think your else: print("Choice error") should be indented the same way your if and elif are, since you probably want to write "Choice error" only if b is not one of given choices. The way it is indented in your code will print "Choice error" after the while loop ends and it will not print that message if you input the value it can't recognize (for example 3).
import sys
import pickle
import string
def Menu():
print ("***********MENU************")
print ("0. Quit")
print ("1. Read text file")
print ("2. Display counts")
print ("3. Display statistics of word lengths")
print ("4. Print statistics to file")
def readFile():
while True:
fileName = input("Please enter a file name: ")
if (fileName.lower().endswith(".txt")):
break
else:
print("That was an incorrect file name. Please try again.")
continue
return fileName
THE_FILE = ""
myDictionary = 0
def showCounts(fileName):
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(fileName, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
print("Number count: " + str(numCount))
print("Comma count: " + str(commaCount))
print("Dot count: " + str(dotCount))
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
def showStats(fileName):
temp1 = []
temp2 = []
lengths = []
myWords = []
keys = []
values = []
count = 0
with open(fileName, 'r') as f:
for line in f:
words = line.split()
for word in words:
temp2.append(word)
temp1.append(len(word))
for x in temp1:
if x not in lengths:
lengths.append(x)
lengths.sort()
dictionaryStats = {}
for x in lengths:
dictionaryStats[x] = []
for x in lengths:
for word in temp2:
if len(word) == x:
dictionaryStats[x].append(word)
for key in dictionaryStats:
print("Key = " + str(key) + " Total number of words with " + str(key) + " characters = " + str(len(dictionaryStats[key])))
return dictionaryStats
def printStats(aDictionary):
aFile = open("statsWords.dat", 'w')
for key in aDictionary:
aFile.write(str(key) + " : " + str(aDictionary[key]) + "\n")
aFile.close()
choice = -1
while choice !=0:
Menu()
choice = (int(input("Please choose 1-4 to perform function. Press 0 to exit the program. Thank you. \n")))
if choice == 0:
print ("Exit program. Thank you.")
sys.exit
elif choice == 1:
THE_FILE = readFile()
elif choice == 2:
showCounts(THE_FILE)
elif choice == 3:
showStats(THE_FILE)
elif choice == 4:
printStats(myDictionary)
else:
print ("Error.")
I'm trying to open a file, have it display the statistics of the word lengths, and then have it make a new file with the statistics of the word lengths. I can read the file and have it display the statistics, but when I print the statistics to file I get an error - "int" object is not iterable. Any ideas? Thanks guys!
Error:
Traceback (most recent call last):
File "hw4_ThomasConnor.py", line 111, in <module>
printStats(myDictionary)
File "hw4_ThomasConnor.py", line 92, in printStats
for key in aDictionary:
TypeError: 'int' object is not iterable
The problem is that you set myDictionary to 0 at the top of your program, and then are sending it to your file writing function here printStats(myDictionary).
In this function you have this line for key in aDictionary, and since you passed in 0, this is effectively for key in 0 which is where the error comes from.
You need to send the result of the showStats function to your printStats function.
As this is looking like homework, I will leave it at that for now.
Sorry I am confused. in the showStats function I have to somehow say
"send results to printStats function" and then in the printStats
function I have to call the results? How would I do that exactly?
The printStats function is expecting a dictionary to print. This dictionary is generated by the showStats function (in fact, it returns this dictionary).
So you need to send the result of the showStats function to the printStats function.
To save the return value of a method, you can assign it on the LHS (left hand side) of the call expression, like this:
>>> def foo(bar):
... return bar*2
...
>>> def print_results(result):
... print('The result was: {}'.format(result))
...
>>> result = foo(2) # Save the returned value
Since result is just like any other name in Python, you can pass it to any other function:
>>> print_results(result)
The result was: 4
If we don't want to store the result of the function, and just want to send it to another function, then we can use this syntax:
>>> print_results(foo(2))
The result was: 4
You need to do something similar in your main loop where you execute the functions.
Since the dictionary you want to print is returned by the showStats function, you must call the showStats function first before calling the printStats function. This poses a problem if your user selects 4 before selecting 3 - make sure you find out a work around for this. A simple work around would be to prompt the user to calculate the stats by selecting 3 before selecting 4. Try to think of another way to get around this problem.
Here:
THE_FILE = ""
myDictionary = 0
you set integer to myDictionary.
and later you do:
printStats(myDictionary)
and as you try to interate over keys of dictionary inside, you fail.