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
Related
I know it sounds dumb, but I am making an annoying baby simulation that repeatedly asks questions unless given an exact input response to prank a friend.
I have a set of random questions as well as random follow-up questions to feed to him while he will toil away until he essentially discovers the "password" input. My follow-up questions, however, will not randomize and instead select only one out of the list and then break the code entirely, making the new input prompt a random character/element over and over again infinitely.
I have tried placing another while loop within the while loop to assert more definite randomness to the follow-up question pulling and hopefully fix the input prompt issue, but I am not even sure if you can do such a thing successfully and it didn't work so I removed it, and I am still REALLY new to coding entirely.
I may just be over my head despite the idea seeming relatively simple so the solution may be something I haven't learned, but here is my silly prank script that I cant fix:
from random import choice
new_questions = ["Where are all the dinosaurs?: ", "How are babies made?: ", "Why don't we have superpowers?: ", "Why is the sky blue?: "]
questions = ["Well why is the sky blue then?!: ", "Why though?: ", "I still don't get it...why?: ", "OHH OKAY...no, no, wait, but...Why?: ", "WHY?!: ", "You suck at explaining things...just tell me why already.: ", "Why?: ", "What does that have to do with the sky being blue...?: ", "Yeah, I get that part, but why?: ", "Ok, why?: "]
new_questions = choice(new_questions)
answer = input(new_questions).strip().lower()
while answer != "just because":
questions = choice(questions)
answer = input(questions).strip().lower()
I have yet to finish it, as I am still trying to understand why this first part breaks.
Upon running, you will see that it executes most of it well, but it cannot randomly pick from my variable "questions" multiple times randomly, and it also breaks after the first pull from the questions list and will consequently only ask for an input with a singular character element instead.
You're overwriting the question list in questions = choice(questions) by assign it a new value (the choice). Change it to:
while answer != "just because":
question = choice(questions)
answer = input(question).strip().lower()
You don't want to do questions = choice(questions) because that replaces the list of questions with a single randomly chosen questions. Instead, something like
while answer != "just because":
question = choice(questions)
answer = input(question).strip().lower()
Notice that questions is now left undisturbed.
I'm new to programming and doing some problems on kattis. But on this one
https://open.kattis.com/problems/jobexpenses
All the given test are correct but when I upload this:
i =input()
k = input().split(" ")
summe=[]
for n in k:
if int(n)<0:
summe.append(int(n))
x=sum(summe)
print(abs(x))
I get a Runtime Error. I don't know what to do now. I'm happy for any tips that might help.
Don't make assumptions like how the input is spaced. Use split() instead of split(" ").
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:
Basically, I have a troubleshooting program, which, I want the user to enter their input. Then, I take this input and split the words into separate strings. After that, I want to create a dictionary from the contents of a .CSV file, with the key as recognisable keywords and the second column as solutions. Finally, I want to check if any of the strings from the split users input are in the dictionary key, print the solution.
However, the problem I am facing is that I can do what I have stated above, however, it loops through and if my input was 'My phone is wet', and 'wet' was a recognisable keyword, it would go through and say 'Not recognised', 'Not recognised', 'Not recognised', then finally it would print the solution. It says not recognised so many times because the strings 'My', 'phone' and 'is' are not recognised.
So how do I test if a users split input is in my dictionary without it outputting 'Not recognised' etc..
Sorry if this was unclear, I'm quite confused by the whole matter.
Code:
import csv, easygui as eg
KeywordsCSV = dict(csv.reader(open('Keywords and Solutions.csv')))
Problem = eg.enterbox('Please enter your problem: ', 'Troubleshooting').lower().split()
for Problems, Solutions in (KeywordsCSV.items()):
pass
Note, I have the pass there, because this is the part I need help on.
My CSV file consists of:
problemKeyword | solution
For example;
wet Put the phone in a bowl of rice.
Your code reads like some ugly code golf. Let's clean it up before we look at how to solve the problem
import easygui as eg
import csv
# # KeywordsCSV = dict(csv.reader(open('Keywords and Solutions.csv')))
# why are you nesting THREE function calls? That's awful. Don't do that.
# KeywordsCSV should be named something different, too. `problems` is probably fine.
with open("Keywords and Solutions.csv") as f:
reader = csv.reader(f)
problems = dict(reader)
problem = eg.enterbox('Please enter your problem: ', 'Troubleshooting').lower().split()
# this one's not bad, but I lowercased your `Problem` because capital-case
# words are idiomatically class names. Chaining this many functions together isn't
# ideal, but for this one-shot case it's not awful.
Let's break a second here and notice that I changed something on literally every line of your code. Take time to familiarize yourself with PEP8 when you can! It will drastically improve any code you write in Python.
Anyway, once you've got a problems dict, and a problem that should be a KEY in that dict, you can do:
if problem in problems:
solution = problems[problem]
or even using the default return of dict.get:
solution = problems.get(problem)
# if KeyError: solution is None
If you wanted to loop this, you could do something like:
while True:
problem = eg.enterbox(...) # as above
solution = problems.get(problem)
if solution is None:
# invalid problem, warn the user
else:
# display the solution? Do whatever it is you're doing with it and...
break
Just have a boolean and an if after the loop that only runs if none of the words in the sentence were recognized.
I think you might be able to use something like:
for word in Problem:
if KeywordsCSV.has_key(word):
KeywordsCSV.get(word)
or the list comprehension:
[KeywordsCSV.get(word) for word in Problem if KeywordsCSV.has_key(word)]
I am trying to name keys in my dictionary in a generic way because the name will be based on the data I get from a file. I am a new beginner to Python and I am not able to solve it, hope to get answer from u guys.
For example:
from collections import defaultdict
dic = defaultdict(dict)
dic = {}
if cycle = fergurson:
dic[cycle] = {}
if loop = mourinho:
a = 2
dic[cycle][loop] = {a}
Sorry if there is syntax error or any other mistake.
The variable fergurson and mourinho will be changing due to different files that I will import later on.
So I am expecting to see my output when i type :
dic[fergurson][mourinho]
the result will be:
>>>dic[fergurson][mourinho]
['2']
It will be done by using Python
Naming things, as they say, is one of the two hardest problems in Computer Science. That and cache invalidation and off-by-one errors.
Instead of focusing on what to call it now, think of how you're going to use the variable in your code a few lines down.
If you were to read code that was
for filename in directory_list:
print filename
It would be easy to presume that it is printing out a list of filenames
On the other hand, if the same code had different names
for a in b:
print a
it would be a lot less expressive as to what it is doing other than printing out a list of who knows what.
I know that this doesn't help what to call your 'dic' variable, but I hope that it gets you on the right track to find the right one for you.
i have found a way, if it is wrong please correct it
import re
dictionary={}
dsw = "I am a Geography teacher"
abc = "I am a clever student"
search = re.search(r'(?<=Geography )(.\w+)',dsw)
dictionary[search]={}
again = re.search(r'(?<=clever )(.\w+)' abc)
dictionary[search][again]={}
number = 56
dictionary[search][again]={number}
and so when you want to find your specific dictionary after running the program:
dictionary["teacher"]["student"]
you will get
>>>'56'
This is what i mean to