I am very new to python but I have this idea in mind. I'd like to create an AI fantasy name generator. I've got a simple one, generating random strings of 3-11 letters, and my idea is: I get a word and decide if it's acceptable (Bggtrkl isn't, while Koerth might be), and in this process I build a dataset on which I'd base the machine learning. My question is - is it possible? If so - where do I begin? What to learn? I am open to any suggestion / advice.
Thank you.
Yes it is possible - the key is to decide the criteria of what is acceptable input. So a first step is to make some rules about what a name is. Everything has to has some kind of boundary or limit which as the coder you'd have to determine because really any combination of letters/numbers/symbols at all could make an acceptable name to someone. This is why in machine learning people are employed to get data from all over to find a pattern to start with.
Then in python these rules translate into the conditions you need to process the input.
(...added...)
There is also the aspect that a name can be recognised according to the context it is in, eg could recognise a word is a name if it only occurs if referring to a person. Once that pattern is determined then the person could be another object such as an organisation or item. Then it is about the patterns in language grammar. At the start I would focus on that aspect of program design and practice coding how to process the input to fit the original pattern with all the basic data structures available. Then research machine learning, AI, NLP - natural language processing to see how to extend my basic code. So to begin - design first.
import time
import random
print ("Welcome to this random name generator")
stop = 0
while True:
while True:
question = input("Are you male or female?\n")
if question == "male":
names = ["Dimah","John","Zack","Max","Mattihas","Roy","Don","Liam","William","Noah","Oliver","Elijah","James","Benjamin"]
break
if question == "female":
names = ["Delia","Laura","Layla","Elizabeth","Olivia","Emma","Ava","Joann"]
break
print("Please enter a valid answer")
lastnames = ["Hoosenator","Maloroda","Yu","Smith","Jones","Williams","Brown","Davis","Miller","Wilson","Chan"]
time.sleep(1)
print("Your name is " + random.choice(names) + " " + random.choice(lastnames))
while True:
again = input("Would you like to generate again?\n")
if again == "yes":
break
if again == "no":
stop = 1
break
print("Please enter a valid answer")
if stop == 1:
print("Thank you for using this random name generator, I hope you are satisfied with it. See you next time!")
break
Related
I am new to python and may have been overly optimistic about the first project I want to tackle. I want to create a program that will help me allocate my checks(I have a banking app this is just for fun lol). I also want this to be a continuous program so it will check to see if there is a 'SavedData.txt' file and if there is it will present all the starting balances in 3 accounts from the last time it was used. Then continue to ask questions to allocate into said accounts from the new check. However, if the file doesn't exist I want it to create it, ask questions and then save the inputs to be called upon the next time it is run.
Here's what I have:
'If the file does not exist ask this prompt'
month = input("Please enter month: ")
day = input("Please enter the day: ")
year = input("Please enter the year: ")
initial_checking = int((input("What is your initial checking account balance?: ")))
initial_savings = int((input("What is your initial savings account balance?: ")))
initial_fun = int((input("What is your initial fun account balance?: ")))
current_check = int((input("What is your check amount?: ")))
save_cont = int(input("How much would you like to contribute to savings?: "))
fun_cont = int(input("How much would you like to contribute to fun account?: "))
current_check = int((current_check - save_cont) - fun_cont)
print("Remaining check balance is " + str(current_check) + ".")
def main():
while True:
q = input("Would you like to put the rest in checking?(Type Y/N): ")
if q in "yY":
global initial_checking
global initial_savings
global initial_fun
global current_check
initial_checking = int(initial_checking + current_check)
print("Your new checking balance is " + str(initial_checking))
return
elif q in "nN":
print("Error! You must contribute your entire check!")
else:
print("You must enter (y/n).")
return
main()
After this is where I start to have issues. If the file does exist, or if the program has been run before, I want it to read the last input and display "This is your current checking account balance: $" and so on and so forth. I then want the same contribution questions to be asked and added to the current balance amount for each respective account. Doing research I have seen when doing something like 'file1 = open("SavedData.txt", "a+") ' will open and append the file. My issue is figuring out how to set up running the check for the file, opening, reading it, adding to it, or creating it then writing, and saving it.
My apologies if there is redundant information or if it looks extremely sloppy as I said I am very very new and may have been overly optimistic about doing this project. I appreciate your time and responses.
As it is your first project I would suggest learning good design from the start. So try to plan out what you have to do first, what components will be needed and how will they interact (you can use sticky notes or whatever you like but have a plan before you start coding), as it will help you define classes/functions when you will be actually writing code.
So for now you nicely define the things you need to do, so do them one by one testing each step.
As of your question about file manipulation first start by writing function that opens a file and read it, as of now using with statement is good practice instead of manually opening and closing files, you can read more here and here.
Then try to write part of your code that defines what should be added to file (I'm not really sure how checks work so I can't help you here).
And when you know what you want to add create a function that will write to the file, it will be similar to reading so you can again refer to previously mentions links.
Finally if everything above is done you can try to enclose it in a loop that will constantly monitor the file. Probably the best approach would be to use already created library like watchdog but if you want to learn how filesystem works it is fine to create custom solution.
Last tip, try to avoid global variables ;P
im kinda noob in programming. i want to save my daily study topics in a list, my code has topic number limitation(in range(3)) but i don't understand how to do it without number limitation.Any suggestion?
topics = []
for todays_topic in range(3):
topics.append(input("inter here>> "))
print(topics)
I'm not sure about your question but I'm guessing that you want to add your todays_topic to your list continuosly until you want to stop. It is better to use while loop instead of for loop. Use while True and keep adding elements. Take a variable and ask whether you want to enter more. If yes then continue, if no, then break the loop. Your code:
topics=[]
while True:
todays_topic=input("Enter here>> ")
topics.append(todays_topic)
asc=input("Enter more?? Y/N: ")
if asc=="N"
break
My task is to: Create a simple program (using Google Forms > Google Sheets > Zapier > Email) that I could use to ask 10 questions to someone, and based on results, would then generate a report to give them.
I have everything figured out except the python part of Zapier, in which I am using if statements to generate the report based on their answers to specific questions. I have made a mock-up with the questions "How are you feeling?" and "What is your favourite food?" to test if it works. I cannot, for the life of me, figure out how to output the variables into the email. What am I supposed to do? I've tried using return{} but that doesn't seem to work, giving me the wrong variables for some reason. Here's my code:
feeling=input_data
favFood=input_data
feelingReport=()
foodReport=()
if feeling == "happy":
feelingReport = ("its nice you're happy")
elif feeling == "sad":
feelingReport = ("its bad you're sad")
elif feeling == "excited":
feelingReport = ("its nice you're excited")
elif feeling == "scared":
feelingReport = ("its bad you're scared")
if favFood == "pizza":
foodReport = ("pizza is my fav too")
elif favFood == "sushi":
foodReport = ("sushi is ok i guess")
elif favFood == "burgers":
foodReport = ("i hate burgers")
output = [{'feelingReport': feelingReport, 'foodReport': foodReport}]
You can use the output statement to use the values in the next step
output = [{'feelingReport': feelingReport, 'foodReport': foodReport}]
In the image below, you can see how the values can be used in the next Zap:
Also, if the newest values aren't being pulled in, try clicking on the Refresh Fields button at the end of the Zap.
(---added the below answer after further investigation in the comments---)
Variables from the previous Zap should also be accessed through the input_data object. For example say that you used the variables data1 and data2. You should then be accessing those variables in the code like this:
feeling=input_data["data1"]
favFood=input_data["data2"]
Here's a screenshot:
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':
First of all i would like to apologize since i am a beginner to Python. Anyway I have a Python Program where I can create text files with the general form:
Recipe Name:
Item
Weight
Number of people recipe serves
And what I'm trying to do is to allow the program to be able to retrieve the recipe and have the ingredients recalculated for a different number of people. The program should output the the recipe name, the new number of people and the revised quantities for the new number of people. I am able to retrieve the recipe and output the recipe however i am not sure how to have the ingredients recaculated for a different number of people. This is part of my code:
def modify_recipe():
Choice_Exist = input("\nOkaym it looks like you want to modify a recipe. Please enter the name of this recipe ")
Exist_Recipe = open(Choice_Exist, "r+")
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like "))
I would recommend splitting your effort into multiple steps, and working on each step (doing research, trying to write the code, asking specific questions) in succession.
1) Look up python's file I/O. 1.a) Try to recreate the examples you find to make sure you understand what each piece of the code does. 1.b) Write your own script that accomplishes just this piece of your desired program, i.e. opens an exist recipe text file or creates a new one.
2) Really use you're own functions in Python particularly with passing your own arguments. What you're trying to make is a perfect example of good "modular programming", were you would right a function that reads an input file, another that writes an output file, another that prompts users for they number they'd like to multiple, and so on.
3) Add a try/except block for user input. If a user enters a non-numeric value, this will allow you to catch that and prompt the user again for a corrected value. Something like:
while True:
servings = raw_input('Please enter the number of servings desired: ')
try:
svgs = int(servings)
break
except ValueError:
print('Please check to make sure you entered a numeric value, with no'
+' letters or words, and a whole integer (no decimals or fractions).')
Or if you want to allow decimals, you could use float() instead of int().
4) [Semi-Advanced] Basic regular expressions (aka "regex") will be very helpful in building out what you're making. It sounds like your input files will have a strict, predictable format, so regex probably isn't necessary. But if you're looking to accept non-standard recipe input files, regex would be a great tool. While it can be a bit hard or confusing skill to learn, but there are a lot of good tutorials and guides. A few I bookmarked in the past are Python Course, Google Developers, and Dive Into Python. And a fantastic tool I strongly recommend while learning to build your own regular expression patterns is RegExr (or one of many similar, like PythonRegex), which show you what parts of your pattern are working or not working and why.
Here's an outline to help get you started:
def read_recipe_default(filename):
# open the file that contains the default ingredients
def parse_recipe(recipe):
# Use your regex to search for amounts here. Some useful basics include
# '\d' for numbers, and looking for keywords like 'cups', 'tbsp', etc.
def get_multiplier():
# prompt user for their multiplier here
def main():
# Call these methods as needed here. This will be the first part
# of your program that runs.
filename = ...
file_contents = read_recipe_file(filename)
# ...
# This last piece is what tells Python to start with the main() function above.
if __name__ == '__main__':
main()
Starting out can be tough, but it's very worth it in the end! Good luck!
I had to edit it a couple times because I use Python 2.7.5, but this should work:
import time
def modify_recipe():
Choice_Exist = input("\nOkay it looks like you want to modify a recipe. Please enter the name of this recipe: ")
with open(Choice_Exist + ".txt", "r+") as f:
content = f.readlines()
data_list = [word.replace("\n","") for word in content]
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like: "))
print data_list[0]
print data_list[1]
print int(data_list[2])*ServRequire #provided the Weight is in line 3 of txt file
print ServRequire
modify_recipe()