My Python 'IF' statements are ignored - python

Sorry that this is a bit of an amateur question, but i can't see what i'm doing wrong here, and it always helps if you get someone else to look at your code!
So i want people to be sorted into a different house depending on their birth month, and my string is being sliced at the right point (confirmed with a quick test in the interactive prompt) but house is always set to the else statement - which shouldn't happen...
Any help will be much appreciated!
(please ignore the append_to_file function also - just focusing on the get_user_inputs function)
(Text wouldn't format properly so i had to link to pastebin:)
CODE IS HERE https://pastebin.com/DzkeZ8bq
had to put code for a pastebin link so have a print statement
print("You're awesome if you help me!")
FURTHER EXPLAINATION:
So say if the following test data is used:
firstName = "Joe"
lastName = "Bloggs"
dateOfBirth = "10/05/2002"
It should sort Joe Bloggs into Saturn house (as dateOfBirth[3:5] is '05', meaning that '05' is in the list 'sat')
But instead, Joe Bloggs is sorted into Mars house (because the else statement has no condition, so my code seems to be defaulting to that.)
Again, thanks in advance :)

try changing
if dateOfBirth[3:5] in nep == True:
To
if dateOfBirth[3:5] in nep:

Related

Intro to Python: Creating a function that tests the validity of 'months'

I have to say thank you in advance to whomever is helping me out here, I recently started learning python a fews days ago and a current problem set we are working on has been quite confusing.
I think it has to do with a fundamental misunderstanding of mine on how parameters are assigned within a function.
As I have briefly mentioned in title, I am being tasked with creating a function is_months_valid(months)
This is what I have done so far, brace yourselves:
def is_valid_month(month):
month = int
if month <= 0:
month == False
print('this is not a valid month')
if month >12:
month = False
print('this is not a valid month')
return month
As you can see what I am trying to do here is create an integer range from 1 to 12 where 'months' is a valid date.
The issue that I have been encountering is this:
'<=' not supported between instances of 'type' and 'int'
I.e a type error, and I think that my issue is that I am having trouble defining my parameter 'months' as an integer that can take any value. And this value, when run through my program presents me with a valid month or a print statement that says that
'this isnt a valid month'
Again, I am not sure how my code appears to anyone outside my perspective but I would appreciate any and all feedback on it.
Thank you
EDIT: Thank you guys my little frankenstein code finally works, for some reason I was under the assumption that in order to have my parameter (month) take any integer value I wanted, I needed to define it as an 'int.'
I know that stackoverflow isnt "help a student with his cs homework.com" but thank you all for your feedback regarding my indentation, the rules of python, and the guidance in the right direction. Coding is something that I want to improve on and hopefully become literate in.
Thank you
Maybe you meant that!
def is_valid_month(month):
if month <= 0:
month = False
print('this is not a valid month')
elif month >12:
month = False
print('this is not a valid month')
else:month=True
return month

How do you recall an item from a list based on it's index position?

I'm attempting to recall an item from a list based on it's index position, and the index position part is important part because in my script the user types in an input and then it's converted into a list and then I want to re-integrate the input into a final print statement. Here's some example code.
print("Star Wars is a [adjective] story of [noun] vs Sith")
swinput = list(swinput.split())
let's say the user input great and Jedi
I would want the output to look like: Star Wars is a great story of Jedi vs Sith
The key piece that I can't get is that regardless of what the user inputs it will show up in the print statement and I can't figure that piece out so any help as always is greatly appreciated!
It seems like you're trying to replace the [adjective] and [noun] parts of that sentence based on some variables. You might want to check out the format method. With it, you can do stuff like this:
def format_quote(adjective, noun):
return "Star Wars is a {} story of {} vs Sith".format(adjective, noun)
or, in Python 3.6 or later, you can use f-strings:
def format_quote(adjective, noun):
return f"Star Wars is a {adjective} story of {noun} vs Sith"
With your information this is what I understood. Tell me if I forgot something.
l = ["word1","word2"]
print(f'this is {l[0]} and this is {l[1]}')
Is this what you are asking for?

?Is there a reason why my program won't perform it's if elif else statement after receiving proper input

Basically, the goal of this program is to take input from the user on what they want to order, process the cost of the item and tack on sales tax and a tip and return that. I'm struggling with how to go about getting my program to take input and run an if elif else statement based on what the input is.
I'm fairly new and I'm still figuring out how to ask a constructive question, so bear with me here. Also, I know there a bits of it that are unfinished, which may factor into it, but I'm not really concerned with the incomplete bits
I've tried making the if statement conditions dependent on the input given using the == operator as well as changing that to an "if answer is __: print a response. I'm fairly confident that I can get the program to print out a tip and tax tacked onto a price, but everything I've tried so far keeps exiting my program after receiving any form of input.
salesTax = 0.07 #the tax added onto the total
tip= 0.18 #the percentage for a tip
steak= 96 # a var for a steak priced so deliciously, that it *must* be good.
goose= 42 #var for the oddly familiar, yet disturbingly alien meal that is goose.
narwhal= 109 #var for a meal that questions its own existence, then laughs in the face of that question
menu = ['high-stakes steak', 'uncanny boiled goose', 'endangered carribrean narwhal caccitore']
print("Tonight's menu at Joe's ethically questionable eatery includes")
print(menu)
input('Hon hon, what\'ll it be, monsieur? the goose, stake or narwhal?')
answer = input
if answer == 'goose':
print("Ah, very good monsieur the cost will be 42. We will beegen ze cooking of ze goose")
elif answer is 'steak':
print("Ah, a high roller, we will begin")
I expect it to take 'goose' as an answer and print a response (eventually i'd make this take the number assigned to goose and calculate tax), but it simply ignores any input every single time.
input is a build-in function, you should assign the value got from input, but your codes assign the function itself to your variable answer
answer = input('Hon hon, what\'ll it be, monsieur? the goose, stake or narwhal?')
You need to assign your input to a variable. Your input is just reading from the keyboard and you don't save that value. Fix this with:
answer = input('Hon hon, what\'ll it be, monsieur? the goose, stake or narwhal?')
if answer == 'goose':

How to reassign an element of a dict

I'm trying to change a variable used as an element of a list after I've defined the variable... Hopefully the code will explain my problem better than I can:
i = 0
friend = "jake"
stuff = [friend]
dialogue = ["talk to %s please" %(stuff[0])]
while i < 2:
print (dialogue)
friend = "paul"
print ("")
i+=1
as it stands the program prints:
talk to jake please
talk to jake please
but I want it to print:
talk to jake please
talk to paul please
Thanks in advance for your help
EDIT
I've realised this example ^ is an over simplification of my problem, so I've written another basic program which better describes my problem and have put it on another question to prevent this one becoming too convaluded
Change friend = "paul" to stuff[0] = "paul"
Alternatively, you could keep friend = "paul" but put stuff = [friend] again on the line below it.
After either of those, you would need to put the dialogue = ["talk to %s please" %(stuff[0])] line again.
If you want to know why your way doesn't work, please ask in the commends. Tell me if this works!
P.S. There are many better ways to do the thing your trying to do. I suggest you learn about iteration, lists, and for loops.
As far as I understand your simplified problem, it seems as if you have different variables in the stuff list that mean different things.
A more appropriate data-structure for that kind of thing (especially when you will be modifying things) is a dictionary.
So, you could define stuff as:
stuff = {"friend": "jake"}
and then you could do things like:
print("talk to %s please" % stuff["friend"] )
#talk to jake please
and also modify the friend attribute much easier than a list by doing:
stuff["friend"] = "paul"
making the output of the snippet two above now:
talk to paul please

match hex string with list indice

I'm building a de-identify tool. It replaces all names by other names.
We got a report that <name>Peter</name> met <name>Jane</name> yesterday. <name>Peter</name> is suspicious.
outpout :
We got a report that <name>Billy</name> met <name>Elsa</name> yesterday. <name>Billy</name> is suspicious.
It can be done on multiple documents, and one name is always replaced by the same counterpart, so you can still understand who the text is talking about. BUT, all documents have an ID, referring to the person this file is about (I'm working with files in a public service) and only documents with the same people ID will be de-identified the same way, with the same names. (the goal is to watch evolution and people's history) This is a security measure, such as when I hand over the tool to a third party, I don't hand over the key to my own documents with it.
So the same input, with a different ID, produces :
We got a report that <name>Henry</name> met <name>Alicia</name> yesterday. <name>Henry</name> is suspicious.
Right now, I'm hashing each name with the document ID as a salt, I convert the hash to an integer, then subtract the length of the name list until I can request a name with that integer as an indice. But I feel like there should be a quicker/more straightforward approach ?
It's really more of an algorithmic question, but if it's of any relevance I'm working with python 2.7 Please request more explanation if needed. Thank you !
I hope it's clearer this way รด_o Sorry when you are neck-deep in your code you forget others need a bigger picture to understand how you got there.
As #LutzHorn pointed out, you could just use a dict to map real names to false ones.
You could also just do something like:
existing_names = []
for nameocurrence in original_text:
if not nameoccurence.name in existing_names:
nameoccurence.id = len(existing_names)
existing_names.append(nameoccurence.name)
else:
nameoccurence.id = existing_names.index(nameoccurence.name)
for idx, _ in enumerate(existing_names):
existing_names[idx] = gimme_random_name()
Try using a dictionary of names.
import re
names = {"Peter": "Billy", "Jane": "Elsa"}
for name in re.findall("<name>([a-zA-Z]+)</name>", s):
s = re.sub("<name>" + name + "</name>", "<name>"+ names[name] + "</name>", s)
print(s)
Output:
'We got a report that <name>Billy</name> met <name>Elsa</name> yesterday. <name>Billy</name> is suspicious.'

Categories