I am making a program on python 3. I have a place that I need the script to restart. How can I do this.
#where i want to restart it
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
print("Press any key to exit")
input()
It's a general question about programming an not specific to Python ... by the way you can shorten your code with the two conditions on boy and girl...
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy" or gender == "girl":
print("Lets get on with the story.")
break
print("Sorry. You cant have that. Type boy or girl.")
print("Press any key to exit")
input()
Simple but bad solution but you get the idea. I am sure, you can do better.
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
restart = input("Would you like to restart the application?")
if restart != "Y":
print("Press any key to exit")
input()
break
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while (input("Guess the phrase: ") != phrase):
print("Incorrect.") //Evaluate the input here
print("Correct") // If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
or you can have two separate function written over, It's same as above(only it's written as two separate function ) :
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while (not(game(phrase))):
print("Incorrect.")
print("Correct")
main()
Hope this is what you are looking for .
Related
I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out:
import time
def start():
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
def other():
name = input("Type the first name: ")
for x in data:
if name in x:
result = print(x)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it.
The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again.
I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help.
There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
Split the other into its own function
Try to use more accurate variable names
As much as you can - avoid having multiple for loops happening at the same time
Have a look at list comprehension it would help a lot in this case
Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.
If my_input == "n" I want to my program to loop again, which works fine.
But if my else statement is True I dont want it to run the whole program again and just "start" at the my_input variable.
How can I achieve this?
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
else:
print("Invalid input, try again.")
name_user_validation()
I misunderstood your question, I would probably restructure your code a bit, so you get rid of your while loops and use recursive function calling to go back when you need to,
something like the below
def name_user_validation():
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split() # This line actually doesn't do anything
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
if not accept_input():
name_user_validation()
def accept_input():
my_input = input("Is that right? (y/n) ")
if my_input == "y":
print("Great!")
return True
elif my_input == "n":
print("Oh no :(")
return False
else:
print("Invalid input, try again.")
accept_input()
name_user_validation()
Add another loop that doesn't terminate until user enters acceptable input.
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
while True:
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
break
else:
print("Invalid input, try again.")
if my_input == 'y':
break
name_user_validation()
Edit: The program terminates only when my_input = y.
I'm stuck with a problem that asks 5 questions. If any of them has the answer no It should print ALIEN! or else Cool.
This is what I have got so far:
human = input("Are you human? ")
human = input("Are you living on planet Earth? ")
human = input("Do you live on land? ")
human = input("Have you eaten in the last year? ")
human = input("Is 2 + 2 = 4? ")
if human == "yes":
print("Cool")
elif human == "no":
print("ALIEN!")`
You could use any() to check if any of the answers to questions is 'no' and print message accordingly:
human = [input("Are you human? "), input("Are you living on planet Earth? "),
input("Do you live on land? "), input("Have you eaten in the last year? "), input("Is 2 + 2 = 4? ")]
if any(x.lower() == 'no' for x in human):
print('ALIEN!')
else:
print('Cool')
You have the variable human that is changed every time and given a new value using input() Try and make multiple variables instead of just using human.
human = input("Are you human? ")
var1 = input("Are you living on planet Earth? ")
var2 = input("Do you live on land? ")
var3 = input("Have you eaten in the last year? ")
var4 = input("Is 2 + 2 = 4? ")
if(human == "yes"):
print("Cool")
elif(human == "no"):
print("ALIEN!")
If you're not worried about storing the variables and only care if one of the questions comes up as "no" or "n":
x=["human?","on earth?", "on land?","someone who eats food?","sure that 2+2=4?"]
for i in x:
if input("Are you {}".format(i)).lower() in ['no','n']:
print("Alien!")
break
else:
print("Cool")
Just a side note: Here you can see a great case for using a for loop since there is code that is repeated many times. Personally, I would do the following to solve this problem.
Create a list of questions
Iterate through the list of questions
If any answer is no, break and print Alien.
Now for the code:
# Initialize our list
lst = ["Are you human? ", "Are you living on planet Earth? ","Do you live on
land? ","Have you eaten in the last year? ","Is 2 + 2 = 4? "]
#Create a flag for Alien
flag = False
#Iterate through the list
for question in lst:
answer = input(question)
if answer == 'no':
#Print alien
print('Alien')
#Change Flag
flag = True
#Break out of the loop
break
#Check to see if our flag was thrown during the loop
if flag == False:
print('cool')
If you want more help on solving coding challenges like this one, check out this intro to python course: https://exlskills.com/learn-en/courses/learn-python-essentials-for-data-science-intro_to_python/content
A function in my code repeats twice. In the chooseName() function, it asks the question, and once you answer, it repeats the question and then moves on with the rest of the code. Why does it do this?
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = raw_input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
displayIntro()
chooseGender()
chooseName()
nameConfirmation()
I apologize for not posting the rest of the code sooner.
This is the output.
Let's begin with your name. What is it? Raven
Let's begin with your name. What is it? Raven
Remove the chooseName( ) call below chooseGender( ) as it has already been called in nameConfirmation( ) definition. It worked for me.
Some modification in your code , Here is updated code:
First edit :
You are calling chooseName() two times ,
Second edit :
You are returning before main logic of your program.
Here
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
You should keep in mind that function is not going to execute anything after you return from it so your code from if answer == "yes": is not going to execute even if user type yes or no
So return it at the last of the program or if you want to return at the same place then use print there instead of 'return'.
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = input("Right... So your name is " + str(name) + "? (yes or no) ")
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
return answer
displayIntro()
chooseGender()
nameConfirmation()
As chooseName() is getting called twice first below call of chooseGender() and second inside nameConfirmation() so that's the reason it is getting executed twice. As a fixed you can comment or remove chooseName() which is below chooseGender() as shown.
displayIntro()
chooseGender()
# chooseName()
nameConfirmation()
So updated code will be as follows:
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = raw_input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
displayIntro()
chooseGender()
# chooseName()
nameConfirmation()
You call the function choseName() and then right after you call nameConfiguration() wich starts by calling choseName(), that's why it is called twice. You can simply remove the choseName() before nameConfiguration().
I'm trying to write an if statement where if the user enters "yes" a game runs but when I cannot figure out how to do this, I can't find it online.
userName = input("Hello, my name is Logan. What is yours? ")
userFeel = input("Hello " + userName + ", how are you? ")
if userFeel == "good":
print ("That's good to hear")
elif userFeel == "bad":
print ("Well I hope I can help with that")
q1 = input("Do you want to play a game? ")
if q1 == "yes":
print ("Alright, lets begin")
import random
print ("This is a guessing game")
randomNumber = random.randint(1, 100)
found = False
yes = "yes"
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == randomNumber:
print ("You got it!")
found = True
elif userGuess>randomNumber:
print ("Guess Lower")
else:
print ("Guess Higher")
elif game == "no":
print ("No? Okay")
q2 = input("What do you want to do next? ")
This is because you have named both your variable for your input "game" and your function call "game". rename one or the other and your code should work as intended.
If you are using Python2.*, You should use raw_input instead of input.
And no matter what version of Python you are using, you should not use the same name for both the function and your variable.