I'm really new to Python and I'm mainly just messing around. I'm trying to put together a function that validates a user input (in my case, to check wether the user writes either James or Peter. This is probably a very newbie question, but I was just wondering if my code is a good way to accomplish this function.
Thanks for any help.
namelist = "Peter", "James"
def nameinput():
global name
name = raw_input("Write a name. ")
def checkname(x):
while name not in namelist:
print "Try again"
nameinput()
else:
print "Good,", name
checkname(nameinput())
if name == "Peter":
print "This is a text for Peter"
elif name == "James":
print "This is a text for James"
No; there is no reason to use global variables here. Pass data around to the functions that need it.
def nameinput():
return raw_input("Write a name. ")
def checkname(name):
namelist = ["Peter", "James"]
while name not in namelist:
print "Try again"
name = nameinput()
else:
print "Good,", name
return name
name = checkname(nameinput())
Using global variables is generally frowned upon (it can really do stupid stuff if you don't always know what you are doing), so don't start doing so that early.
You could easily avoid that by returning the name from nameinput.
Also, you already have the name list. Do the following in the end:
if name in namelist:
print("This is a text for " + name)
Related
I need to check whether the input is empty or not and cannot use if statements.
print("What is your name?")
name = input()
print("Hi, {}".format(name))
Use a while loop that only terminates if the length of name is 0:
name = ""
while len(name) == 0:
print("What is your name?")
name = input()
print("Hi, {}".format(name))
You could try something like this:
print("What is your name?")
name = input()
name = "Hi, {}".format(name)
while name == "Hi, ":
name = "You didn't key in any name"
print(name)
This is ugly, but it will produce the exact output you want.
The idea is to use a loop that will run only once, and will only run if the name variable is empty after input() is called.
I would recommend assert. It will stop your programming to continue running when the requirement is not met.
print("What is your name?")
name = input()
assert name != "", "You didn't key in any name"
print("Hi, {}".format(name))
What is your name?
AssertionError: You didn't key in any name
As my previous answer with the while loop received some criticism, I decided to demonstrate a less "naive" but perhaps more complicated solution, that actually does not use any kind of direct conditional operator:
print("What is your name?")
name = input()
answer = {}
answer[len(name)] = "Hi, {}".format(name)
answer[0] = "You didn't key in any name"
print(answer[len(name)])
Here we rely on a dictionary with the length of the input as an integer key.
We don't even need to compare the length to 0, we just overwrite the 0 key with the error message.
If input length is greater than 0, the name will be under its own key, and will be printed, if not, the empty "Hi" string will be replaced.
Would this ever be useful in the real world?
Probably not, unless there are many more than 2 options.
Does it comply with the task requirements?
Yes. It gives the desired output.
Why does my program return "function name at 0x3424243" whenever I call my defined function?
To let you know that 3424243 isn't the actual number, but either way it shows a very random number, whenever I call my defined function.
My code:
print("WELCOME!")
name = input("\nWhat is your name? ")
print("\nHello " + name + "!")
def name():
print(name)
print("\nGoodbye", name)
How can I fix this so that it says goodbye to the name I typed in. The code above generates "Goodbye, function name at 0x3424243>"
Don't use the same name for the input variable and the function.
First:
name = input("\nWhat is your name? ")
Will run and name will point to the input string.
When:
def name():
Is evaluated name will start pointing to the function instead of the input string.
Modify your code like this:
print("WELCOME!")
name = input("\nWhat is your name? ")
print("\nHello " + name + "!")
def fn(): # Changed the name of the function to avoid the clash.
return name # Return the name.
print("\nGoodbye", fn())
Output:
WELCOME!
What is your name?
Hello Dipen!
Goodbye Dipen
After reading your comments to Dipens's answer, I think what you are looking for is something like this:
print("\nGoodbye %s" % fn())
But in that case you don't want fn to actually print anything, only to return a string. In your original example the code would execute along the lines of the following:
print("text", print("name"))
... which would result in the same/similar behavior as you're experiencing.
I am new to Python. Working with 2.7 for class.
The teacher set a project in which we are to code a program that takes a piece of a Monty Python script (input by user), stores it in a list of lists, replaces a specific name in the script with the user's name and prints the revised script out to console.
The issue I am running into is in my third function replace_name, the parameters are the list of lists, old name, new name.
However, I am getting
NameError:'word_list' is not defined
I understand that if a variable is not defined in the Main then it is local to its function.
I thought though, that by using return in the function that that information is stored to be used by subsequent functions.
Am I wrong?
def new_name(): #prompts for user's name. checks if input is valid
while True:
name = raw_input("Please enter your name.\n")
if len(name) < 1:
print "Invalid, please enter your name.\n"
else:
return name
def orig_script():#reads in script, splits into list of lists
word_list = []
script = raw_input("Please enter script, one line at a time. Enter 'done' to exit. \n")
if len(script) < 1:
print "Empty text field. Please try again.\n"
while script != 'done':#splits string input,adds to list
words = script.split()
word_list.append(words)
script = raw_input("Please enter script, one line at a time. Enter 'done' to exit.\n ")
if len(script) < 1:
print "Empty text field. Please try again.\n"
return word_list
def replace_name(word_list,old_name,new_name):#replaces old name with new name in list. creates new list from changes.
new_list = []
for sentences in range(word_list):
sentence = word_list[sentences]
for words in range(sentece):
word = sentence[words]
if word == old_name:
sentence[words] == new_name
new_list.append(sentence)
print new_list#debugging-change to return
new_name()
orig_script()
replace_name(word_list, Robin, new_name)
If my indentation is a bit off here, I apologize.
I tried to correct it from the copy/paste.
There are no indentation errors given in repl.it.
Traceback (most recent call last):
File "python", line 45, in <module>
NameError: name 'word_list' is not defined
You did not assign any of the word_list, Robin, new_name variables. Returning a variable of a particular name does not bind it to any type of external variable on its own, especially not one of the same name.
For example, you need to assign the return value explicitly to its own variable.
word_list = orig_script()
name = new_name()
replace_name(word_list, "old name", name)
Also
for sentences in range(len(word_list)):
sentence = word_list[sentences]
Is the same as
for sentence in word_list:
Note: You do have a typo in sentece and this is a comparison, not an assignment sentence[words] == new_name
Bonus, I think you can rewrite replace_name as
def replace_name(word_list,old_name,new_name):
return [[new_name if w == old_name else old_name for w in sentence] for sentence in word_list]
Pass the parameter in you function argument.
Ex.
#take the o/p of variable in another one and pass in funcation
return_val = orig_script()
old_name = ["jack", "mike" , "josh"]
new_name= ["jen" , "ros" , "chan"]
#calling replace name funcation
replace_name(return_val,old_name,new_name)
I'm teaching myself Python and writing a simple GPA calculator. I have very little programming experience prior other than a college Java course, so bear with my code.
The premise is, the code will ask if you want to add a course to the list. If you do, it runs a function asking you the class name. Every time you add a class it'll ask if you want to add another. If you don't, it'll spit out a list of the classes you've added and then ask you to enter in the grades. I didn't get the grading part done yet. I don't think that will be too hard.
The problem is you can add a bunch of classes and it will only spit out the last one you entered. I'm assuming the issue is in askAgain(): classList = addClasses() because it keeps overwriting, but I'm not sure how to avoid a global variable (since they're bad?) and still keep this from overwriting itself. I seem to draw a blank when trying to figure out how to call something once to intialize it and not run it again. I've also read that conditional variables are bad, so I'm not sure what's best practice here. thanks
def main():
askAgain()
return 0
def askAgain():
while True:
addOrNot = raw_input("Add a class? [y/n]: ")
if addOrNot == "Y" or addOrNot == "y":
classList = addClasses() #This is probably where my issue is.
else:
try:
editClassGradeSelection = mainMenu(classList)
addGrades(editClassGradeSelection, classList)
except:
print("Hey you didn't add any classes yet.")
def addClasses():
try:
if classList in locals():
print("debug msg - classList exists")
except:
classList = []
classList.append(raw_input("Add class to the list: "))
return classList
def mainMenu(classList):
print("Here are the classes you've added: ")
counter = 0
for classes in classList:
print((str(counter+1)) + ". " + (str(classList[counter])) + "\n")
counter = counter + 1
while True:
editGrade = raw_input("Enter the number for the class grade to edit: ")
if int(editGrade) > len(classList) or int(editGrade) < 1:
print("Enter a proper number in the range listed.")
else:
break
return editGrade
def addGrades(editClassGradeSelection, classList):
print("debug stuff for now: ")
print((str(editClassGradeSelection)))
print((str(classList[:])))
if __name__ == '__main__':
main()
Although this snippet makes sure classlist is defined:
try:
if classList in locals():
print("debug msg - classList exists")
except:
classList = []
classlist is a local variable, hence everytime you run that function, classlist will be [], which probably explains why you can't ever display more than one. The classlist you assign it to gets reassigned to the one element of classlist (addClasses scope) every time this line is called:
classList = addClasses() #This is probably where my issue is.
I have been trying to figure this out for way too long! What to do?
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return(submission)
name = input("What is your name?")
(fallBack(name))
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
I keep having the last input just print out nothing...
You need to store the result of fallBack().
Also, change fallBack() to return the original value if it is non-null:
def fallBack(submission):
if not submission:
return "fixed!"
else:
return submission
Then, use it like this:
name = fallBack(input("What is your name?"))
Just remove the brackets around fallBack(name)
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return submission
name = input("What is your name?")
name = fallBack(name)
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
Also remember that if using python 2.7 you should use raw_input instead of input
I'm not sure what you want to do, but I think this would do it:
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return (submission)
name = input("What is your name?")
name = fallBack(name)
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
Your two mistakes were not to return anything in case there is nothing to fix, and not to assin the value returned by the function.
By the way, there is a much more idiomatic way of doing this in Python:
name = input("What is your name?")
name = name or 'fixed!'
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
The second line tests if converting name to a boolean, and, if it returns False (for a string, it is equivalent to testing if it is not empty), replace it with 'fixed!'
The return is not well aligned! You are not returning anything unless submission is empty! :-)
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return(submission)