name = ""
name = input("Hi there, what is your name? ")
while name.isalnum():
name = input("Hi there, what is your name? ")
while name.isdigit():
name = input("Hi there, what is your name? ")
This is what the code looks like, but I only want it to accept letters only. When I run this code however, there is a problem and the program keeps asking for the user's name for any input provided, the only way the program continues is if a 'space (bar)' is pressed. What is wrong with this?
while name.isalnum():
Means that the loop will keep running as long as name is alphanumeric. You want:
while not name.isalnum():
Your goal can be better achieved through regex:
import re
p=re.compile(r'[a-zA-Z\s]+$')
name="user0000"
while not p.match(name):
name = input("Hi there, what is your name? ")
This will accept names like "George Smith" but not "Smith1980"
Related
My code works fine for the salesperson to enter the following criteria until the file is created with one list after being prompted to continue or quit writing the .txt file.
def write_text():
print("Welcome to a Costco Hotel Text Creator.")
print('-'*20) #This serves no purpose but to make the terminal look cleaner.
new_file = input("Enter a new file name: ")
while True: #In the loop where the sales person must enter the following criteria for the new text.
with open(new_file, "w") as f:
f.write(str(input("Enter a member's name: ")))
f.write(str(";")) #Makes it easier and logical to seperate the text by semicolon.
print("The members services are: ")
services = ['Conference','Dinner','Lodging','Membership Renewal']
for service in services:
print(f"{service.capitalize() : <14}") #Capitalizes the string, but not allowed to type exactly.
f.write(str(input("Enter the hotel services. Type exactly shown: ")))
f.write(str(";")) #Makes it easier and logical to seperate the text by semicolon.
f.write(str(input("Enter the price: ")))
f.write(str(";")) #Makes it easier and logical to seperate the text by semicolon.
f.write(str(input("Enter the full date (MM/DD/YYYY): ")))
print('-'*20) #This serves no purpose but to make the terminal look cleaner.
exit = input("Are you done writing the text file? If yes, please type 'yes' to exit")
if exit == 'yes': #If the person typed 'no' then it exits before entering the sales system.
print("Exiting the saved file.")
break
write_text()
My result:
Sammy;Conference;20.00;09/25/2022
Expected result:
Sammy;Conference;20.00;09/25/2022
Johnny;Conference;25.00;09/25/2022
Tony;Conference;30.00;09/25/2022
The list goes on until the user can enter 'yes' to quit. I already have the function that allows reading the text file to sum the revenue per category. Any help and advice is appreciated. Thank you!
When you use with open(...) as .. it closes the file as soon as you exit the code block, and since you are using the w file mode you are overwriting your previous entries every time your loop goes back to the top. You also don't need to wrap input statements with str(). The return value of input will always be a string.
One solution would be to simply put the while true loop inside of the the with open( ) block. You will also need to add a line break at the end of the loop.
def write_text():
print("Welcome to a Costco Hotel Text Creator.")
print('-'*20) # This serves no purpose but to make the terminal look cleaner.
new_file = input("Enter a new file name: ")
with open(new_file, "w") as f:
while True: # In the loop where the sales person must enter the
f.write(input("Enter a member's name: ") + ";")
print("The members services are: ")
services = ['Conference','Dinner','Lodging','Membership Renewal']
for service in services:
print(f"{service.capitalize() : <14}") # Capitalizes the string, but not allowed to type exactly.
f.write(input("Enter the hotel services. Type exactly shown: ") + ";")
f.write(input("Enter the price: ") + ";")
f.write(input("Enter the full date (MM/DD/YYYY): ") + "\n")
print('-'*20)
exit = input("Are you done writing the text file? If yes, please type 'yes' to exit")
if exit == 'yes': # If the person typed 'no' then it exits before entering the sales system.
print("Exiting the saved file.")
break
write_text()
You can also combine the ";" with the text from the input statement to cut back on calls to write. This also makes it look cleaner and more readable as well.
You could also just use the a/append file mode, but closing and reopening the file over and over again doesn't seem like the better option.
Update
If you want to verify that the user input matches a certain word you can do something like this, lets say you want to validate that the user input one of the listed services correctly
print("The members services are: ")
services = ['Conference','Dinner','Lodging','Membership Renewal']
for service in services:
print(f"{service.capitalize() : <14}") # Capitalizes the string, but not allowed to type exactly.
while True:
response = input("Enter the hotel services. Type exactly shown: ")
if response in services:
f.write(response + ';')
break
else:
print("Incorrect entry please try again.")
I would recommend taking this functionality and putting it into a separate function so that you can apply the logic to all of your input statements.
So basically, what I'm trying to do is to create a menu that allows me to modify the contents of a text file. It's supposed to look like this:
Question 1
I think I already know how to create the menu, as shown here:
print("User Management")
print("1.Add new record")
print("2.View all record")
print("3.Search record")
print("4.Exit")
option = int(input("Enter your choice: "))
if option == 1 :
The problem I have I have no idea how to correlate the options to the commands. For example, if I wanted to correlate this:
name = input("Please enter your name:")
email = input("Please enter your email address:")
f = open("user.txt","a")
f.write("\n"+name+","+email)
f.close()
print("Record added."))
to 1 so whenever I input 1 in the "Enter your choice" it allows me to add a name and email address to the text file, etc. Here's an example I can find:
Example
I have been told that using the if and elseif functions allows me to do that, but I have no idea how. I'm quite new to Python, so forgive me if I seem ignorant. Any help will be appreciated.
You're right in that using a conditional (the fancy technical term for if/elseif/else) is the way to do that. Assuming that the text you have included in your question is accurate, it's likely that you haven't indented the code that is meant to be in the if block.
Python uses indentation (that is, spaces or tabs) to indicate what code is within each control structure. So in your example, if you want to only execute the second block of text if option == 1 you would want:
print("User Management")
print("1.Add new record")
print("2.View all record")
print("3.Search record")
print("4.Exit")
option = int(input("Enter your choice: "))
if option == 1 :
name = input("Please enter your name:")
email = input("Please enter your email address:")
f = open("user.txt","a")
f.write("\n"+name+","+email)
f.close()
print("Record added."))
For more on using if and other control flow, see the tutorial here.
So I am using Jupyter notebook and when I run the code
name = input(print('What is your name?'))
The code will produce the output:
What is your name?
None []
Since I cant copy and paste the rectangle that comes when using the function input(), lets asume the brackets represent that rectangle. Then say you write John Doe in the box, it will then show NoneJohn Doe Why is the word None shown next to the name and the box? How do you remove it? Thanks
I believe you want to prompt the user to type his/her name and then print out the name?
if so, try this:
name = input('What is your name?')
print('Your name is '+ name)
Also with this in mind.
Input takes a prompt string as its argument, which it will print automatically, but print returns None; it is this that gets printed by input. Your code is equivalent to:
name = print(...) # prompt == None
ans = str(input(name))
Instead, use str.format to build the prompt and pass it straight to input
I've basically made a def function to ask user's name with the input
but when I tried to make an input to get the user's name accordingly, I came to realise that each input has to be assigned individually so as to later print that input linked according to what the user inserted their name.
## Ask user's name with the use of def function.
def asking_username():
print("What's your name? ")
username = input()
return username
print("Hello, " + asking_username().title() + "!")
The code above that I made has no problem, but I'd like to make the input to get an user insert in the same line as the print("What's your name? ").
How do you individually assign each input so that it does not get confused with the other input in case multiple inputs are inserted?
How about:
username = input("Enter your name\n")
This works, because I'm using the newline character ("\n").
So, basically, this is my code:
import random
import os
answer = input('What is the problem with your mobile phone? Please do not enter more than one sentence.')
print('The program has detected that you have entered a query regarding: '
if 'wet' or 'water' or 'liquid' or 'mobile' in answer:
print('Put your mobile phone inside of a fridge, it sounds stupid but it should work!')
What I want to know is, say for example if the user enters the keywords 'wet' and 'mobile' as their input, how do I feed back to them knowing that my program has recognised their query.
So by saying something like 'The program has detected that you have entered a query regarding:' how do I filter their keywords into this sentence, say, if they entered 'My mobile phone has gotten wet recently', I want to pick out 'mobile' and 'wet' without saying:
print('The program has detected that you have entered wet')
Because that sounds stupid IMO.
Thanks
If I understand your question correctly, this should solve your problem. Just put the print statement inside the if condition! Very simple, I guess :)
import random
import os
answer = input('What is the problem with your mobile phone? Please do not enter more than one sentence.')
if 'wet' or 'water' or 'liquid' or 'mobile' in answer:
print('The program has detected that you have entered a query regarding: water') # or anything else wet or whatever
print('Put your mobile phone inside of a fridge, it sounds stupid but it should work!')
You can do that with a tuple, a list and any function:
SEND_REPORT_TUPLE = ('wet', 'water', 'liquid', 'mobile')
#make a list from the input
input_list = answer.split(" ")
#And then the use any function with comprehension list
if any(e in SEND_REPORT_TUPLE for e in input_list):
print("The program has detected a query...")