Beginner question about making a program change based on user input - python

I'm trying to learn to code and decided to give myself a simple task. It's a madlib game (roses are..., ... is blue, etc..). I want to make the program change '... is blue' to '... are blue' based on use input. So if the use inputs 'my head' the program says 'my head is blue' instead of 'my head are blue.'
I've tried to implement this:
if thing in ['my','your']:
print(thing + " is blue")
else:
print (thing + " are blue")
However the programme only reads 'are' when 'my' or 'your' are written on their own. Is there a way to print something based on whether or not a word is present, not if a certain phrase or word is written?
colour = input ("roses are... ")
thing = input(" ... are blue")
love = input("I love ... ")
print("roses are " + colour)
if thing in ['my','your']:
print(thing + " is blue")
else:
print (thing + " are blue")
print("I love " + love)

You can check if a sub-string is in your list by doing:
if any(word in thing for word in ['my', 'your'])
pretty self explanatory:
it's a for loop that just returns true or false. it basically looks at your variable thing which is storing a string, checks if it's also within your list
So full code:
colour = input ("roses are... ")
thing = input(" ... are blue ")
love = input("I love ... ")
print("roses are " + colour)
if any(word in thing for word in ['my', 'your']):
print(thing + " is blue")
else:
print (thing + " are blue")
print("I love " + love)

Related

How can I fix this list problem (list index out of range)

I'm new to programming and trying to make a vocabulary test machine in python, and the problem I'm having is when you're restarting the test and trying to redo the wrong answers, the correct answers being inputted should be removed from the list which contains the wrong answers.
So basically, in beginning you are putting in custom vocabulary words and then answering them, if any words are incorrect they are put in a list, and when redoing the test, if they are correct this time they should be removed from the list. So at the end if you are answering the words correctly the list should be empty. But I am getting this error: IndexError: list index out of range
What do you suggest I should do?
(I translated the code from another language so if anything is not matching that's the reason)
import replit, sys, time, os
word = []
word1 = []
wordwrong = []
wordwrong1 = []
incorrect = 0
correct = 0
swedish = ""
print("Type: 'Stop' to stop")
while swedish.lower() != "stop":
swedish = input("\nType the word in swedish:")
if swedish.lower() != "stop":
word.append(swedish)
else:
replit.clear()
break
english = input("\nType the word in english:")
word1.append(english)
replit.clear()
print("Type: 'Stop' to stop")
for x in range(len(word)):
wordanswer = input("translate word " + "'" + word[x] + "'" + ":").lower()
replit.clear()
while wordanswer != word1[x]:
print("Incorrect answer! try again, " + str(2-incorrect) + " tries left")
wordanswer = input("translate " + "'" + word[x] + "'" + ":")
incorrect = incorrect + 1
replit.clear()
if incorrect == 2:
replit.clear()
incorrect = incorrect-2
wordwrong.append(word[x])
wordwrong1.append(word1[x])
break
else:
print("Correct answer!")
correct = correct + 1
incorrect = incorrect*0
replit.clear()
print("Your result:", correct, "/", len(word), "correct answers " +"(" + str(correct/len(word)*100)+"%)")
restart = input("\nTo restart; type 'restart':").lower()
correct = correct*0
incorrect = incorrect*0
restart = "restart"
while restart == "restart" and len(wordwrong) > 0:
for x in range(len(wordwrong)):
wordanswer = input("translate word " + "'" + wordwrong[x] + "'" + ":").lower()
while wordanswer != wordwrong[x]:
print("Incorrect answer! try again, " + str(2-incorrect) + " tries left")
wordanswer = input("translate word " + "'" + wordwrong[x] + "'" + ":")
incorrect = incorrect + 1
if incorrect == 2:
incorrect = incorrect-2
break
else:
print("Correct answer!")
correct = correct + 1
incorrect = incorrect*0
wordwrong.remove(wordwrong[x])
wordwrong1.remove(wordwrong1[x]) (here i am trying to remove the words that got corrected)
print("Your result:", correct, "/", len(word), "correct answers " +"(" + str(correct/len(word)*100)+"%)")
restart = input("\nTo restart; type 'restart':").lower()
As I can't comment yet:
I think the problem is that this
for x in range(len(wordwrong)):
loop is trying to go through all of the elements of wordwrong in
wordwrong.remove(wordwrong[x])
even though the size of wordwrong is changing and getting smaller each time
a word is removed from the list. I might be wrong though. I'll hope this helps you.
One immediate suggestion is that you're inputting Swedish words and their English equivalent, and then storing these in separate parallel lists. This is not wrong, per se, but frequently troublesome. You could store them as a list of tuples, or even better as a dictionary.
words = {}
while True:
print("Type: 'Stop' to stop")
swedish = input("Enter Swedish word: ")
if swedish.lower() == "stop": break
english = input("Enter English equivalent: ")
words[swedish] = english
Now, if you want to iterate over all of the Swedish words and their English equivalents:
for swedish, english in words.items():
...
If the user gets two attempts for each translation, and you want to track how many they translate correctly:
correct = 0
attempts = 2
for swedish, english in words.items():
correct_translation = False
for attempt in range(attempts):
translation = input(f"Translate Swedish word {swedish} to English: ")
if translation.lower() == english.lower():
correct_translation = True
break
elif attempt == attempts - 1:
print("Incorrect.")
else:
print("Incorrect. Try again.")
if correct_translation: correct += 1

How do I make a single word in a string a certain color

I am writing a print statement that prints a single word in the whole string as a different color. Does anyone know how I can do that? The method I am using prints only the highlighted word.
import random
def skyBlue(skk): print("\033[96m {}\033[00m" .format(skk))
lsubject = ["physics", "geology", "history", "algebra", "literature"]
subjectColor = skyBlue(random.choice(lsubject))
print("You study " + str(subjectColor) + ".")
You can just return the string that you have already formatted.
def skyBlue(skk): return "\033[96m {}\033[00m".format(skk)
subjectColor = skyBlue(random.choice(lsubject))
print("You study " + subjectColor + ".")

How to not display () and '

I'm running a file with 2 functions, it Works correctly but it display the following when I run it:
Enter your weight (in Kilograms): 81
Enter your height (in Centimeters): 175
Enter your age: 20
Enter 5 if you are a male or -161 if you are female: 5
('You have to consume between: ', 1447.0, 'and', 1537.4375, 'calories a day.')
Below is my code:
def calBurned(weight:float, height:float, age: int, genderValue:float)->str:
TMB = (10*weight)+(6.25*height)-(5*age) + genderValue
minCal = TMB*0.80
maxCal = TMB*0.85
text = "You have to consume between ", minCal, "and", maxCal, "calories a day."
return text
def calRec()->None:
weight = float(input("Enter the your weight (in Kilograms): " ))
height = float(input("Enter your height (in Centimeters): "))
age = int(input("Enter your age: "))
genderValue = float(input("Enter 5 if you are a male or -161 if you are female: "))
calRecom= calBurned(weight, height, age, genderValue)
print(calRecom)
calRec()
Is it posible to return just the text without the all the (',')?
Your text is a tuple. You can convert each of its items to a string and return the concatenation of them:
text = " ".join(map(str, text))
You can also build text as a string in the first place:
text = f"You have to consume between {minCal} and {maxCal} calories a day."
Last but not least, a function should not return formatted text; it should return the results of computations (minCal,maxCal). Formatting should be done by the caller.
Use:
text = "You have to consume between {} and {} calories a day.".format(minCal, maxCal)
In calcBurned you didn't concatenate the strings, rather you made it a tuple, in this line:
text = "You have to consume between ", minCal, "and", maxCal, "calories a day."
change all the commas (,) to pluses (+), and change minCal and maxCal to str(minCal) and str(maxCal), and it should work:
text = "You have to consume between " + str(minCal) + " and " + str(maxCal) + " calories a day."
Just change
text = "You have to consume between ", minCal, "and", maxCal, "calories a day."
to
text = f"You have to consume between {minCal} and {maxCal} calories a day."

How to recognize name (from text file) in user input and then print name

My ideal goal is for the chat bot to recognize that you are talking about one of your siblings. So, when you mention your brother or sister (either by name or the keywords: my brother/sister) the chat bot will already know who they are from the data given in their text file. I have already figured out the keyword part, but when I mention them by name (For example: I can't stand James). The chat bot doesn't print what I want it to and when the user tells the chat bot their sibling's name it ends up printing both ("Oh, so your brother's name is") and ("I'll make sure to remember that, so what about " + brother_status['name'] + "?"). What can I do to fix this problem?
I have already tried this, but this doesn't seem to work either:
import string
user_input = raw_input("Please enter your sisters name: ").translate(string.maketrans("",""), string.punctuation)
with open('file.txt') as sibling_database:
if len(user_input.split()) >= 2:
for line in sibling_database:
for word in line.split(':'):
for words in user_input.split():
if words in word:
print("Oh, so your brother's name is " + line.split(':')[1])
Also here is my original code (In case you want to make any other changes):
import string
brother_status = dict([
('name', ''),
('nickname', ''),
('current age', ''),
('relationship', '')])
brother_keywords = ["Brother", "brother"]
sister_keywords = ["Sister", "sister"]
def main():
while True:
user_input = raw_input("What type of sibling do you have: ").translate(string.maketrans("",""), string.punctuation)
for keyword in brother_keywords:
if keyword in user_input:
with open('file.txt', 'r') as sibling_database:
for brother_data in sibling_database:
if brother_data.startswith("Brother's Name"):
print (brother_data.split(':')[1])
return
break
if user_input.split():
with open('file.txt') as sibling_database:
for line in sibling_database:
for word in user_input.split():
if word in line:
print("Oh, so your brother's name is " + line.split(':')[1] * 1)
return
break
if user_input.split():
for keyword in brother_keywords:
if keyword in user_input:
if user_input not in brother_status:
with open ('file.txt') as sibling_database:
first = sibling_database.read(1)
if not first:
print ("You never mentioned a brother. What's his name?")
user_input = raw_input("What's his name: ")
brother_status['name'] = (user_input)
with open('file.txt', 'w') as sibling_database:
sibling_database.write("Brother's Name:" + brother_status['name'] * 1 + '\n')
print ("I'll make sure to remember that, so what about " + brother_status['name'] + "?")
continue
if __name__ == "__main__":
main()
Your bigger problem is managing the state of your program.
Everyloop; you are testing all of your if, and them being true will get executed all the time, which is not what you want.
I would suggest to not rush steps too quickly, for instance I don't think if not first: does what you expect.
One way to help organise and manage that state is to use functions. Use plenty of them!
Then I would suggest going piece by piece : you need to figure out under what conditions you want each question/answer to appear in your code. If you're asking about a brother you don't know, then probably the code that talks about an unknown brother shouldn't be in the place. Or should have condition to guard the code from executing.
You'll probably get to a point where you'll have conditions all over the place, when that happens (and not before, or for curiosity) you should check out "state machines".
Side notes about python 3 :
Python 2 is becoming obsolete in 2020 and should not be used anymore. Systems will not ship with them, and people are expected to use python 3, and support for python 2 will stop.
This is not to say you shouldn't continue using python 2 as a learning tool, but you should think about learning python 3, you'll get more help more easily. Also there's a few cool features that python 2 doesn't have and you wouldn't want to miss out on that^^
I have updated your code with nltk pos tags to extract out the names from text file. Try it:
import string
import nltk
nltk.download('maxent_treebank_pos_tagger')
brother_status = dict([
('name', ''),
('nickname', ''),
('current age', ''),
('relationship', '')])
brother_keywords = ["Brother", "brother"]
sister_keywords = ["Sister", "sister"]
def main():
while True:
user_input = raw_input("What type of sibling do you have: ").translate(string.maketrans("",""), string.punctuation)
for keyword in brother_keywords:
if keyword in user_input:
with open('file.txt', 'r') as sibling_database:
data = sibling_database.readline()
data = nltk.word_tokenize(data)
tagged_data = nltk.pos_tag(data)
for name, pos in tagged_data:
if pos == "NNP":
print(name)
return
break
if user_input.split():
with open('file.txt') as sibling_database:
for line in sibling_database:
for word in user_input.split():
if word in line:
print("Oh, so your brother's name is " + line.split(':')[1] * 1)
return
break
if user_input.split():
for keyword in brother_keywords:
if keyword in user_input:
if user_input not in brother_status:
with open ('file.txt') as sibling_database:
first = sibling_database.read(1)
if not first:
print ("You never mentioned a brother. What's his name?")
user_input = raw_input("What's his name: ")
brother_status['name'] = (user_input)
with open('file.txt', 'w') as sibling_database:
sibling_database.write("Brother's Name:" + brother_status['name'] * 1 + '\n')
print ("I'll make sure to remember that, so what about " + brother_status['name'] + "?")
continue
if __name__ == "__main__":
main()

This Python quiz is driving me crazy

I'm new to StackOverflow (1st time posting) and new to coding with python. Currently enrolled in a course through Udacity. I'm having a very hard time with a project we were given for this course and decided to come here to see if anyone could help.
The project is to create a quiz with 4 blanks that need to be answered correctly by the player. It's required to have the quiz print out with the correct answer, but I'm having a very hard time getting this to print out correctly.
My code is below. Would appreciate any help or advice I can get on this.
Thanks!
easy_quiz = "If you ever get stuck, check out the __1__ for common
problems students face when attempting this project. If you need
additional help, you can schedule a 1:1 appointment with one of our
__2__ to get you un-stuck. This project should be __3__. If at any time
it becomes not fun, take a step back, deep breath, and ask for __4__!.
\n\n"
easy_answers = ["forums", "mentors", "fun", "help"]
medium_quiz = "Game must have 3 or more levels and each level contains 4 or more __1__ to fill in. Immediately after running the program, user is prompted to select a difficulty level from easy / __2__ / hard. Once a level is selected, game displays a fill-in-the-blank and a prompt to fill in the first one. When player guesses __3__, new prompt shows with correct answer in the previous blank and a new prompt for the next blank. When player guesses __4__, they are prompted to try again. \n"
medium_answers = ["blanks", "medium", "correctly", "incorrectly"]
hard_quiz = "__1__ are used as __2__ to automate tasks which are likely to be repeated. Functions produce the appropriate output (typically with a __3__ statement) from the appropriate input (function parameters). Your code should take advantage of __4__ and variable names should reflect the values they store. \n"
hard_answers = ["Functions", "tools", "return", "variables"]
blanks = ["__1__", "__2__", "__3__", "__4__"]
difficulty = raw_input("\nChoose your difficuty level = easy, medium, or hard? ")
print ""
if difficulty == "easy":
quiz = easy_quiz
answers = easy_answers
print "You chose easy!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + easy_quiz
elif difficulty == "medium":
quiz = medium_quiz
answers = medium_answers
print "You chose medium!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + medium_quiz
elif difficulty == "hard":
quiz = hard_quiz
answers = hard_answers
print "You chose hard!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + hard_quiz
def word_in_pos(word, parts_of_speech):
for pos in parts_of_speech:
if pos in word:
return pos
return None
def play_game(quiz, parts_of_speech):
replaced = []
i = 0
quiz = quiz.split()
for word in quiz:
replacement = word_in_pos(word, parts_of_speech)
if replacement != None:
user_input = raw_input("Type an answer for: " + replacement + " " )
word = word.replace(replacement, user_input)
replaced.append(word)
guesses = 0
while user_input != answers[i]:
guesses = guesses + 1
print "Incorrect, try again \n" + " ".join(replaced)
user_input = raw_input("Type an answer for: " + replacement + " ")
if guesses == 4:
return "\nGame Over! Better luck next time. \n"
print "Correct \n" + " ".join(replaced)
i = i + 1
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
return replaced
print play_game(quiz, blanks)
Here is a working version of your play_game() method:
def play_game(quiz, parts_of_speech):
replaced = []
i = 0
quiz = quiz.split()
for word in quiz:
replacement = word_in_pos(word, parts_of_speech)
if replacement is not None:
user_input = raw_input("Type an answer for: " + replacement + " " )
guesses = 0
while user_input != answers[i]:
guesses = guesses + 1
if guesses == 5:
return "\nGame Over! Better luck next time. \n"
print "Incorrect, try again \n" + " ".join(replaced) + " " + replacement
user_input = raw_input("Type an answer for: " + replacement + " ")
replaced.append(user_input)
print "Correct \n" + " ".join(replaced)
i = i + 1
else:
replaced.append(word)
replaced = " ".join(replaced)
return replaced
The main change is to delay modifying the replaced list until the correct answer has been given. That simplifies a lot of the code, eliminating the need for the word variable.

Categories

Resources