It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So I'm making a video player that automatically chooses the next video based on some weighted probabilities. When a video comes in, it reads all its metatags from a csv, then looks up the next match after the probability rolls. I had all the various metatag checks programmed in-line with if statements and for loops, but the client has just asked to have on and off switches for each of the filters and I'm having trouble wrapping my head around the most efficient way of approaching the problem.
I'm still fairly green with Python, so I figured I'd ask before trying to do something the worst way possible. I'm wondering (if there isn't a way to do this that I just don't know of yet) if it would be better to have the on and off switches interrupt and change the variables before they get to this point, so that for example when the on switch is on, a list of every possible color would be assigned to the variable color, so that it always passes and no videos get rejected from the color, thus keeping the same basic formatting.
Below is a simplified version of what I kind of have going on, for readabilities sake. Before it, the program gets all the variables it needs from the csv, and after the final print, the ones that pass get added to a list of good choices which is randomly pulled from:
for eachrow in table:
Answer = False
for eachcell in eachrow:
if color == req_color:
if speed == req_speed:
if exclusion == req_exclusion:
print ('No pass!')
else:
Answer = True
print ('All attributes match')
if Answer:
print ('This passes')
Cheers!
perhaps you are looking for continue ?
The continue statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop.
http://docs.python.org/reference/simple_stmts.html#continue
It sounds like you want to use continue. Continue is sort of like break, except where break terminates the loop, continue just skips the rest of the current run of the loop and starts the next.
I can't really tell what you are trying to do, but you could try something like this:
testsToRun = ['speed','color']
for row in table:
Answer = False
for cell in row:
if cell['color'] == color and 'color' in testsToRun:
print ('No pass!')
continue
if cell['speed'] == speed and 'speed' in testsToRun:
print ('No pass!')
continue
if cell['exclusion'] == exclusion and 'exclusion' in testsToRun:
print ('No pass!')
continue
Answer=True
print ('All attributes match')
if Answer:
print ('This passes')
Thanks for the advice, everyone. I solved the issue by actually going back to where the variables are defined. I set it so that when its off, it sends all the possible variables to the if, so that it always passes if its off. That way when the switch is on and it takes the user input, it selectively passes things through. I thought about other options but since this prototype has to have a quick turn around time, this seemed like the best bet.
Thanks again!
Related
so i have this mission to build a python cashier program using only python. without db use.
i use the dict and keys method to build it.
so i have 2 questions:
can i get an idea how to keep the program running after the moneybalance part, while i'm still saving the current moneybalance status? like, to make it an continuous program and not just one time.
i would like to get overall review on how is the idea for this mission, how it's written, and etc. would you do it in other way? if so i would like to hear how.
remember, my mission is to build python cashier without any outside libraries\db's.
Code:
print('welcome to python cashier')
money = int(input('enter cashier current money\n'))
prices = {"small popcorn" : 3, "medium popcorn" : 5,
"large popcorn" : 8, "small drink" : 1,
"medium drink" : 2, "large drink" : 3 }
def calc(money, prices):
try:
itemchange = pay - itemvalue
except Exception as e:
print(e)
finally:
print(f'change: {itemchange}')
def show(money, prices):
try:
for key,value in prices.items():
print (f'{key}: {value}')
except Exception as e:
print(e)
finally:
return False
show(money, prices)
def start(money, prices):
try:
for key, value in prices.items():
global item
item = str(input('enter what you want to buy:\n'))
if (item in prices.keys()):
global itemvalue
itemvalue = prices.get(item)
print(f'{item}: {itemvalue}')
global pay
pay = float(input('how much costumer pay?\n'))
return calc(money, prices)
else:
print('item not found')
except Exception as e:
print(e)
finally:
moneybalance = money + itemvalue
print(f'moneybalance: {moneybalance}')
start(money, prices)
The real question is if someone asked you to save the information. As you said they asked in the mission to do this without a database I don't think you need to do that. Btw if it's without an actual database you can use just .txt files to save information. Check about the "open" function in Python.
Quick Example:
with open('save.txt', 'w') as file:
file.write(str(cash)) # cash is an integer.
It's an example of writing a file. Btw I don't think they wanted you to save the information. Check it before you're applying something to don't ruin your work :).
I would suggest to put all the declarations of variables at the start of the script and add a "main" function. Call the main function from name == 'main'. Too I recommend you to do a more detailed function names. Try not to use global variables in this small code (you can declare it at the start, it'll be global and more easy to read your code and understand it faster). I think in your first question you thought about making your program run more than one time in any program run? Read about Python Loops if I'm correct :). Too you wrapped your input return with str() and it useless, because the returned value from input is already str (String type).
Quick Example:
# Variables Declaration (Just an example for the structure).
ABC = 0
cash = 1000
# Functions Declaration
def calculate_price(money, prices):
# Code Here.
pass
def main():
# The code of your start function, you don't need and arguments for this.
pass
if __name__ == '__main__':
main() # Call main here.
In this way your code will be readable and comfort to analyze :).
This sounds more like an assignment than an actual problem.
Here is the thing, and this is fundamental software architecture. You only need a database when it is time to persist something. So, what you need os a persistence service. Call it a database if you want, it can be as simple as a text file, as someone sugested.
Ironically the same set of rules that made your life easier as a developer, are making you confused. And questions arise. Specifically the question of what exactly happens when I close the program?
But the answer is dead simple. The requirements made it simple. If you close the application its gone. There is no persistence mechanism. This is actually super safe. No record, no proof. More importantly, its a requirement to be like so.
The problem, therefore, is you. You feel the need for persistence. You see an account and immediately place it in a database somewhere. You do a transaction, you feel the need to store it.
So what exactly happens when you persist something in a program? The program keeps all the information it needs to run. It may have gotten that information from a database, a user, or it may have randomly generated it. Who cares? All the program needs is the information in objects it knows how to use, in classes types and whatever more; in other words, in RAM. So persistence is taking things out of RAM into a less volatile storage.
But the real question is, how exactly does that affect the program? Does that cause any fundamental change?
For one the cashier operations are still the same. Prices must still be calculated, transactions must still be made, and all the rules associated must still be observed.
If something, there is less code involved. There is no solving the persistence problem. The information is volatile. Its a requirement to be so.
This is fundamentally the evolution process of a system under development, or even to some extent in production.
During development I care very little to store anything. What is actually usefull is to have reproucible state of the data. One I can interact with to make tests and verify that the software works (ie. it does not let me buy something if I have no money). This is easier done without any database system, specially the repoducible part.
Sure I can do backups of the data, but is it not easier to just restart the app? And where is the bug exactly if I need a specific database to see it? Is it in the code? Or is it a consistency issue in the database system? Probably the latter. How does that affect the cashier? It doesn't. Its a persistence detail. It has nothing to do with the business of a cashier.
I feel I have way more I could say, but I'm not sure where exactly you expect to get with this question. So I will stop here. Feel free to further inquire on this matter.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
Question1 = input("We will start off simple, what is your name?")
if len(Question1) > 0 and Question1.isalpha(): #checks if the user input contains characters and is in the alphabet, not numbers.
Question2 = input("Ah! Lovely name, %s. Not surprised you get all the women, or is it men?" % Question1)
if Question2.lower() in m: #checks if the user input is in the variable m
print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2))
elif Question2.lower() in w: # checks if the user input is in the variable w
print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2))
else: #if neither of the statements are true (incorrect answer)
print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!")
else:
print ("Come on, enter your accurate information before proceeding! Restart me!") #if the first question is entered wrong (not a name)
Question3 = input("Now I know your name and what gender attracts you. One more question and I will know everything about you... Shall we continue?")
In order to get the right answer, I will first tell you what happens when I run it:
There are several scenarios but I will walk you through 2. When I run the program I am first asked what my name is, I can enter anything here that is alphabetic, then it asks me if I like men or woman, weird I know but it's a project I am working on, if I were to say 'men' or 'women' the program runs perfectly, but if I were to enter say... 'dogs' it would follow the else statement print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!") but then it continues the code and goes to the last line shown above "Now I know your name and what gender attract you...... blah blah". What I am trying to do is have it restart the script if you were to enter anything other than 'men' or 'women'.
I was told that a while statement would work, but I would need an explanation as to why and how... I'm new to Python in a sense.
That's what loops are for.
while True:
# your input and all that here
if answer == "man" or answer == "woman":
# do what you want if the answer is correct
break # this is important, as it breaks the infinite `while True` loop
else:
# do whatever you want to do here :)
continue
If you want the script to repeat indefinitely, you can simply wrap everything in a while loop like so:
while True:
# Do yo your logic here.
# Break out when a condition is met.
If you want to be more savvy with it you can use a method and have the method call itself over and over until it's done.
def ask_questions():
# Do your logic here
if INPUT_NOT_VALID:
ask_questions()
else:
# Continue on.
Also, search on this site for you text because I've seen about five or six questions all involving this programming scenario which means it has to be a common problem from a programming class (one I'm assuming you are in). If that's the case discuss with classmates and try to stimulate each other to find the solution instead of just posting online for an answer.
I have a piece of coding that is most basically a quiz. I had error handling so that if someone pressed a letter or anything other than a number, it would carry on with the quiz instead of letting the person attempt another question. (For example, if question 5 was 2+3 and they entered t, then it would carry on and not give them a different question for question 5).
I tried to update the coding, so it would loop:
def random_question():#defines function to get random question
count = 0#equates count to 0
for number in range (0,10):#makes the code generate the question 10 times
try:#the code makes it so the computer tries one thing and is the beggining
questionList = [random_sum,random_subtraction,random_times]#puts functions in a list to be called on
randomQuestion = random.choice(questionList)#calls on the list to generate the random questions
randomQuestion()#calls on variable
except ValueError:#if there is a value error or a type error it will notice it and try to stop it
print ("Please enter a number")#prints out the statement if there is a type error or a value error
else:
break
random_question()#calls on the function random_question
However, it comes up with a syntax error, and highlights the 'except' part next to the ValueError.
Any help as to why this is would be much appreciated.
Your except statement should have the same indention as your try statement. In your sample code it is indented an extra tab which would cause that error.
Python takes indention seriously and it is often the culprit. I'm unclear if your def line is a place holder or if this code is part of it, but if this code is part of the function definition you have other indention issues to worry about.
I'd suggest going through it carefully and making sure everything is lined up properly. The basic rule of thumb is, if something is part of something else, it is indented under it.
def something():
step 1
step 2
if (condition):
the true thing
else:
the false thing
while (something):
repeat something
this is not part of the function anymore
1.I'm using break to break out of a loop, but I don't know how to make the program keep going no matter what unless this happens. Just typing in while: is invalid (or so the progam tells me) and I want the game to keep going even if the user types in an emptry string.
2.Is there a way to not have to re-type a bit of code every time I need it? I have a bunch of responses for the program to spit out that I'll have to use many times:
if action[0]=='go':
print("You're supposed to go to David!")
elif action[0]=='look':
print("You can't see that")
elif action[0]=='take':
print("You don't see the point in taking that.")
else:
print("I don't recognise that command")
Where action is a list from the player's input. Or do I just have to type it out again each time?
I don't know how to define a function that does the above, and I'm not even sure that's what I'm supposed to do.
3.Some story descriptions I'm using are a very long stings and I don’t want players to have to scroll sideways too much. But I want to just define them as variables to save myself some typing. Is there a way around this. Or do I just have to type it out every time with
print(“““a string here”””)
4.If the string starts with 'look' and has 'floor' or 'mess' or 'rubbish' in it, I want it to print a certain output. This is what I currently have:
if action[0]=='look':
if 'floor' in action or 'rubbish' in action or 'trash' or 'mess' in action:
print('onec')
elif 'screen' in action or 'computer' in action or 'monitor' in action:
print('oned')
elif 'around' in action or 'room' in action or 'apartment' in action:
print('onee')
elif 'david' in action or 'tyler' in action or 'boy' in action or 'brat' in action or 'youth' in action:
print('onef')
break
else:
print("You can't see that")
It prints 'onec' for any input beginning with 'look'.
The while statement requires a condition.
You can call the same instructions over and over using a function.
"String literals can span multiple lines in several ways"
Use strategically-placed print statements to show the value of action, e.g. after if action[0]=='look'
Lastly, please don't add any more items to this question. Rather ask a new question. This site has somewhat specific rules on that sort of thing.
To make an infinite While loop, use while True:.
You could use a dict to store common action strings and their responses.
Just register the string first, then when the input come, change it:
command = "nothing"
command = input("Enter command: ")
while command:
Or just simply:
while True:
Yes, think about it by yourself.. Okay, why not put it in list responses?
If it is really long, put it in a file. Read it when you need it using open(). More on File Processing
This will help you shorten your code, making it easier to read, and makes it more efficient.
while requires a condition that it has to evaluate. If you want it to loop forever, just give it a condition that always evaluates to True, such as 4>3. It would be best for everyone if you just used while True:, which is the clearest option.
For this specific case, I would recommend using a dict() and its .get() method. Something like this:
action_dict = {'go':"You're supposed to go to David!",
'look':"You can't see that",
'take':"You don't see the point in taking that."
}
print(action_dict.get(action[0], "I don't recognise that command")
would replicate what you have going on right now.
See the link provided by cjrh here: http://docs.python.org/3.3/tutorial/introduction.html#strings
Our mind-reading powers are a bit off in October, we'll need some more information other than "it does not work" to help you with that.
I'm trying to learn Python with the help of Learning Python the Hard Way.
I've reached exercise 41 (Gothons from Planet Percal #25), you can see the full code >here<
I understand everything until the last function runner()
def runner(map, start)
next = start
while True:
room = map[next]
print "\n--------"
next = room()
runner(ROOMS, 'central_corridor')
As far as I can understand, next is assigned the value of start, being the key of the first function to run. The the while loop is initiated assigning the function at that key to room.
Then the function prints out a line of dashes and after that it assigns the returned value of the function call to the variable next.
What I don't understand is why the user "sees" the function being called. To me it looks like the function call is just assigned to a variable next. I would expect something like next() or room() being the next line. Secondly I don't understand why the while-loop stops, shouldn't it just continue until false or quit?
These might seem like foolish questions to most of you, but I'm new to the programming game and I don't understand the answers being given to this question elsewhere on this site.
Hope someone can dumb down to my level and explain it to me...
The user sees the function being called, because the function prints things.
The function is actually being called (with "room()") and the result of the call is set to next.
E.g. If the room is "the_bridge", some stuff is printed and then "death", "escape_pod" or "the_bridge" is returned.
While it's true that "while True:" is an infinite loop, Python has a way to quit the program entirely.
The call "exit(0)" quits the whole program right there and then, no questions asked.
I'm not sure how many questions you have, but I'll clarify two things:
(1) next = room() works because map is a dict, the values of which are functions, so room = map[next] retrieves a function from map, and stores that function in the variable room. The expression room() calls that function.
(2) Looking at the code, it does appear that the only exit from the loop will be when the programme exits, or when an exception (if any) is thrown.
The Gothon thing is not even Ex 41.
(Maybe it was before, when this post was written? It's Ex 43 now.)
Anyway, it's confusing.
I thought i finally found something relevant to ex 41, then i come here and see this...