I have a question about python 3.4.1
So suppose you have a program like this:
name = input("What is your name?")
print("Hi", name ,'!')
So you get:
.>>> What is your name?
So you type in you James and you get back:
.>>> Hi James!
Then after it prints this little message, it automatically resets, and goes back to:
.>>> What is you name?
Thanks for you time! :D
while True:
name = input("What is your name?")
print("Hi", name ,'!')
Use a while loop
You need some condition to break out of the loop:
while True:
name = input("Enter your name or press q to quit")
if name == "q":
break # if user enters `q`, we will end the loop with this break statement
print("Hi", name ,'!') # or else just print the name
A nice tutorial on while loops.
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.
I am attempting to create a contact list with a def() function to easily loop back to the top later in the code. The issue I am having is that I define "function_question" in the def portion but when I run the code it gives me a NameError saying "function_question" is not defined. Any help or suggestions is appreciated!!
#Created a def so I can easily run back the code to the top.
def user_prompt():
print('Welcome to your contact directory.')
function_question = int(input("What would you like to do? \n1 Add Conctact \n2 Find Contact \n3 Edit Contact \n4 Delete Contact:"))
user_prompt()
#Adding a contact to the contact list.
while function_question == 1:
name = input('What is the persons name? ')
phone_number = input('What is the phone number? ')
email = input('What is your email? ')
address = input('What is the person adress? ')
if len(phone_number) != 10:
phone_number = input("the phone number you provided is not the proper length. Re-enter:")
contact = [] + [name] + [phone_number] + [email] + [address]
contact_list.append(contact)
ans = input('Would you like to add another contact? ')
if ans == 'yes':
continue
if ans == 'no':
user_prompt()
You could simply return the value from the function and save it to a variable outside the function. Like:
def user_prompt():
print('Welcome to your contact directory.')
return int(input("question"))
input_question = user_prompt()
The issue is that the variable function_question is empty.
In your code you defined two variables function_question with the same name but with different memory address; the first is a local variable that works only into the user_prompt() function.
The correct code is:
#Created a def so I can easily run back the code to the top.
def user_prompt():
print('Welcome to your contact directory.')
return int(input("What would you like to do? \n1 Add Conctact \n2 Find Contact \n3 Edit Contact \n4 Delete Contact:"))
function_question = user_prompt()
#Adding a contact to the contact list.
while function_question == 1:
...
I suggest you to search about python scope variable for more details.
The function_question variable is in the scope of the user_prompt function so you cannot use it in the global scope. You need to make it global for it to be acessible
I reccomend reading through this,
https://www.w3schools.com/PYTHON/python_scope.asp
def write():
writefile=input("Please enter the last name: ")
name=input("Please enter your name:")
street=input("Enter House Number and Street Name:")
city=input('Enter City, State and ZIP:')
home=input('Enter Home Phone Number:')
mobile=input('Enter Cell Phone Number:')
outfile=open('C:\\Users\\Force\workspace\addressbook.txt','w')
outfile.write("Added "+name+writefile)
outfile.write(street+city+home+mobile)
outfile.close()
def read():
phonebook=open("C:\\Users\\Force\workspace\addressbook.txt",'r')
numEntries=0
lastName=phonebook.readline().rstrip()
while lastName!='':
firstName=phonebook.readline().rstrip()
street=phonebook.readline().rstrip()
city=phonebook.readline().rstrip()
homephone=phonebook.readline().rstrip()
mobilephone=phonebook.readline().rstrip()
numEntries=numEntries+1
LastName=phonebook.readline().rstrip()
def menu():
print('1: Look up person by last name')
print('2: Add a person to the address book')
print('3: Quit')
option=input('Pick your option: ')
if option==1:
read()
if option==2:
write()
if option==3:
print("Good bye!")
menu()
Every time it brings me to the menu and I try selecting an option it just terminates the program. Not sure if it's my user defined functions, the opening of the text file or even just all of it. (Using Pydev 3.6)
In option=input('Pick your option: '), option is a string. You could either convert it to an int, or test it with
if option=='1':
And - not to be picky, but you might want to consider 'elif'
First I'm sorry this might be a dumb question but I'm trying to self learn python and I can't find the answer to my question.
I want to make a phonebook and I need to add an email to an already existing name. That name has already a phone number attached. I have this first code:
phonebook = {}
phonebook ['ana'] = '12345'
phonebook ['maria']= '23456' , 'maria#gmail.com'
def add_contact():
name = raw_input ("Please enter a name:")
number = raw_input ("Please enter a number:")
phonebook[name] = number
Then I wanted to add an email to the name "ana" for example: ana: 12345, ana#gmail.com. I created this code but instead of addend a new value (the email), it just changes the old one, removing the number:
def add_email():
name = raw_input("Please enter a name:")
email = raw_input("Please enter an email:")
phonebook[name] = email
I tried .append() too but it didn't work. Can you help me? And I'm sorry if the code is bad, I'm just trying to learn and I'm a bit noob yet :)
append isn't working because the dictionary's values are not lists. If you make them lists here by placing them in [...]:
phonebook = {}
phonebook ['ana'] = ['12345']
phonebook ['maria'] = ['23456' , 'maria#gmail.com']
append will now work:
def add_contact():
name = raw_input("Please enter a name:")
number = raw_input("Please enter a number:")
phonebook[name].append(number)
Im trying to write a program that assigns an empty str to the variable myvar. then in a while loop the program asks for the user to type text, anything they want and it will print to the screen until the user enters the text quit which will end the loop and stop the program.
this is what I have
myvar = str("")
while myvar != "quit":
user_input = raw_input()
user_input = myvar
print myvar
Thanks.
how about
for output in iter(raw_input,"quit"):
print output
you're pretty close, but the indentation's off and the logic needs a slight tweak:
myvar = ""
while myvar != "quit":
myvar = raw_input()
print myvar
note that this will also print "quit". I'll leave that as a final exercise to you to figure out how to cut that out.