I am trying to write a simple program in python to read command line arguments and print a final word based on the arguments. If there is any argument of the form "-f=" then the will go to the front of the final printed word. Similarly for "-e=" the text goes to the back and if there is -caps as an argument then the final printed word will all be uppercase. I do a while loop to scan through the arguments and check for these flags. The full code is:
import sys
i=1
while i<len(sys.argv):
frnt_wrd = None
lst_wrd = None
arg_1 = str(sys.argv[i])
if arg_1.startswith('-f='):
front = arg_1.split('=')
frnt_wrd = front[1]
elif arg_1.startswith('-e='):
last = arg_1.split('=')
lst_wrd = last[1]
if arg_1.startswith('-caps'):
caps = True
else:
word = arg_1
i+=1
print (front)
print (frnt_wrd)
I had a couple of if statements later on to print out the word based on whether frnt_wrd and lst_wrd were not equal to None (i.e. a value had been assigned to them) but nothing was printing out. To check the problem I did:
print (front)
print (frnt_wrd)
and the output actually gives me front as the desired array (when there is an argument of the form "-f=" but returns frnt_wrd as None even though I defined:
frnt_wrd = front[1]
When I type exactly this line outside of the while loop it actually works but why is it not defining the frnt_wrd inside the while loop?
Edit: The full code giving me frnt_wrd as None is above. What else do you need?
I would like to learn how to do it with while and without argparse. I need to understand why I am defining a variable and it is not defining.
Traceback:
enter image description here
The problem is that you reset frnt_word and lst_word to None each time through the loop, so you're overwriting the value that was set by a previous argument. You should just initialize them before the loop.
frnt_word = None
lst_word = None
caps = False
word = None
for arg in sys.argv[1:]:
optarr = arg.split("=")
if optarr[0] == "-f":
frnt_word = optarr[1]
elif optarr[0] == "-e":
lst_word = optarr[1]
elif optarr[0] == "-caps":
caps = True
else:
word = arg
Related
Newbie trying to learn some basic python, I've imported a json file containing a dictionary of terms. I'm trying to create a script that lets users look up definitions from my dictionary. I'm getting stuck on lines 14-15. I don't want the script to stop after just two attempts. I can work out how to set it to a max # of attempts but not how to make it infinite allowing unlimited tries. Each new query should be followed by a close match result using the get_close_matches method in difflib if the attempt is not an exact match, with the user prompted to accept or reject the closest match. My script, however, will stop after two attempts and if the 2nd query is not an exact match error out instead of presenting the 3 (the default for the method) closest matches to the word. Any ideas?
import json
from difflib import get_close_matches
data=json.load(open('data.json'))
def translate(w):
w=w.lower()
if w in data:
return data[w]
elif len(get_close_matches(w,data.keys()))>0:
yn=input("Did you mean %s? Enter Y or N: " % get_close_matches(w,data.keys())[0]).upper()
while yn =="N":
i=input("Enter Word: ")
return data[get_close_matches(i,data.keys())]
else:
return data[get_close_matches(w,data.keys())[0]]
word=input("Enter Word: ")
print(translate(word))
Your current approach isn't working because of the return statement inside the while yn == "N" loop. That return immediately takes you out of the function, regardless of whether the loop has completed, so there's no way for this loop to run more than once.
You could edit the loop to prevent it from always returning, but it's easier to move the loop outside the function. That way you don't have to worry about whether you're working with the initial input or a subsequent input, and you can cut down on duplicate code:
def translate():
w = input("Enter Word: ").lower()
if w in data:
return data[w]
close_matches = get_close_matches(w, data.keys()) # This only runs if w was NOT in data
if len(close_matches) > 0:
yn = input("Did you mean %s? Enter Y or N: " % close_matches[0]).upper()
if yn == 'Y':
return data[close_matches[0]]
return None # This is optional. Reaching the end of a function will return None by default
translated_word = None # Force at least one iteration of the loop
while translated_word is None: # Keep going until there's a match or the user types "Y"
translated_word = translate()
print(translated_word) # This will only run once the loop condition is False
I have the script below, what I am finding that if my Try statement is satisfied, the whole iteration of the first loop will end and it will just go into the next loop iteration.
What I want to happen is it the, if statement, is satisfied, it then just back to the elif within the for loop that it sits within.
So essentially I want to go
For loop.
Then try if something works (I know some wont)
Then go back into a for loop (and all the subsequent loops will still work.
Ideally I would structure this as: for loop- try statement- for loop, but essentially I am asking the same question as when that happens to, the loop also breaks out.
Thaankyou, Sam
# LOOP OVER THE DICTIONARIES (CSV LINE DATA) AND PULL UP THE PARAMETER KEY TO MATCH
tester = []
updatefamilyname = IN[6]
typename_input01_value = IN[7]
typename_input02_value = IN[8]
for datarow_dict in Data_DictionaryList:
# Get matching value from data row dictionary
Matching_Value = str(datarow_dict[parameter_key_tomatch])
#test.append(parameter_key_tomatch)
#test.append(Matching_Value)
try:
Get_Matching_Value_LongIndex = Base_MatchingWalls_Dict[Matching_Value]
Split_Index = Get_Matching_Value_LongIndex.split(indexplacesplit)[1]
MatchedWall = Base_MatchingWalls[int(Split_Index)]
#test.append(MatchedWall)
#test.append("here2")
for para_key, para_value in datarow_dict.items():
#ResultOutput.append(para_key)
#ResultOutput.append(typename_input01_value)
#test.append(para_key)
#test.append(para_value)
# We then say if the paramter key is the same as the matching key, open the following
if para_key == parameter_key_tomatch:
#test.append("inside")
ResultOutput.append(para_key + " equal to " + para_value)
# Set New Family Type Name Value
#if para_key == typename_input01_key:
#typename_input01_value = para_value
#tester.append("inside link")
#elif para_key == typename_input02_key:
#typename_input02_value = para_value
#else:
#print ("go")
elif para_key != parameter_key_tomatch:
ResultOutput.append(para_key)
print ("not here")
#ResultOutput.append(para_key)
#TestParameter_ = testparavalue(MatchedWall, para_key, para_value)
#else:
#pass
# We then say, if its not the same, this is when we want to do some things, could be where we change the family name if we change the name of the name and number
else:
print ("ouside exception")
#ResultOutput.append("else why")
if updatefamilyname == "Yes":
ResultOutput.append("update name accepted")
print ("yes")
# THIS IS WHERE WE COULD PASS IN THE OTHER ONE TO MATCH TO FORM THE CHANGE IN FAMILY TYPE NAME
#typename_input01_value
#typename_input01_value
# This is where we bring in
# Anything where matching para does not have a corresponding wall type
except:
print ("here")
ResultOutput.append(Matching_Value)
I'm writing some code in Python that calculates the area of a triangle or a circle, depending on the user's choice. I want to write "if the user's choice is a C (for circle), continue running", but everything I write doesn't work and it shows an error.
I have:
option = raw_input('Enter C for Circle and T for Triangle: ')
circle = 'C'
tringle = 'T'
if option == circle:
return option
As noted in the comments, you cannot return a value unless it is from a function.
If you want to accomplish a running example you can easily use a while loop like so:
circle = 'C'
tringle = 'T'
value = True
while value:
option = raw_input('Enter C for Circle and T for Triangle: ')
# check lower() so capitalization doesn't matter
if option.lower() == circle:
# do something
print("Do something, 'C' has been selected")
pass
else:
value = False
As an explanation, if you are unclear on what is happening above. The while loop is always True if the selected option is circle, thus the loop never terminates and the iteration continues. If the selected option is not circle, the value of value will not be True, so the loop breaks before the code in the loop is executed again.
You're getting a SyntaxError because you are calling return despite not having any function defined. According to Python syntax, you can only return from inside of a function. I'd recommend reading up on how to create Python functions (this article does a good job of explaining it)
I'm trying to run an if-then true-false statement. How, I continuously receive errors when attempting to do so.
This is what I have so far.
from urllib.request import urlopen
dna2rna = {'A':'U', 'T':'A', 'C':'G', 'G':'C'}
def dna2rna(seq):
return ''
codon2aa = {"AAA":"K", "AAC":"N", "AAG":"K", "AAU":"N",
"ACA":"T", "ACC":"T", "ACG":"T", "ACU":"T",
"AGA":"R", "AGC":"S", "AGG":"R", "AGU":"S",
"AUA":"I", "AUC":"I", "AUG":"M", "AUU":"I",
"CAA":"Q", "CAC":"H", "CAG":"Q", "CAU":"H",
"CCA":"P", "CCC":"P", "CCG":"P", "CCU":"P",
"CGA":"R", "CGC":"R", "CGG":"R", "CGU":"R",
"CUA":"L", "CUC":"L", "CUG":"L", "CUU":"L",
"GAA":"E", "GAC":"D", "GAG":"E", "GAU":"D",
"GCA":"A", "GCC":"A", "GCG":"A", "GCU":"A",
"GGA":"G", "GGC":"G", "GGG":"G", "GGU":"G",
"GUA":"V", "GUC":"V", "GUG":"V", "GUU":"V",
"UAA":"_", "UAC":"Y", "UAG":"_", "UAU":"T",
"UCA":"S", "UCC":"S", "UCG":"S", "UCU":"S",
"UGA":"_", "UGC":"C", "UGG":"W", "UGU":"C",
"UUA":"L", "UUC":"F", "UUG":"L", "UUU":"F"}
rna = ('AUG').upper()
amino = ''
while rna:
amino += codon2aa[rna[:3]]
rna = rna[3:]
print(amino)
if __name__ == '__main__':
with urlopen('http://web.njit.edu/~kapleau/teach/current/bnfo135/sequence.gb') as conn:
data = conn.readlines()
lines = [line.strip() for line in [datum.decode() for datum in data]]
flag = False
dna = ''
for line in lines:
if ORIGIN in line:
then True
if True:
ORIGIN == dna
Its hard to tell exactly how to fix this without knowing more about what your code is meant to do, but you seem to have a fundamental misunderstanding of how the syntax works.
if ORIGIN in line:
then True
if True:
ORIGIN == dna
What you probably mean here is something like this:
if ORIGIN in line:
dna = ORIGIN
Basically, there's no need for the then True - everything in the indented block is run if and only if the condition succeeds. This also means that, aside from thrn True being a syntax error, a block starting with if True: will always run (except in one edge case that Python 2.x lets you trigger, but Python 3 has fixed).
Its also important to understand the difference between a = b and a == b. The first one is an assignment statement, which says 'from now on, the variable a refers to the same object that the variable b currently refers to' - it changes something in your program. On the other hand, a == b asks the question "are these two things equal?" - and so it is usually next to an if, like if a == b:.
I´m experiencing problems with my code.
I can´t get it to append to the list not_found as well as it loops twice for some reason.
Can anyone point me in the right direction? The match works for my_track, but it doesn't when it doesn't match.
# coding: utf-8
#!/usr/bin/env python
import spotimeta
import sys
import time
my_tracks = raw_input("Please enter a sentence: ").title().split()
playlist = []
real_playlist = []
not_found = []
def check_track(track_name, my_track, track_href):
if track_name == my_track:
playlist.append(track_href)
return 1
# make sure the user does not input a single word as input
if (len(my_tracks) > 1):
path = my_tracks[1]
else:
sys.exit("Invalid input, please enter a sentence.")
# let's search
for my_track in my_tracks:
match = 0
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if not match == 1:
try:
match = check_track(result["name"],my_track,result["href"])
except Exception, e:
error = "not available"
else:
if data['total_results'] > 0:
not_found.append(my_track)
You should try debugging it. One of the simplest ways of debugging is add the lines:
import pdb
pdb.set_trace()
Then when you run the script it will stop at the set_trace line in the debugger.
Check out http://docs.python.org/library/pdb.html for more information.
From my understanding you're trying to do something like:
for my_track in my_tracks:
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if result['name'] == my_track:
playlist.append(result['href'])
elif data['total_results'] > 0:
not_found.append(my_track)
Will this more or less work for you?
Please help me to understand.
Right off the bat, I'm noticing two things.
First, you're checking data['total_results'] a bit late; if the total results value is greater than zero (wait, what?), then you want to add it to the list immediately and move on without parsing the data. I would, after the call from spotimeta.search_track(), check to see if this is the data you don't want (then subsequently add it into the list).
Second, I'm confused about the intention of your for loop. If you're going through it to only find one item, then you can use the in statement (my_track in result).