I am writing a text game in python 3.3.4, at one point I ask for a name. Is there a a way to only accept one name, (one argument to the input) and if the user inputs more than one arg.
Here is what I currently have.
name =input('Piggy: What is your name?\n').title()
time.sleep(1)
print('Hello, {}. Piggy is what they call me.'.format(name))
time.sleep(1)
print('{}: Nice to meet you'.format(name))
time.sleep(1)
print('** Objective Two Completed **')
I am guessing I will need to use something like while, and then if and elif.
Help is greatly appreciated
while True:
name = input("What is your name? ").strip()
if len(name.split()) == 1:
name = name.title()
break
else:
print("Too long! Make it shorter!")
Related
I am currently writing a code that accepts user inputs. However, I intend to put in an option such that if the user made an error, they may restart the process again by typing in a specific input. And I'm hoping that the code clears all previous input from the namespace:
For example
name = input("what is your name: ")
age = input("how old are you:? ")
## if the user realizes that they put in the wrong name and wish to restart the process, they may input "restart"
if age == 'restart':
### I don't know what code to put here.
else:
#I'd continue the rest of my codes
I'd greatly appreciate any tips.
Supposedly you want the console to clear if the user decides to change its input in name
import os
while True:
os.system('clear') #we imported "os" for this built-in function
name = input("Enter your name: ")
age = input("how old are you:? ")
if age == 'restart': #if user inputs 'restart' we head back to the start of the loop
input("Press Enter Key to Continue...")
continue
# Rest of the code goes here
You can simple wrap the code in a while loop
name = input("what is your name: ")
age = 'restart' # This is simply taking input because of the next line of code
while age == 'restart':
age = input("how old are you:? ")
# Rest of the code goes here
I'm new to python so please kindly help, I don't know much.
I'm working on a project which asks for a command, if the command is = to "help" then it will say how to use the program. I can't seem to do this, every time I try to use the if statement, it still prints the help section wether the command exists or not.
example: someone enters a command that doesn't exist on the script, it still prints the help section.
print("welcome, to use this, please input the options below")
print ("help | exit")
option = input("what option would you like to use? ")
if help:
print("this is a test, there will be an actual help section soon.")
else:
print("no such command")
Check using == equality operator
print("welcome, to use this, please input the options below")
print("help | exit")
option = input("what option would you like to use? ")
if option == "help":
print("this is a test, there will be an actual help section soon.")
else:
print("no such command")
You need to reference your variable option in the if statement for it to work.
print("welcome, to use this, please input the options below")
print ("help | exit")
option = input("what option would you like to use? ")
if option == "help":
print("this is a test, there will be an actual help section soon.")
else:
print("no such command")
I'm also just starting with Python and I hope we both can learn a lot from here.
Try this.
`print("welcome, to use this, please input the options below")
print ("help | exit")
option = input("what option would you like to use? ")
if option == "help":
print("this is a test, there will be an actual help section soon.")
else:
print("no such command")`
ive written some code and it works fine (from what i can see anyway) until I get to the "else" part, really i just want to set up a simple loop but I dont know how. the error is "Statement expected, found Py:ELSE_KEYWORD Statement expected, found Py:COLON"
name = input("Hello, what is your name? ")
restart = input ("Do you want to chat 'y' (type 'y' for yes) or 'n'")
while restart == "y":
print("Hello " + name)
feeling = input("How are you today? ")
print("I'm feeling good!")
else:
print("Sorry, the restart")
else: print("goodbye")
I am just trying to set up my loop then I will finish my code.
Three things:
Python is unique in that whitespace matters - code within the same block should have the same indentation
Else-statements can only be used following an if-statement. Since you don't have any if-statements in your code, you can't have any else-statements. We can just remove them.
You need to ask the user if they want to keep going at the end of your loop.
Here's a cleaned-up version of your code:
name = input("Hello, what is your name? ")
restart = input ("Do you want to chat 'y' (type 'y' for yes) or 'n'")
while restart == "y":
print("Hello " + name)
feeling = input("How are you today?")
print("I'm feeling " + feeling)
restart = input ("Do you want to chat 'y' (type 'y' for yes) or 'n'")
print("Goodbye")
The loop structure needs to be changed. We need to run an infinite loop and only when user types 'n' we should come out of that loop
I am learning python and practicing my skills my making a simple text based adventure game.
In the game, I want to ask the player if they are ready to begin. I did this by creating a begin() function:
def begin():
print(raw_input("Are you ready to begin? > "))
while raw_input() != "yes":
if raw_input() == "yes":
break
print(start_adventure())
else:
print("Are you ready to begin? > ")
print(begin())
below this in my code is the function start_adventure()
def start_adventure():
print("Test, Test, Test")
When I run the program it starts up and I get to the point where it asks if I am ready to begin. Then it just loops infinitely and I can only exit the program if I completely close Powershell and restart Powershell. What am I doing wrong? How can I get the loop to stop once the player inputs "yes"?
What do you expect this to do? The solution to your problem is to try to understand what the code does, instead of just throwing stuff together. (Don't worry; at least 80% of us were at that stage at one point!)
As an aside, I strongly recommend using Python 3 instead of Python 2; they made a new version of Python because Python 2 was full of really strange, confusing stuff like input causing security vulnerabilities and 10 / 4 equalling 2.
What do you want this to do?
Repeatedly ask the user whether they are ready to begin until they answer "yes".
Call start_adventure().
Ok. Let's put what we've got so far into a function:
def begin():
while something:
raw_input("Are you ready to begin? > ")
start_adventure()
There are a lot of gaps in here, but it's a start. Currently, we're getting the user's input and throwing it away, because we're not storing it anywhere. Let's fix that.
def begin():
while something:
answer = raw_input("Are you ready to begin? > ")
start_adventure()
This is starting to take shape. We only want to keep looping while answer != "yes"...
def begin():
while answer != "yes":
answer = raw_input("Are you ready to begin? > ")
start_adventure()
Hooray! Let's see if this works!
Traceback (most recent call last):
File "example", line 2, in <module>
while answer != "yes":
NameError: name 'answer' is not defined
Hmm... We haven't set a value for answer yet. In order to make the loop run, it has to be something that isn't equal to "yes". Let's go with "no":
def begin():
answer = "no"
while answer != "yes":
answer = raw_input("Are you ready to begin? > ")
start_adventure()
This will work!
Python 3 Solution
You should not be calling raw_input() multiple times. Simply instantiate x and then wait until the user inputs Y to call your start_adventure function. This should get you started:
def start_adventure():
print('We have started!')
#do something here
def begin():
x = None
while x!='Y':
x = input('Are you ready to begin (Y/N)?')
if x=='Y':
start_adventure()
begin()
Your Raw input function (I'm assuming it works correctly) is never assigned to a variable. Instead you call it in your print statement, print the result of it and then you call it again in your while loop condition.
You never actually satisfy the while loop condition because your input isn't assigned to a variable. Assign Raw_input("Are you ready to begin? >") to a variable to store the input. Then while loop with the variable. Make sure in your while loop when the condition is met you reset the variable to something else.
Your program flow is wrong too, you need to call your raw input function inside the while loop. This will change the while loop condition so that when the condition is met (user types "yes") it won't loop infinitely. Hope this helps!
Example of what you need in code form:
//initialize the condition to no value
condition = None;
#check the condition
while condition != "yes"
#change the condition here based on user input **inside the loop**
condition = raw_input("are you ready to begin? >")
if condition == "yes":
#condition is met do what you need
else:
#condition not met loop again
#nothing needs to go here to print the message again
I am trying to run a script which asks users for their favorite sports teams. This is what I have so far:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input is "Yankees":
print("Good choice, go Yankees")
elif input is "Knicks":
print("Why...? They are terrible")
elif input is "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
Whenever I run this script, the last "else" function takes over before the user can input anything.
Also, none of the teams to choose from are defined. Help?
Input is a function that asks user for an answer.
You need to call it and assign the return value to some variable.
Then check that variable, not the input itself.
Note
you probably want raw_input() instead to get the string you want.
Just remember to strip the whitespace.
Your main problem is that you are using is to compare values. As it was discussed in the question here --> String comparison in Python: is vs. ==
You use == when comparing values and is when comparing identities.
You would want to change your code to look like this:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input == "Yankees":
print("Good choice, go Yankees")
elif input == "Knicks":
print("Why...? They are terrible")
elif input == "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
However, you may want to consider putting your code into a while loop so that the user is asked the question until thy answer with an accepted answer.
You may also want to consider adding some human error tolerance, by forcing the compared value into lowercase letters. That way as long as the team name is spelled correctly, they comparison will be made accurately.
For example, see the code below:
while True: #This means that the loop will continue until a "break"
answer = input("Who is your favorite sports team: Yankees, Knicks, or Jets? ").lower()
#the .lower() is where the input is made lowercase
if answer == "yankees":
print("Good choice, go Yankees")
break
elif answer == "knicks":
print("Why...? They are terrible")
break
elif answer == "jets":
print("They are terrible too...")
break
else:
print("I have never heard of that team, try another team.")