Everytime this piece of code is compiled, I expect it to go through each "if,elif" untill it finds a match. So it can continue to print out the given list on the screen.
But to my surprise even if you input "rifles", all it does is give you the "else" statement.
This is my first post on Stackoverflow, so forgive me if I made some mistake.
Any help is very much appreciated, thanks in advance.
rifles = ["Ak47", "M4A1", "Aug", "Famas", "Galil"]
pistols = ["Glock", "USP", "Deagle", "P250", "Five-7", "Tec-9"]
shotguns = ["Buckshot", "Benelli", "M1319", "Sawed-Off"]
snipers = ["AWP", "SSG", "Cheytac", "Barret", "M24"]
grenades = ["Smoke", "High-Explosive", "Flash", "Concussion", "Molotov", "Incendiary"]
knives = ["Bayonette", "Karambit", "Machete", "Butterfly", "Katana"]
equipment = ["Kevlar", "Helmet", "Tactical-Shield", "Boots", "Nightvision"]
raw_input = input("Search: ")
def search():
if raw_input == "Rifles":
for ri in rifles:
print(ri)
break
elif raw_input is "Pistols":
for pi in pistols:
print(pi)
break
elif raw_input is "Shotguns":
for sho in shotguns:
print(sho)
break
elif raw_input is "Snipers":
for sni in snipers:
print(sni)
break
elif raw_input is "Grenades":
for gre in grenades:
print(gre)
break
elif raw_input is "Knives":
for kni in knives:
print(kni)
elif raw_input is "Equipment":
for equ in equipment:
print(equ)
else:
print("Try again...")
return
search()
You are breaking each loop after you only print one element.
if raw_input == "Rifles":
for ri in rifles:
print(ri)
break
You don't really need the break, so get rid of it and it will work when you type "Rifles"
Your code can be expressed in a much more concise and "pythonic" way:
guns = {
"rifles" : ["Ak47", "M4A1", "Aug", "Famas", "Galil"],
"pistols" : ["Glock", "USP", "Deagle", "P250", "Five-7", "Tec-9"],
"shotguns" : ["Buckshot", "Benelli", "M1319", "Sawed-Off"],
"snipers" : ["AWP", "SSG", "Cheytac", "Barret", "M24"],
"grenades" : ["Smoke", "High-Explosive", "Flash", "Concussion", "Molotov", "Incendiary"],
"knives" : ["Bayonette", "Karambit", "Machete", "Butterfly", "Katana"],
"equipment": ["Kevlar", "Helmet", "Tactical-Shield", "Boots", "Nightvision"],
}
gun = raw_input("Search: ")
gun = gun.lower()
try:
print guns[gun]
except KeyError:
print "No gun of type %s" % gun
But to my surprise even if you input "rifles", all it does is give you the "else" statement.
Your code checks for "Rifles", not "rifles". If you want the two to compare equal, you need to normalise the letter case, for example, like so:
if raw_input.lower() == "rifles":
for ri in rifles:
...
Related
I keep getting an error when I run this functions. Everything goes through and then it shows this error. I have tried adding .items() to the end when I print the dictionary and still throws this error.
CLARIFICATION just realized. Not getting any type errors or anything. It prints fine but when doesn't add the second variable to the dictionary. Instead it prints this..
{'Frappe': ('small', function type_of_milk at 0x000002BE2BCD2F78>)}
def order():
ready_to_order = True
while ready_to_order != False:
ordering_q = input(
"""Do you know what you would like to order or do you need to see the menu?
[M]enu or [R]eady to order or [Q]uit: """)
if ordering_q.upper() == "Q":
sys.exit()
elif ordering_q.upper() == "M":
print(Menu())
elif ordering_q.upper() == "R":
ready_to_order = False
else:
print("Please enter valid letters only, try again.")
print(" ")
print(" ")
add_cart = True
while add_cart != False:
order1 = input("What would you like to order?")
if order1.upper() == "Done":
add_cart = False
elif order1 == 'a1':
print("Frappe added to cart")
global total_order
total_order += 3
drink_size()
type_of_milk()
order_dict['Frappe'] = (drink_sizes, type_of_milk)
add_cart = False
print(order_dict)
This line:
order_dict['Frappe'] = (drink_sizes, type_of_milk)
is adding the function type_of_milk to your dict, which is why you see function type_of_milk at 0x000002BE2BCD2F78> when you print the dict out. Maybe you meant to say type_of_milk()?
I'm writing my first program - it's an idiom generator, which combines individual elements from lists of random verbs, nouns, and pronouns (that I have entered) in Madlibs style and generates a humorous expression. This is a simplified version of my source code:
baseFunction = True
def mainFunction() :
import random
quest = input("Which language do you want it in? Type 'French' or 'English'. ")
if quest == "French" or "french":
verb =
#list of verbs I have manually entered
noun =
#list of nouns I have manually entered
pronoun =
#list of pronouns I have manually entered
morenouns =
#list of nouns I have manually entered
phrase = random.choice(verb) + random.choice(noun) + random.choice(pronoun) + random.choice(morenouns)
print(phrase)
print("Now, give it some meaning and use in the world!")
elif quest == "English" or "english":
verb =
#another list of verbs I have manually entered
noun =
#another list of nouns I have manually entered
pronoun =
#another list of pronouns I have manually entered
morenouns =
#another list of nouns I have manually entered
phrase = random.choice(verb) + random.choice(noun) + random.choice(pronoun) + random.choice(morenouns)
print(phrase)
print("Now, invent some meaning for it and use it in the world!")
f8 = input("Do you want to make another one? Say 'yes' if you do. ")
if f8 == "yes" or "Yes":
mainFunction()
else:
print("Thanks for playing!")
else:
print("Didn't quite catch that. Try again! (say yes!)")
mainFunction()
def malif() :
ques = input("Want to hear a funny idiom? Say 'yes' or 'no'. ")
if ques == "yes" or "Yes":
mainFunction()
elif ques == "no" or "No":
print("Wrong answer. Try again! (say yes)")
malif()
else:
print("Didn't quite catch that. Say 'yes' or 'no'.")
while baseFunction :
malif()
mainFunction()
Essentially, I am asking the user whether they want to make an idiom, offering them a choice of language, generating the expression for them, and then asking them if they want to repeat the process. When I run the script in PyCharm, it runs the two functions in order (meaning, malif() first and then mainFunction(), as I have it at the end) but it does not pay any attention to my input (ex. if I say 'no' it runs the mainFunction anyway and will always do it in French even if I say 'English').
I used some of the tips discussed in this entry (Python - How to make program go back to the top of the code instead of closing). I think the problem lies calling the functions in their own definitions (ex. calling malif() if I answer 'no' to input 'ques', which is defined in malif() ). Yet, I have followed the tips discussed in the question that I linked and it is still not working the way that I want it to. Am I doing something wrong in formatting the code (ex. in terms of indentation) or if it is not obvious what I am doing wrong, is there a way for me to loop functions back to the beginning that was not suggested in the original question?
Thanks!
First some tips when you work with strings as input. Python will make the difference between caps and non-caps letter, thus a good way to deal with strings is to lower() them first (or upper(), ...):
Example:
ques = input("Enter Yes or No: ")
ques = ques.lower()
if ques == "yes":
# do something
elif ques == "no":
# do something else
else:
# raise error
Now I feel like your code is build in a funny way. A good habit is to separate the import from the functions, from the main program. The 2 first will be imported if the module (file) is imported, while the last one will be played when the file is executed. To do so, you can use this:
# -*- coding: utf-8 -*-
"""
docstring of the module
"""
# Imports
import random
import os
# Functions
def f():
return "Hello world"
# Main program
if __name__ == '__main__':
# Calling the function, taking the inputs and so on
In the main program, it's rather useful to deal with the possibility that an exception is raised. Moreover, if you use the cmd to display your program, the cmd will close immediately when an error is raised. This syntax is quite useful:
if __name__ == '__main__':
try:
# Do stuff
except:
import sys
print (sys.exc_info()[0])
import traceback
print (traceback.format_exc())
os.system("pause") # for windows, else easy way is to have an empty input to freeze the cmd
Now your code. I would rework it this way:
# -*- coding: utf-8 -*-
"""
Docstring
"""
# Imports
import random
import os
# Functions
def build_a_phrase(language) :
if language == "french":
verb = ["vendre", "atterir", "attaquer", "jeter"]
#list of verbs I have manually entered
noun = ["arbre", "poisson", "chien"]
#list of nouns I have manually entered
pronoun = ["un", "les"]
#list of pronouns I have manually entered
morenouns = ["chat", "oiseau"]
#list of nouns I have manually entered
choices = [random.choice(verb), random.choice(noun), random.choice(pronoun), random.choice(morenouns)]
phrase = " ".join(choices) # Add a space between the words
return phrase
elif language == "english":
verb = ["...", "...", "..."]
#another list of verbs I have manually entered
noun = ["...", "...", "..."]
#another list of nouns I have manually entered
pronoun = ["...", "...", "..."]
#another list of pronouns I have manually entered
morenouns = ["...", "...", "..."]
#another list of nouns I have manually entered
choices = [random.choice(verb), random.choice(noun), random.choice(pronoun), random.choice(morenouns)]
phrase = " ".join(choices) # Add a space between the words
return phrase
if __name__ == '__main__':
try:
# Parameters
available_language = ["french", "english"]
available_answers = ["yes", "no"]
# Safety implementation of an input
quest = ""
i = 0
while quest.lower() not in available_answers:
quest = input("Want to hear a funny idiom? Say 'yes' or 'no'. ")
i += 1
if i == 2: # number of tries
break
if quest.lower() == "no":
print ("I'm sure you meant yes.")
language = ""
i = 0
while language.lower() not in available_language:
language = input("Which language do you want it in? Type 'French' or 'English'.\n")
i += 1
if i == 2: # number of tries
break
while True:
sentence = build_a_phrase(language)
print (sentence)
print ("Now, give it some meaning and use in the world!")
f8 = ""
i = 0
while f8.lower() not in available_answers:
f8 = input("Do you want to make another one? Say 'yes' if you do. ")
i += 1
if i == 2: # number of tries
break
if f8.lower() == "no":
print("Thanks for playing!")
break
except:
import sys
print (sys.exc_info()[0])
import traceback
print (traceback.format_exc())
os.system("pause")
Hope you'll get a few good tricks from this answer, and some good habits :)
Not complete yet, when the input is wrong, an Error should be raised rather than waiting for the error resulting in the wrong input (i.e. a raise statement should be placed instead of the breaks)
I am just exploring the vast language of python. I'm heavily relying on the inbuilt error-decetion and googling to debug my programs. I had no luck this time around. Thank you for your time!
I am getting
"invalid syntax at line 5"
Here is my python-code of a simple HANGMAN-game:
import random
def __secretword__():
secret_word = word_list[random.randomint(len(word_list))
return secret_word #THIS IS LINE 5
def __ask__():
ans = input("Would you like to play more? (yes/no): ")
if ans == "yes"
__secretword__()
else:
print(":(")
__secretword__()
word_list = ["nei", "brun", "ja", "smile", "glad", "gal"]
secret_word = secret_word
sw_list = list(secret_word)
guess_lines = ["_"] * len(secret_word)
mistakes = []
lives = 2 * len(secret_word)
print(guess_lines)
user_guess = input("Guess a letter: ")
while(lives != 0)
if user_guess in sw_list:
i = sw_list.index(user_guess)
del guess_lines[i]
guess_lines.insert(i, user_guess)
print(guess_lines)
print("Lives: ", lives)
print("Mistakes: ", mistakes)
if "_" not in guess_lines:
break
else:
mistakes.append(user_guess)
print(guess_lines)
lives = lives - 1
print("Lives: ", lives)
print(mistakes)
__ask__()
Your problem is that the line before return is missing its closing square bracket ]. So Python thinks you're still inside the brackets when you get to line 5, and placing return inside brackets is a syntax error.
This is a fairly common problem - if you get a syntax error on a line that looks fine, it's often worthwhile to look at the previous line, and see if your line might be being considered part of that.
while loop == 6:
if EVENTCOUNT >= 4:
_, username, para, value = event.split(" ", 3)
try:
self.dbcur.execute('select ? from users where name = ?', [para, username])
if rrf is None:
print notex
else:
print str(username)+" has been altered: "+str(para)+" => "+str(value)+"."
while loop == 2:
again = raw_input("Is that all? (Y/N)")
while True:
if again == "Y":
# edit another parameter
loop=4
elif again == "N":
print "Thanks! Bye! \nAll credits of this program go to Trey."
#end program
break
else:
print "Sorry! That wasn't Y or N."
loop == 2
I get an the error: "IndentationError: expected an indented block" and there is an error underneath the if EVENTCOUNT >=4:
Use an IDE, which often has an indentation tool for automatically converting mixed tabs and spaces to either all tabs or spaces. Here is your code with 4 spaces per indent.
while loop == 6:
if EVENTCOUNT >= 4:
_, username, para, value = event.split(" ", 3)
try:
self.dbcur.execute('select ? from users where name = ?', [para, username])
if rrf is None:
print notex
else:
print str(username)+" has been altered: "+str(para)+" => "+str(value)+"."
while loop == 2:
again = raw_input("Is that all? (Y/N)")
while True:
if again == "Y":
# edit another parameter
loop=4
elif again == "N":
print "Thanks! Bye! \nAll credits of this program go to Trey."
#end program
break
else:
print "Sorry! That wasn't Y or N."
loop == 2
except Exception,err:
print "error"
You must use a consistent indentation for all blocks within a file - I (and PEP8) strongly recommend four spaces.
Mixing tabs and spaces in a single file is bad because tabs have variable perceived widths based on the developer's environment. Mixing the number of spaces within a single file can confuse the interpreter.
hey im making a simple little grocery list on Python. I know it's not the most eloquent... but I am just learning the syntax right now. I want to get into learning Django.
list = []
def makeList():
listing = True
while listing:
addTo = raw_input("Add to list: ")
if addTo == 'q':
listing = False
else:
list.append(addTo)
def checkList():
if check in list:
print "Yay there is " + check + " here"
else:
print "No you have not added that..."
addAnother = raw_input("Would you like to add it? ")
if str.lower(addAnother) == "yes":
list.append(check)
elif str.lower(addAnother) == "no":
print "Okay then here is your list."
print list
else:
print check
makeList()
check = raw_input("What item: ")
checkList()
I know its pretty complex and hard to understand O_o... but you can see that the nested if statement is not registering when you run it.
What is making it do this? I think that's the best way to ask this.
I've rewritten it a bit to make it cleaner and more Pythonic;
def get_list(prompt, halt):
lst = []
while True:
item = raw_input(prompt)
if item == halt:
return lst
else:
lst.append(item)
def check_list(lst, item):
if item in lst:
print('Yay there is {} here'.format(item))
return True
else:
print('No you have not added {}'.format(item))
return False
def get_yesno(prompt):
while True:
yesno = raw_input(prompt).lower()
if yesno in {'y', 'yes'}:
return True
elif yesno in {'n', 'no'}:
return False
def main():
mylist = get_list('Add to list:', 'q')
check = raw_input('Look for item:')
if not check_list(mylist, check):
if get_yesno('Would you like to add it?'):
mylist.append(check)
print(mylist)
if __name__=="__main__":
main()
Some style tips:
Don't use list as a variable name; it's a built-in function, and you don't want to overwrite it.
Global variables are almost always a bad idea; passing data around explicitly makes it much easier to figure out where bad data is coming from, and makes functions more reusable.
camelCase is generally denigrated; use_underscores for function names instead.
You probably intended to keep going rather than break when you append the new item (or at least print something to indicate success), but the nested if statement works just fine, appends the thing to the list as specified and then the function and program terminate.