How to add a name for editing in input?
New name
name = input("New your name : ")
print(name)
New your name :
How to add a name for editing ? (edit the name Charles)
something like
edit = "Charles"
name = input("Edit your name : " + edit)
print(name)
Edit your name : Charles
Thank you to help..
If your Python was compiled with readline support, you can actually do it using only the standard library:
import readline
def make_pre_input_hook(default):
def pre_input_hook():
readline.insert_text(default)
readline.redisplay()
return pre_input_hook
readline.set_pre_input_hook(make_pre_input_hook('Charles'))
name = input('Edit your name: ')
print('You are now called {}.'.format(name))
Note that with Python 2, you'd need to use raw_input instead of input.
I don't think there is any way to do this with just the command line. Instead, I suggest providing some default value in parentheses, and using that in case the user does not enter any input. This is also much more common and requires fewer keystrokes from the user in case he wants to change the default (no need to delete).
>>> name = input("Enter name (some default): ") or "some default"
Enter name (some default):
>>> name
'some default'
>>> name = input("Enter name (some default): ") or "some default"
Enter name (some default): foobar
>>> name
'foobar'
Here, the or "some default" has the effect that if the first part of the expression -- the result of input -- is empty, then the second part, i.e. the default value, is used.
How about:
defaultname = 'Charles'
nameprompt = 'Enter your name, or just press Return to accept the default name.\nDefault Name: '+defaultname
name = input(nameprompt)
if name == '':
name = defaultname
Related
I tried to write a script that replaces Hotmail address with Gmail if found in the input, but there is something wrong with the function I think. There is no syntax error but the result just does not output the replaced Gmail domain but the same Hotmail one.
old_email = "hotmail.com"
new_email = "gmail.com"
email = input("Enter email: ")
def replace_domain(email, old_email, new_email):
if "#" + old_email in email.endswith:
index = len(old_email)
new = email[:-index]+ "#" + new_email
return new
return email
a = email
print(a)
Here's the fixed code and then I'll explain what I've changed:
old_email = "hotmail.com"
new_email = "gmail.com"
email = input("Enter email: ")
def replace_domain(email, old_email, new_email):
if email.endswith("#" + old_email):
index = len(old_email)
new = email[:-index] + new_email
return new
return email
a = replace_domain(email, old_email, new_email)
print(a)
First: There was no call to the function. I've added that to the penultimate line.
Second: endswith is a function. I've therefore changed that line so that the function is called with the old email domain.
Third: The # was being output twice, because it isn't removed in the :-index part and then a new one is added immediately afterwards.
I would also make some recommendations:
Fourth: a is not a descriptive variable name, which makes the code harder to read. Similarly, index and new are not ideal variable names. Words like new are best avoided as variable names, because they can easily clash with built-in names.
Fifth: I would consider changing the variable name old_email to old_domain instead. Same with new_email. This is a better match for the contents of that variable.
Example output:
Enter email: robson#hotmail.com
robson#gmail.com
Another example output:
Enter email: robson#aol.com
robson#aol.com
I'm not really sure why this autocorrect isnt working, but every time i try to use the Speller() function i get this error:
TypeError: '>' not supported between instances of 'str' and 'int'
and here is my code:
import time
from autocorrect import Speller
def main(consoleMode):
if consoleMode:
# beg fur input :D
inputVar = input("Console Mode input: ")
if Speller(inputVar.lower()) == "hi" or Speller(inputVar.lower()) == "hello" or Speller(inputVar.lower()) == "wassup" or Speller(inputVar.lower()) == "sup":
if name == None:
name = int(input("Hello!\nI'd like to get to know you.\nWhat's your name?\n> "))
if ("not" in Speller(name) and "tell" in Speller(name)) or ("not" in Speller(name) and "say" in Speller(name)):
print("Alright, I'll just call you Bob for now :)")
name = "Bob"
else:
print("Hey " + name + "!")
while True:
main(True)
edit: I also tried doing int(disisastringvariable) but it just doesnt even work as it also throws an error
you might want to check out the documentation for the autocorrect module the speller class inits signature is def __init__(self, threshold=0, lang='en'): So when creating an instance of the class and passing in a single argument it will assume you are passing in a threshold.
So calling Speller("something") will pass a string in that will be stored as the threshold. then on line 27 of the init method. if threshold > 0 this string will be compared to an int. Hence the error. Since you cannot do > between a string and an int.
I would suggest first read any documentation for this module. The example from the documenation suggest to use it like
>>> spell = Speller(lang='en')
>>> spell("I'm not sleapy and tehre is no place I'm giong to.")
"I'm not sleepy and there is no place I'm going to."
You are trying to pass the code you want to check to the Speller constructor.
Instead, you should create the object once, and then it is callable and checks input. Read the examples here: https://github.com/fsondej/autocorrect
import time
from autocorrect import Speller
my_speller = Speller(lang='en')
name = None
def main(consoleMode):
global name
if consoleMode:
# beg fur input :D
inputVar = input("Console Mode input: ")
if my_speller(inputVar.lower()) == "hi" or my_speller(inputVar.lower()) == "hello" or my_speller(inputVar.lower()) == "wassup" or my_speller(inputVar.lower()) == "sup":
if name == None:
name = input("Hello!\nI'd like to get to know you.\nWhat's your name?\n> ")
if ("not" in my_speller(name) and "tell" in my_speller(name)) or ("not" in my_speller(name) and "say" in my_speller(name)):
print("Alright, I'll just call you Bob for now :)")
name = "Bob"
else:
print("Hey " + name + "!")
while True:
main(True)
You also had a problem with the variable name being used before declaration - I think you want to have a global instance of this and use it in all calls to your main function.
I know this is not hard, but I keep getting either an undefined error or different errors, I tried everything I could think of to get the solution. I placed the input variables outside of the code and it worked partially. I'm only 3 weeks or so into my first computer science class. help is appreciated, please & thanks.
# function that prompts the user for a name and returns it
def user():
name = input("Please enter your name: ")
return name
# function that receives the user's name as a parameter, and prompts the user for an age and returns it
def userAge(name):
age = input("How old are you, {}? ".format(name))
return age
# function that receives the user's name and age as parameters and displays the final output
def finalOutput(name, age):
age2x = int(age) * 2
print("Hi, {}. You are {} years old. Twice your age is {}.").format(name, age, str(age2x))
###############################################
# MAIN PART OF THE PROGRAM
# implement the main part of your program below
# comments have been added to assist you
###############################################
# get the user's name
user()
# get the user's age
userAge("name")
# display the final output
finalOutput("name", "age")
You're not storing the values the user supplies, or passing them back to your function calls, here:
user()
userAge("name")
finalOutput("name", "age")
Change the above lines to:
name = user()
age = userAge(name)
finalOutput(name,age)
Correction 1:
Don't pass arguments with double quotes, that means you are passing a string literal to the function not actual value of variable.
for example, if you assign variable name as "Jhon" and you pass it to the function as userAge("name") means you are passing string literal "name" to userAge() not variable value "Jhon".
def printName(name):
print(name)
name = "jhon"
printName("name")
output: name
def printName(name):
print(name)
name = "jhon"
printName(name)
output: jhon
Better assign the return value to some Valerie and pass without double quotes as mentioned by #TBurgis.
Correction 2:
Syntax mistake in print statement. Correct syntax should be
print("Hi, {}. You are {} years old. Twice your age is {}.".format(name, age, str(age2x)))
To define a text and its title, usually I do:
Story="I was a good boy"
But I would like to create a function that allows the user to type a title for a text and keep the title outside the function, for further use.
Here what I created so far:
def create_text():
x=input("Text title: ")
y=input("Text : ")
x=y
return x
When I run the code:
>>> create_text()
Text title: Story
Text : I was a good boy
'I was a good boy'
And it's ok.
But when I type again the Text title outside the function, I get
>>> Story
Traceback (most recent call last):
File "<pyshell#349>", line 1, in <module>
Story
NameError: name 'Story' is not defined
How can I create a function that allows the user to specify title and words for a text, and keep them also outside the function?
Thank you in advance
You could try a dictionary.
def create_text():
x = input("Text title: ")
y = input("Text : ")
userinput = {x: y}
return userinput
Now, when you run it, you can reference the story by its user-provided name ('Story').
>>> userinput = create_text()
Text title: Story
Text : I was a good boy
>>> userinput['Story']
'I was a good boy'
You need the function to return the values you want to use outside of it:
def create_text():
_title = input("Text title: ")
_text = input("Text : ")
return _title, _text
_title and _text are local to the function and are not defined outside it's scope, so to use them make sure to use the return value (outside the function):
title, text = create_text()
# use 'title' and 'text' ...
You want to transform a user input text into a variable.
def create_text():
x=input("Text title: ")
y=input("Text : ")
globals()[x] = y
return x
Now:
>>> create_text()
Text title: Story
Text : I was a good boy
'Story'
>>> Story
'I was a good boy'
>>>
But, notice that normally this is not a good idea. You're letting
your program input (which usually you don't have control with) to mess
up with your global namespace, which might influence the workings of
the rest of your script and even of Python itself -- not let say that
putting things in globals() is almost always bad design.
Considering that, the approach offered in the other answers are better
options (specially the "return a dictionary" IMHO).
I have a project in python where I want to assign names for my classes in School downtown in the Michigan High School. The classes that I have are '1B, 2B and 3B', and when the user inputs their name and classroom name, their class will be validated to ensure it is correct in the specific format '1,2 OR 3', 'B' - so they cannot write '4B' or '2A' because those classes do not exist.
So far, I have developed this block of code:
while True: # This starts the whole of the while loop.
class_name = str(input("Please enter your class name >>"))
if re.match("1A" "2A" "3A", class_name):
print("Incorrect. Please write your class name again.")
else:
print("Your class name has been accepted")
How can I validate the class_name variable so it can match the classroom names '1A, 2A or 3A?' Thanks,
Taylor Hayward.
Your logic is backwards (and your syntax is wrong, too). You don't want to test for a set of illegal class names (that set is far too large) - you want to test against the set of legal names and repeat if the test fails.
while True: # This starts the whole of the while loop.
class_name = input("Please enter your class name >>") # str() is unnecessary
if class_name not in {"1B", "2B", "3B"}:
print("Incorrect. Please write your class name again.")
else:
print("Your class name has been accepted")
break # Exit the while loop
A regex would also be possible:
if not re.match("[123]B$", class_name):
Note the $ anchor to ensure that the match ends after B, otherwise input like 2BC would be accepted by the regex (re.match() only anchors the match to the start of the string, not the end).