Nested Loop 'If'' Statement Won't Print Value of Tuple - python
Current assignment is building a basic text adventure. I'm having trouble with the following code. The current assignment uses only functions, and that is the way the rules of the assignment state it must be done.
def make_selections(response):
repeat = True
while repeat == True:
selection = raw_input('-> ')
for i, v in enumerate(response):
i +=1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
if selection == i:
print v[1]
else:
print "There's an error man, what are you doing?!?!?"
firstResponse = 'You chose option one.'
secondResponse = 'You chose option two.'
thirdResponse = 'You chose option three.'
responses = [(0, firstResponse), (1, secondResponse),( 0, thirdResponse)]
make_selections(responses)
My intention in that code is to make it so if the user selects a 1, it will return firstResponse, if the user selects 2 it will return secondResponse, etc.
I am basically just bug testing the code to make sure it produces the appropriate response, hence the "Error man..." string, but for some reason it just loops through the error message without printing the appropriate response string. Why is this?
I know that this code is enumerating the list of tuples and I can call them properly, as I can change the code to the following and get the expected output:
for i, v in enumerate(response):
i += 1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
print i, v
Also, two quick asides before anyone asks:
I know there is currently no way to get out of this while loop. I'm just making sure each part of my code works before I move on to the next part. Which brings me to the point of the tuples.
When I get the code working, a 0 will produce the response message and loop again, asking the user to make a different selection, whereas a 1 will produce the appropriate response, break out of the loop, and move on to the next 'room' in the story... this way I can have as many 'rooms' for as long of a story as I want, the player does not have to 'die' each time they make an incorrect selection, and each 'room' can have any arbitrary amount of options and possible responses to choose from and I don't need to keep writing separate loops for each room.
There are a few problems here.
First, there's no good reason to iterate through all the numbers just to see if one of them matches selection; you already know that will be true if 1 <= selection <= len(response), and you can then just do response[selection-1] to get the v. (If you know anything about dicts, you might be able to see an even more convenient way to write this whole thing… but if not, don't worry about it.)
But if you really want to do this exhaustive search, you shouldn't print out There is an error man after any mismatch, because then you're always going to print it at least twice. Instead, you want to only print it if all of them failed to match. You can do this by keeping track of a "matched" flag, or by using a break and an else: clause on your for loop, whichever seems simpler, but you have to do something. See break and continue Statements, and else Clauses on Loops in the tutorial for more details.
But the biggest problem is that raw_input returns a string, and there's no way a string is ever going to be equal to a number. For example, try '1' == 1 in your interactive interpreter, and it'll say False. So, what you need to do is convert the user's input into a number so you can compare it. You can do that like this:
try:
selection = int(selection)
except ValueError:
print "That's not a number!"
continue
Seems like this is a job for dictionaries in python. Not sure if your assignment allows this, but here's my code:
def make_selections(response):
selection = raw_input('-> ')
print response.get(selection, err_msg)
resp_dict = {
'1':'You chose option one.',
'2':'You chose option two.',
'3':'You chose option three.'
}
err_msg = 'Sorry, you must pick one of these choices: %s'%sorted(resp_dict.keys())
make_selections(resp_dict)
The problem is that you are comparing a string to an integer. Selection is raw input, so it comes in as a str. Convert it to an int and it will evaluate as you expect.
You can check the type of a variable by using type(var). For example, print type(selection) after you take the input will return type 'str'.
def make_selections(response):
repeat = True
while repeat == True:
selection = raw_input('-> ')
for i, v in enumerate(response):
i +=1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
if int(selection) == i:
print v[1]
else:
print "There's an error man, what are you doing?!?!?"
Related
can't get program to iterate properly (TypeError: 'NoneType' object is not iterable)
So just getting started learning python. as practice i decided to build a program that would handle my attacks for my D&D character and i can't quite seem to get this to iterate properly. from random import randint def roll_dice(): type = raw_input("Initiative (i) or Attack (a): ") #variable that is passed through the function roll = randint(1,20) if roll == 1: print "Natural 1" elif roll == 20: print "Natural 20" else: crit = "n" if type == 'i': result = roll + 5 print "Initiative = %d" % result return elif type == 'a': """ most of the rest of the program is after here but that all works fine so there is no reason to take up space with that""" roll_dice() for type in roll_dice(): if type == 'a' or type == 'i': continue program will loop once and then gives me: TypeError: 'NoneType' object is not iterable I know this means that the second time it goes to iterate it is passing nothing through but i can't quite figure out how to fix it. any help and/or explanations would be greatly appreciated Edit: I know it does not run as posted. The whole thing is over 100 lines and I did not want to swamp people with that. Once I get home I will post with the whole thing. For clarification: With the whole program it will run once through loop back to the start and then return the error after a completed second run through the program. So the first time through the loop works it is after the completed second run and attempting to start a third.
It doesn't seem like your roll_dice() function returns anything, causing the TypeError. The reason it "seems" like the program loops once is because of the line right before the for loop, which calls the function. What it seems like you are trying to do is extract the type variable from inside your function, which can be done by returning the type with return type instead of just return and using the if statement alone. To loop until type isn't a or i, a while loop may be more useful, like so: while True: type = roll_dice() if type != 'a' and type != 'i': break
Index Out Of Range When Artificially Limited
when I run this program, sometimes I receive an error.This error however is not possible as I am using an 8x8 grid and I limit the inputs so that they can only be numbers from 0-7, to obey the fact that list indexes start at 0. The user must input coordinates (1-8),(A-H) and the program will check to see if those coordinates are correct, by systematically going through the CompShips list and repeatedly comparing those coordinates to ones given by the user. If the cords match, then a message will appear and a "Z" will change to an "X" on those coordinates, indicating a HIT. If the guess does not match, a "Z" will change to an "M" on those coordinates indicating a MISS. CompShips=[[1,0],[1,1],[2,2],[2,3],[2,4],[3,0],[3,1],[3,2],[5,4],[5,5],[5,6],[5,7],[1,7],[2,7],[3,7],[4,7],[5,7]] FRow1=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow2=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow3=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow4=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow5=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow6=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow7=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow8=["Z","Z","Z","Z","Z","Z","Z","Z",] def PrintFireBoard(): print(Index) print(FRow1) print(FRow2) print(FRow3) print(FRow4) print(FRow5) print(FRow6) print(FRow7) print(FRow8) FireBoard=[FRow1,FRow2,FRow3,FRow4,FRow5,FRow6,FRow7,FRow8] while len(CompShips) !=0 or CompSuccess==17: FireRow=input("Please Choose The Row That You Wish To Fire Upon (1-8) ") FireIndex=input("Please Choose The Column That You Wish To Fire Upon (A-H) ") #As Lists start at 0 FireRow=int(FireRow)-1 if FireIndex==("A"): FireIndex=0 elif FireIndex==("B"): FireIndex=1 elif FireIndex==("C"): FireIndex=2 elif FireIndex==("D"): FireIndex=3 elif FireIndex==("E"): FireIndex=4 elif FireIndex==("F"): FireIndex=5 elif FireIndex==("G"): FireIndex=6 elif FireIndex==("H"): FireIndex=7 Guess=[FireRow,FireIndex] #Check To See If Correct UserSuccess=0 for i in CompShips: if Guess==i: CompShips.remove(Guess) UserSuccess=1 else: pass if UserSuccess==1: print("HIT") print(FireRow) print(FireIndex) FireBoard[[FireRow][FireIndex]]=("H") PrintFireBoard() else: print("MISS") print(FireRow) print(FireIndex) FireBoard[[FireRow][FireIndex]]=("M") PrintFireBoard() I receive the error: IndexError: string index out of range
Looks like these two lines FireBoard[[FireRow][FireIndex]]=("H") FireBoard[[FireRow][FireIndex]]=("M") should be FireBoard[FireRow][FireIndex]="H" FireBoard[FireRow][FireIndex]="M" Explanation: In your old code, FireBoard[[FireRow][FireIndex]]=("H") [FireRow][FireIndex] means, given a list [FireRow] (which contains just one element), get the FireIndex-th element. This is not what you're trying to do. For example [3][0] returns 3, and [3][1] gives IndexError. Take a look at How to define a two-dimensional array in Python Also note that ("H") is the same as the string "H". There is no need to add parentheses.
Here is a much cleaner code! CompShips=[[1,0],[1,1],[2,2],[2,3], [2,4],[3,0],[3,1],[3,2], [5,4],[5,5],[5,6],[5,7], [1,7],[2,7],[3,7],[4,7], [5,7]] FRow=[["Z"]*8]*8 #1 More Pythonic def PrintFireBoard(): #print(Index) for i in range(0,8): print(FRow[i]) FireBoard=FRow[:] #NOTE THIS ONE!!! mydict = {} for i,key in enumerate(["A","B","C","D","E","F","G","H"]): #2 More Pythonic mydict[key] = i while len(CompShips) !=0 or CompSuccess==17: FireRow=input("Please Choose The Row That You Wish To Fire Upon (1-8) ") FireIndex=input("Please Choose The Column That You Wish To Fire Upon (A-H) ") FireRow=int(FireRow)-1 FireIndex = mydict[FireIndex] Guess=[FireRow,FireIndex] print(Guess) UserSuccess=0 for i in CompShips: if Guess==i: CompShips.remove(Guess) UserSuccess=1 else: pass if UserSuccess==1: print("HIT") print(FireRow,FireIndex) FireBoard[FireRow][FireIndex]="H" #3 your problem here PrintFireBoard() else: print("MISS") print(FireRow,FireIndex) FireBoard[FireRow][FireIndex]="M" PrintFireBoard() 1) As explained in the comments that's just a more nicer way to create a list of lists!. Remember DRY principle! Do Not Repeat yourself! 2) Instead of having all that if else to convert the 'A' to 0. You can use a dictionary lookup instead! 3) Your problem seems to be here! correct this to FireBoard[FireRow][FireIndex]="H" PS: NOTE THIS ONE!!!: I'm not just making FireBoard as an alias to FRow! I'm copying it into a FireBoard as a new list! There's a subtle difference read about it here. I'm doing this incase you don't want your original FRow list to be modified!
The indentation in your question was off. I think that all the code from Guess=[FireRow,FireIndex] until the end should be preceded by 4 spaces. I've removed print(Index) since it was not defined. To access FireBoard use: FireBoard[FireRow][FireIndex] Instead of FireBoard[[FireRow][FireIndex]] This should be working CompShips=[[1,0],[1,1],[2,2],[2,3],[2,4],[3,0],[3,1],[3,2],[5,4], [5,5],[5,6],[5,7],[1,7],[2,7],[3,7],[4,7],[5,7]] FRow1=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow2=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow3=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow4=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow5=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow6=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow7=["Z","Z","Z","Z","Z","Z","Z","Z",] FRow8=["Z","Z","Z","Z","Z","Z","Z","Z",] def PrintFireBoard(): print(FRow1) print(FRow2) print(FRow3) print(FRow4) print(FRow5) print(FRow6) print(FRow7) print(FRow8) FireBoard=[FRow1,FRow2,FRow3,FRow4,FRow5,FRow6,FRow7,FRow8] while len(CompShips) !=0 or CompSuccess==17: FireRow=input("Please Choose The Row That You Wish To Fire Upon (1-8) ") FireIndex=input("Please Choose The Column That You Wish To Fire Upon (A-H) ") #As Lists start at 0 FireRow=int(FireRow)-1 if FireIndex==("A"): FireIndex=0 elif FireIndex==("B"): FireIndex=1 elif FireIndex==("C"): FireIndex=2 elif FireIndex==("D"): FireIndex=3 elif FireIndex==("E"): FireIndex=4 elif FireIndex==("F"): FireIndex=5 elif FireIndex==("G"): FireIndex=6 elif FireIndex==("H"): FireIndex=7 Guess=[FireRow,FireIndex] #Check To See If Correct UserSuccess=0 for i in CompShips: if Guess==i: CompShips.remove(Guess) UserSuccess=1 else: pass if UserSuccess==1: print("HIT") print(FireRow) print(FireIndex) FireBoard[FireRow][FireIndex]=("H") PrintFireBoard() else: print("MISS") print(FireRow) print(FireIndex) FireBoard[FireRow][FireIndex]=("M") PrintFireBoard()
Python issue with replace statement?
I've been write this practice program for while now, the whole purpose of the code is to get user input and generate passwords, everything almost works, but the replace statements are driving me nuts. Maybe one of you smart programmers can help me, because I'm kinda new to this whole field of programming. The issue is that replace statement only seems to work with the first char in Strng, but not the others one. The other funcs blower the last run first and then the middle one runs. def Manip(Strng): #Strng = 'jayjay' print (Strng.replace('j','h',1)) #Displays: 'hayjay' print (Strng.replace('j','h',4)) #Displays: 'hayhay' return def Add_nums(Strng): Size=len(str(Strng)) Total_per = str(Strng).count('%') # Get The % Spots Position, So they only get replaced with numbers during permutation currnt_Pos = 0 per = [] # % position per for percent rGen = '' for i in str(Strng): if i == str('%'): per.append(currnt_Pos) currnt_Pos+=1 for num,pos in zip(str(self.ints),per): rGen = Strng.replace(str(Strng[pos]),str(num),4); return rGen for pos in AlphaB: # DataBase Of The Positions Of Alphabets for letter in self.alphas: #letters in The User Inputs GenPass=(self.forms.replace(self.forms[pos],letter,int(pos))) # Not Fully Formatted yet; you got something like Cat%%%, so you can use another function to change % to nums # And use the permutations function to generate other passwrds and then # continue to the rest of this for loop which will generate something like cat222 or cat333 Add_nums(GenPass) # The Function That will add numbers to the Cat%%% print (rGen);exit()
NameError when programming in python
I made a program in python that is supposed to accept a name as user input. It will then check if the name given is contained inside a string that is already given and if it is then the program will print out the telephone next to that name. My code is as follows: tilefwnikos_katalogos = "Christoforos 99111111: Eirini 99556677: Costas 99222222: George 99333333: Panayiotis 99444444: Katerina 96543217" check=str(input("Give a name: ")) for check in tilefwnikos_katalogos: if check=="Christoforos": arxi=check.find("Christoforos") elif check=="Eirini": arxi=check.find("Eirini") elif check=="Costas": arxi=check.find("Costas") elif check=="George": arxi=check.find("George") elif check=="Panayiotis": arxi=check.find("Panayiotis") elif check=="Katerina": arxi=check.find("Katerina") s=check.find(" ",arxi) arxi=s y=check.find(":",arxi) telos=y apotelesma=tilefwnikos_katalogos[arxi+1:telos] print(apotelesma) But when I try to run it, I input the name and then the following message pops up: Traceback (most recent call last): File "C:\Users\Sotiris\Desktop\test.py", line 16, in <module> s=check.find(" ",arxi) NameError: name 'arxi' is not defined What am I doing wrong?
You're getting your error because arxi isn't getting defined in the first place when then name the user gave is not present on your list.You can fix that by simply adding an unconditional else case to your if/else if bundle as pointed in the comments. But the very way you tackled this problem is faulty, storing data like this in a string is a bad idea, you want to use a dictionary: phone_catalog = {'Christoforos': 99111111, 'Eirini': 99556677, 'Costas': 99222222, 'George':99333333, 'Panayiotis':99444444, 'Katerina': 96543217} Also check isn't a very clear variable name, maybe you should try using something better like: user_name = str(input("Give a name: ")) And now you can do your if/elif condition but replacing it for using dictionary logic and making sure you have a final else, like such: if user_name in phone_catalog: print(phone_catalog[user_name]) else: print("Unknown user") See how the dictionary made your life much easier and your code cleaner here? Read more on Python Data Structures.
so there are a few things you have overlooked / not going as expected, the first of which is how iterating over strings in python works: tilefwnikos_katalogos = "Christoforos 99111111: Eirini 99556677: Costas 99222222: George 99333333: Panayiotis 99444444: Katerina 96543217" for check in tilefwnikos_katalogos: print(check) #print(repr(check)) #this shows it as you would write it in code ('HI' instead of just HI) so check can never be equal to any of the things you are checking it against, and without an else statement the variable arxi is never defined. I'm assuming you meant to use the check from the user input instead of the one in the loop but I'm not sure you need the loop at all: tilefwnikos_katalogos = "Christoforos 99111111: Eirini 99556677: Costas 99222222: George 99333333: Panayiotis 99444444: Katerina 96543217" check=str(input("Give a name: ")) #the str() isn't really necessary, it is already a str. if check=="Christoforos": arxi=check.find("Christoforos") elif check=="Eirini": arxi=check.find("Eirini") elif check=="Costas": arxi=check.find("Costas") elif check=="George": arxi=check.find("George") elif check=="Panayiotis": arxi=check.find("Panayiotis") elif check=="Katerina": arxi=check.find("Katerina") else: raise NotImplementedError("need a case where input is invalid") s=check.find(" ",arxi) arxi=s y=check.find(":",arxi) telos=y apotelesma=tilefwnikos_katalogos[arxi+1:telos] print(apotelesma) but you could also just see if check is a substring of tilefwnikos_katalogos and deal with other conditions: if check.isalpha() and check in tilefwnikos_katalogos: # ^ ^ see if check is within the string # ^ make sure the input is all letters, don't want to accept number as input arxi=check.find(check) else: raise NotImplementedError("need a case where input is invalid") although this would make an input of C and t give Cristoforos' number since it retrieves the first occurrence of the letter. An alternative approach which includes the loop (but not calling the variable check!) would be to split up the string into a list: tilefwnikos_katalogos = "..." check = input(...) for entry in tilefwnikos_katalogos.split(":"): name, number = entry.strip().split(" ") if check == name: apotelesma=number break else: raise NotImplementedError("need a case where input is invalid") although if you are going to parse the string anyway and you may use the data more then once it would be even better to pack the data into a dict like #BernardMeurer suggested: data = {} for entry in tilefwnikos_katalogos.split(":"): name, number = entry.strip().split(" ") data[name] = number #maybe use int(number)? if check in data: apotelesma = data[check] else: raise NotImplementedError("need a case where input is invalid")
Python input datatype handling
I spent a good hour or more looking for the answer on here. I have found a few things that help, but do not answer my question specifically. I am using Python 3.3.3. I am a novice so please be gentle. I am trying to create a program that takes a user input, but then I need to do a check to see what datatype that input is, and then based on that datatype take a certain course of action. Any string besides those found in this list: valid_help_string_list = ['\'help\'', '\'HELP\'', 'help', 'HELP'] should result in the printing of: 'please enter a valid entry' or something to that effect. Any integer (over 0 but under 500) should have float() used on it to make the rows line up. Any float (over 0.0 but under 500.0) is valid. For the sake of this project I am assuming nobody using this will weigh under 100 lbs or over 500. Anything not falling within those categories should also yield the same "please enter a valid response" error message to the user. I think it's simple enough of a project to take on for a novice. The program is meant to allow you to input your weight and then creates a pictogram based on that weight and saves it all on the next open line of the .txt file I have set up for it. Or if you want to see the legend for the pictogram, you should be able to type help in any variation found in that list. Any help would be much appreciated.
The user input will be a string by default, so we need to check whether it could become an integer or float. As you want to turn the integers in floats anyway, there's no need to do anything complex: def validate_input(val, min_v=100, max_v=500): try: val = float(val) except ValueError: print("Not a valid entry") else: if not min_v < val <= max_v: print("Value should be between {} and {}".format(min_v, max_v)) else: return val return False Now your calling loop can read: while True: val = input("...") if val in valid_help_string_list: # print help else: val = validate_input(val) if val: break # use val Note that this relies on the return from validate_input being either False or a number larger than 0; Python will interpret a zero return as False and not reach the break, so I recommend keeping min_v >= 0.