Trying to create a simple form in python with user input - python

I am a newbie to Python, and trying to create an input form using a nested dictionary with the following flow, but really struggling to cope with how to code having multiple values (as a list) that can be associated per topic within the dictionary:
Steps
Ask the user to input a topic / issue which is stored in an empty dictionary
Immediately after entering a topic / problem, prompt user to enter an action to resolve the problem, associate it with a due date entered by the user to complete by, and then linked to the topic / issue (key) created in step 1 as value to that key
Prompt user to add another action to the same topic if required with y/n or move to add another topic
add another topic / issue if required
print the dictionary with the topic / issues (keys) and associated values or multiple values with due dates.
Note I have not added due dates, and code to loop through the completed dictionary to list problems / actions with the due dates to amend, delete or change.
Any help really appreciated!! :)
here is a sample of my incomplete code:
problems = {}
problems_open = True
actions_open = True
while problems_open:
issue = input("\nPlease enter a topic / problem? ")
while actions_open:
action = input("What action are you going to take for this topic? ")
problems[issue] = action
repeat = input("Would you like to add another action y/n?")
if repeat == 'n':
actions_open = False
""" This is not appending multiple actions to the dictionary problems, just the
last entry """
""" Not sure how to add a due date to each action """
repeat = input("Would you like to add another topic / problem? ")
if repeat == "n":
problems_open = False
print("\n--- List of problems and actions with dates ---")
for issue, action in problems.items():
print("The problem: " + issue + " has " + "the following actions: " + action)

The problem in your code were the nested lists. The problem with nested lists is, that you can't iterate through them with numbers. That means to identify the specific value in the list would be very difficult.
The solution is to use lists (the ones with the square brackets).
I made a working code for your problem:
problems = []
actions = []
problems_open = True
actions_open = True
offset = -1
while problems_open:
issue = input("\nPlease enter a topic / problem? ")
problems.append(issue)
while actions_open == True:
action = input("What action are you going to take for this topic? ")
actions.append(action)
actions_open = False
repeat = input("Would you like to add another topic / problem? y/n ")
if repeat == "n":
problems_open = False
elif repeat == "y":
problems_open = True
actions_open = True
print("\n--- List of problems and actions with dates ---")
for problems, actions in zip(problems, actions):
print("The problem: " + problems + " has " + "the following actions: " + actions)
The only difference in this code is that you are not asked multiple times for taking another action on one problem again. I just made a working list for you. I hope it helped.

Related

Printing user output with while loop/beginner Python

hopefully there is a simple answer for this. How can I take user input from a while loop and print all of the input (without using lists when writing this)? Is there a way to output this information when the number of executions from the user is unknown? I am only a beginner so if there is a simple way to do this just using basics please let me know!
Here is an example of what I am trying to ask:
Say I am asking the user for the name and price of an item. They have the option to enter more items, or stop the execution. Then the output would list the name of the items, the prices, and their total amount purchased. I would like to print out all of these items that they have inputted.
Output formatted something like this:
Item Name Item Price
Soap $ 3.98
Detergent $ 6.99
Chips $ 2.50
....
....
Your Total: $xx.xx
I know how to do everything else, just having issues displaying all of their given input after they stop the execution. Just needing some guidance in this area. Please let me know if there is anything I can clarify. Thanks in advance!
I am using Python 3.
So I hope this matches what you were asking for.
I used nested dictionries, incase you want more info per item, but I mean you can also use tuples if you want.
prompts = ["Item name", "Item price"]
flag = True
items = {}
indx = 0
while flag:
inp = input("Type 'new' to register a new item or 'exit' to exit ")
if inp == "new":
output = {}
for p in prompts:
inp = input(p)
output[p] = inp
indx += 1
items[indx] = output
if inp == "exit":
flag = False
This is fairly simple, but to explain the steps;
Typing new allows you to start entering a new item.
It asks the prompts that are listed in the prompts list.
(It also uses these prompts to name the values in the output dict)
Once all the data is in, it'll be indexed and added into the items dict.
Then the loop begins again. You can add the new item, or type exit to stop entering items.
Edit:
Also I decided to use a flag instead of breaks so you can modify if you want more stop conditions.
I didn't understand so well but I think you can use:
bill = ''
total_price = 0
while True:
item = input('(If Done Write Exit) Item Name: ')
if item == "exit":
break
price = input("price: ")
bill = bill + "Item: "+item + '\nPrice: ' + price + '\n\n'
total_price += int(price)
print('\n'*4)
print(bill+'\n\nTotal Price:',total_price)

How to add an infinite amount of variables in Python

A little bit of context for this: I am going to be a junior in high school next year and I thought it would be cool to code some equations for things I would be doing in school. I have done equations for algebra (solving for x in the quadratic equation and such), and I thought it would be cool to create some code for chemistry. I'm trying to figure out how to balance equations, and I was thinking I could enter in all of the amounts and using a certain key (let's say space) it would continue to the next part of the chemical equation. Here is basically what I was thinking.
reac1_chem1 = input("Enter the first chemical: ")
reac1_amount1 = input("Enter the amount of " + reac1_chem1 + " atoms: )
reac1_chem2 = input("Enter the second chemical: ")
reac1_amount2 = input("Enter the amount of " + reac1_chem2 + " atoms: )
I want to continue this process until space is entered in as a chemical. How would I make this process infinite? Is creating variables the way to go or should I make a list? Any suggestions would be appreciated! Let me know if this was in any way confusing and I can try to clear it up for you. Thanks!
A dictionary would be great:
chemicals = dict()
index = 1
while True:
chemical = input(f"Enter chemical {index}: ")
if chemical == " ":
break
else:
chemicals[chemical] = input("Enter the amount: ")
index += 1
print(chemicals)
You could try to store the information in a dictionary of dictionaries, example as follows:
dct = {"ReactionNameOrID": {"ChemicalName1":"ATOMS", "ChemicalName":"ATOMS2"}}
You can then access the information like this:
dct.get("ReactionNameOrID").get("ChemicalName1")
#which will return: "ATOMS"
You could then use a class to store everything inside including the functions.
class Reactions():
#initialize the dictionary
def __init__(self):
self.dict_reactions = {}
#add a function to the class to add more reactions
def add_chemical(self):
reaction_name = input("Enter the reaction name/id: ")
dict_chemicals = input("Enter the chemicals + atoms as dictionary: ")
self.dict_reactions[reaction_name] = dict_chemicals
MyReactions = Reactions()
# Enter the reaction name/id: FirstReaction
# Enter the reaction name/id: {"H":100, "O":500}
MyReactions.add_chemical()
print(MyReactions.dict_reactions)
#{'FirstReaction': '{"H":100, "O":500}'}

Python Program counting and list question

I made a Python program to repeat the number of internships that I applied for, BUT I need it to store the amount I add so that I can ask it later how many I applied for, rather than me having to enter a number every time. Also, I want it to be able to update if the number of internships I applied for changes, I will input the new number of internships manually. How can I change my program to do that? Please take a look thanks
print("Welcome back, Ryan")
internships = {}
asking_ryan = True
amount = input("Enter how many internships you have applied for: ")
amount = int(amount)
if amount > 1:
print("You have applied for: " + str(amount) + " internship(s)")
str(amount)
if amount < 1:
print("Error! you cannot apply for 0 internships!")
if amount == 1:
print("You have applied for: " + str(amount) + " internship")
Program output:
Welcome back, Ryan.
Enter how many internships you have applied for: 2
You have applied for: 2 internship(s)
I saw your question. I kind of understand it.
You want to be able to update the internships you have done so you don't have to always rerun the program so it counts your internship?
You might have to use some files for that, should be simple!
First, you can make a file called opens.txt and add a 0 to the file that tracks how many times you opened that program. When you run the program do this:
opens = open("opens.txt", w+)
open_count = int(opens.read())
opens.write(open_count + 1)
if open_count == 1:
amount = input("Enter how many internships you have applied for: ")
... # Other Code
Then make a file called something like internships.txt where it will store how many internships you currently have, default it to 0.
internships = open("internships.txt", w+)
internship_count = int(internships.read())
print("You currently have applied to {} internships since last time...".format(internship_count)
new_internships = input("How many new internships have you applied for? ")
internships.write(internship_count + new_internships)
I think this should help? Haven't used files in a long time. Next time please phrase your question a bit better.

How do I make the for loop work only if one or more items != 'yes'

I'm working on a HW assignment where I create a fake club with entry questions. If any of the questions are answered with "no", then the person isn't allowed to join.
I've tried going back to the og lessons about lists and loops, but I can't find what I'm trying to do on there.
Here's my code so far.
# Purpose: Create a fake club that has certain requirements, ask user to
# fill out the application, and print out their answers + results.
def main():
display = input('Hi! This is your application to The Aqua Project...')
display2 = input('Read the following questions and just type y or n')
# Weird list format...
user = [input('Are you at least 18 yrs old? '),
input('Can you work with other people? '),
input('Do you like animals? '),
input('Are you okay with getting dirty sometimes? ')]
# Here's the problem, I want to print 'sorry you cant join' once...
for i in range(4):
if user[i] != 'y':
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
i += 1
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
main()
When you put a 'n' for some questions it says you can join, but for others it says you can't join. I don't know why sometimes it says you can when you placed a no in the interview, it shouldn't.
The usual ways to do this are a for loop with a break and an else clause:
for answer in user:
if answer != 'y':
print('Sorry')
break
else:
print('Congratulations')
Or the any() function:
if any(answer != 'y' for answer in user):
print('Sorry')
else:
print('Congratulations')
If one "no" means decline, you can add break to exit the loop after print decline info. Just like:
for i in range(4):
if user[i] != 'y':
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
# i += 1 # <<<<<<<<<<<<<<<<<< this code may be not needed here
break # <<<<<<<<<<<<<<<<<< where to add break
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
or you can use a variable to indicate whether to decline, just like:
toDecline = False
for i in range(4):
if user[i] != 'y':
toDecline = True
if toDecline:
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
There are a few ways to do this:
Use a flag variable and just output at the end. (Slightly inefficient if the first response is a no)
Use a flag variable and a while loop to exit as soon as the user responds with no. (Can be slightly confusing)
Use the builtin any method. (Can be confusing, not recommended)
flag = True
for i in range(4):
if user[i] != 'y':
flag = False # User has answered no to something, set the flag to false
if flag: # User has answered yes to everything
# <do your `yes` output>
else: # User has answered no to something
# <do your `no` output>
there are some small points in your code that need to be changed:
# Purpose: Create a fake club that has certain requirements, ask user to
# fill out the application, and print out their answers + results.
def main():
display = input('Hi! This is your application to The Aqua Project...')
display2 = input('Read the following questions and just type y or n')
# Weird list format...
user = [input('Are you at least 18 yrs old? '),
input('Can you work with other people? '),
input('Do you like animals? '),
input('Are you okay with getting dirty sometimes? ')]
# you define a variable inside function main
# and assign a list to it
# this variable will not be visible outside
# you should just return it
return user
# Here's the problem, I want to print 'sorry you cant join' once...
# call your function before you test the answer
# and assign the the result of the function to a
# variable you can use in your check
user= main()
# define a flag variabe to
# see if the answers are ok according your check
ok= True
for i in range(4):
if user[i].lower()[:1] != 'y':
# you could also use your original code
# in the check. The code above is an example
# how you could make sure the user can enter
# upper/lower case letters and also "yes"
# and "y" [:1] cuts off 1 character
# if the string is non-empty, otherwise it
# returns an empty string
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
i += 1
# memorize that some question wasn't ok
ok= False
# I guess here you might want to exit the loop?
# so use a break, otherwise the other answers
# would be checked as well and the message
# output several times per user in some cases
break
if ok:
# this code here doesn't belong in the loop body
# I guess. It should be executed after all questions
# have been checked positive (which is only known
# after the loop has been executed)
# So here we are sure the answers were yes, because
# otherwise we would have set ok to False
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at TheAquaProject.com')
justToShowInCMD = input('')
# if you call your function here, you can't check
# the result of the input() calls because
# by the time you check it it has not been entered
I would suggest storing your questions in a list and using a for loop to ask them. Store the user's response to another list and check if there is any "n" in this list. See code below:
questions = ["Are you at least 18 yrs old?", "Can you work with other people?", "Do you like animals?", "Are you okay with getting dirty sometimes?"]
answers = list()
for question in questions:
user_answer = input(f"[y/n] {question}: ").lower()
answers.append(user_answer)
if "n" in answers:
print("Sorry, you can't join our club.")
else:
print("Congrats! You are in!!")
# you can print your desired messages as well.
Assuming you are iterating 4 times (using range(4))based on the length of user, what you can simple do is the following:
if 'n' or 'no' in user:
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
You can modify the if condition to cater to other forms of negative answers like 'N' or 'No'. You don't need to iterate over user.
Comments on OP main():
A key point of programming, is code use efficiency.
Don't repeatedly call functions (e.g. input and print) when not necessary.
There are several ways your problem can be solved.
The other answers focus on your original user list, complete with repeatedly calling input
Once user executes, it essentially becomes a list of y and or n values, which you then unpack with a loop to check the values.
Another problem with the user list method, is it requires all of the questions to be answered, prior to disqualification. What if there were 40 questions? I'd be annoyed.
Incidentally, a list can be unpacked as follows: for value in user:. There is no need to address the list by index with python.
Updated main() implementation:
def print_list(values: list):
"""Print the values of a list"""
for value in values:
print(value)
def main():
"""Iterate through a questionnaire"""
# Variables at the top
intro = ['Hi! This is your application to The Aqua Project...',
'Read the following questions and just type y or n']
questions = ['Are you at least 18 yrs old? ',
'Can you work with other people? ',
'Do you like animals? ',
'Are you okay with getting dirty sometimes? ']
final = ['\nCongratulations, you have met all of our requirements!',
'We will send an email soon to discuss when our team',
'will meet up to help save some animals!',
'In the meantime, visit our website at www.TheAquaProject.com']
print_list(intro)
for i, question in enumerate(questions, start=1):
response = input(question)
if response == 'n': # can be replaced with != 'y'
print("Sorry, you can't join the club!")
break
if i == len(questions):
print_list(final)
Comments on updated main():
Instead of calling print a lot, store the text in a list and then call the print_list function to do the printing.
Keep custom functions separate
Custom functions should perform one function
values: list this is a type hint, which tells what data type the values parameter of print_list should be.
Annotations
"""""": use docstrings
Documenting Python Code: A Complete Guide
Double space between functions: How to Write Beautiful Python Code With PEP 8
main(): Defining Main Functions in Python
questions is obvious, it's just the questions from user, as a list without calling input
unpack questions with a for-loop and use the built-in function: enumerate.
There are many Built-in Functions
i goes with enumerate to count.
Other languages create a dummy variable, like count = 0, then use count+=1 to track loop iteration; this is considered not pythonic. Python uses enumerate, but only if you need a count for implementing something else.
if condition checks if response is n
If the if condition evaluates as True (e.g. when response = n, n == n is True), the user gets the sorry message, break, ends the loop, and the questionnaire is complete.
There are no nicities here, the function does not check to make certain a user enters y, it only checks for n. That wasn't in the scope of the question.
The start parameter of enumerate is set to 1. If all the questions are answered, i=4 and len(questions)=4 so i == len(questions) evaluates as True and the user gets the congratulations message.
len(questions) is used instead of 4, because it's a bad idea to hardcode in values like that, because then you have to remember you've done so. What if the number of questions changes? Then your if condition is broken.
Resources:
I'm not affiliated with RealPython, but they are a great source of incredibly in depth tutorials.
Lists and Tuples in Python
Basic Data Types in Python

How To Print Strings Between Integer Ranges - Python 3

I'm very new to Python and programming in general, so excuse me if the code is terrible and the problem rather easy to solve.
I have written code to allow a user to have employee data printed based on 3 different inputs, which they are allowed to choose from.
The options the user has available to them are to pick employees based on their payroll number; a minimum and maximum salary range; their job title.
I made two functions for the formatting. The first one turns the lines of the text file into lists, then the second function grabs those individual lists and formats them.
Then the code requests the user to input the file name. If the file cannot be found, they get to try again. If it is correct, the file is loaded and then runs through the functions to print out a neat table.
Then the user is asked what method they want to choose from to select specific employees. They are given 4 options, 3 are mentioned at the start and the fourth is to just end the program.
I managed to successfully get the first option to print out the employees without hassle, as is the same for the fourth option to end the program. I almost have the third one completed, I just need to find a way to print the name without a comma. My problem resides within the second option: how do I print the employees and their details if they fall between the minimum and maximum salary ranges entered by the user if the range isn't an integer since it has to include a '£' sign?
Here's the code. It's the biggest chunk in the program because I just have no clue how to make it work properly -
def detailsPrint(field) : #takes tuple and prints
print("{:30}" "{:6}" "{:15}" "{:7}".format(field[3] + ", " + field[4], field[0], field[2], "£" + field[1]))
if display == 2 :
maxSalary = "£1000000"
minpay = input("Enter the minimum pay : ")
maxpay = input("Enter the maximum pay : ")
if len(minpay) and len(maxpay) < maxSalary :
for s in employeeList :
if s[1] >= minpay :
detailsPrint(s)
The outcome should be something like (example) Simpson, Bart 12345 Consultant £55000 if the minpay were to be £50000 and maxpay £60000
edit: Managed to get it working. Here's the code
if display == 2 :
x = False
maxSalary = 1000000
minpay = int(input("Enter the minimum pay: "))
maxpay = int(input("Enter the maximum pay: "))
if int(minpay) > int(maxSalary) or int(maxpay) > int(maxSalary) :
x = False
print("No employees earn over £1000000. Try again.")
if int(minpay) or int(maxpay) < int(maxSalary) :
for s in employeeList :
if int(s[1]) >= minpay and int(s[1]) <= maxpay :
detailsPrint(s)
x = True
if x == False :
print("No employees could be found within that range. Try again")
print("\n")
Simplest solution: don't ask for the £ char ;-)
A solution that work with your requirement is to change the line
if len(minpay) or len(maxpay) > maxSalary :
with something like
if int(minpay[1:]) > int(maxSalary[1:]) or int(maxpay[1:]) > int(maxSalary[1:]) :
which check the numeric value of the strings (your condition seems wrong anyway to me)
You could replace all "£" signs to "" in a string.
YourString.replace("£", "")

Categories

Resources