Basic Python function - python

I am trying to complete two different questions but cannot get them to work. Please help me understand where I went wrong.
1) For each number between 1 and 100, odds should be normal and even numbers should print out the word "Billy". Must start at 1 not 0 and include the number 100. Here's my answer (I know I'm way off)
for i in range(1,101):
if i % 2 == 0:
print(Billy)
else:
print(i)
2) Ask the user: "What is your name?". Response should look like "Hello Billy" for all names except Joe and Susie. For Joe it should say "Hi Joe :)" and for susie it should say "Ahoy Susie :D". Here is where I'm at:
name = input("What is your name?")
if name == "Joe":
print("Hi Joe :)")
if name == "Susie":
print("Ahoy Susie :D)
else: print("Hello", name)

try this
for i in range(1,101):
if i % 2 == 0:
print('Billy') #you missed quote marks here
else:
print(i)
(bad indentation, and missing quote marks)
and
name = input("What is your name?")
if name == "Joe":
print("Hi Joe :)")
elif name == "Susie":
print("Ahoy Susie :D") #and you missed quote marks here
else:
print("Hello" + name)
...same issues.

Related

Why is my function executing twice?

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().

How to compare the items in list with the user input?

I am trying to compare the answer from user with a list:
answers=["Sundar Pichai","Mark Zukenberg","Narendra Modi"]
print ('Welcome to Quizz!!')
player_name= raw_input("Enter Your Name:")
def out_ans():
guess_ans = raw_input("enter your answer:")
for ans in answers:
if guess_ans.lower() == ans.lower():
print(player_name +" correct answer")
else:
print(player_name + " its a wrong answer")
print ("Q.No 1 Who is the present CEO of Google??")
out_ans()
print ("Q.No 2 Who is the founder of FaceBook??")
out_ans()
This is the output
Welcome to Quizz!!
Enter Your Name: xyz
Q.No 1 Who is the present CEO of Google??
enter your answer: sundar pichai
xyz its a correct answer
xyz its a wrong answer
xyz its a wrong answer
Q.No 2 Who is the founder of FaceBook??
enter your answer: mark zukenberg
xyz its a wrong answer
xyz its a correct answer
xyz its a wrong answer
I think you need to print the message only once, informing the user about the correctness of his answer.
Then you need something like this:
def out_ans():
guess_ans = raw_input("enter your answer:")
correct = False
for ans in answers:
if guess_ans.lower() == ans.lower():
correct = True
if correct:
print(player_name +" correct answer")
else:
print(player_name + " its a wrong answer")
answers=["Sundar Pichai","Mark Zukenberg","Narendra Modi"]
print ('Welcome to Quizz!!')
player_name= raw_input("Enter Your Name:")
def out_ans():
guess_ans = raw_input("enter your answer:")
if guess_and.lower() in [x.lower() for x in answers]:
print(player_name +" correct answer")
else:
print(player_name + " its a wrong answer")
print ("Q.No 1 Who is the present CEO of Google??")
out_ans()
print ("Q.No 2 Who is the founder of FaceBook??")
out_ans()
But what do you think will happen when I answer on first question 'Mark Zukenberg'? :) Yes, you are right - program will say it is correct answer. To avoid situations like this, change architecture of your quiz as well:
def check_ans(player_ans, valid_answer):
result = "correct answer" if player_ans.lower() == valid_answer.lower() else "its a wrong answer"
return '{0} {1}'.format(player_name, result)
quiz = (("Q.No 1 Who is the present CEO of Google??", "Sundar Pichai"),
("Q.No 2 Who is the founder of FaceBook??", "Mark Zukenberg"))
print('Welcome to Quizz!!')
player_name = input("Enter Your Name:")
for question, answer in quiz:
player_ans = input(question)
print(check_ans(player_ans, answer))
You don't have to print everytime, when you find your response, return :
def out_ans():
guess_ans = raw_input("enter your answer:")
for ans in answers:
if guess_ans.lower() == ans.lower():
#if we find a correct answer, exit
print(player_name +" correct answer")
return
#if didn't find any correct answer
print(player_name + " its a wrong answer")
Try this:
answers=[ "Sundar Pichai", "Mark Zukenberg", "Narendra Modi" ]
flagGuessWrong = False
print ( 'Welcome to Quizz!!' )
player_name = raw_input( "Enter Your Name:" )
def out_ans():
guess_ans = raw_input( "enter your answer:" )
for ans in answers:
if guess_ans.upper() == ans.upper():
print(player_name +" correct answer")
flagGuessWrong = False
break
else:
flagGuessWrong = True
if(flagGuessWrong):
print(player_name + " its a wrong answer")
print ("Q.No 1 Who is the present CEO of Google??")
out_ans()
print ("Q.No 2 Who is the founder of FaceBook??")
out_ans()
This way it will compare everything you have on the array, but keep in mind it will not give you the correct answer (Eg: Q.No 2 Who is the founder of FaceBook?? => Narendra Modi (Will give correct) ) this is because you are looping through the entire array and once it finds a matching pair it will leave (My modification). The rest you need to apply some logic, maybe a dictionary so that he will find key/value pairs and return the correct answer.

How to print all search matches in list of objects

This search function works but if I for example search for an animal called Sarah and there are two animals in the list called Sarah it only prints one of them. How should I do to make it print all the search matches?
def search():
choice = int(input("""
1 Name
2 Age
3 Specie
4 Gender
What do yo want to search for? """))
if choice == 1:
your_search = input("Write the animal name: ").capitalize()
for Animals in animal_list:
if your_search == Animals.name:
print(Animals)
break
else:
print("Sorry, couldn't find any animal called " + your_search + ", maybe check the spelling.")
Try removing break after each successful match
You're telling the program to stop searching after it finds a result. Just remove the break command and add a marker stating if a name was found:
def search():
choice = int(input("""
1 Name
2 Age
3 Specie
4 Gender
What do yo want to search for? """))
if choice == 1:
your_search = input("Write the animal name: ").capitalize()
found = False
for Animals in animal_list:
if your_search == Animals.name:
found = True
print(Animals)
if found == False:
print("Sorry, couldn't find any animal called " +
your_search + ", maybe check the spelling.")

Why is my if true/elif/else-code not working?

In python, I am trying to make this code accept the user to move forward if he writes "True", and not if he writes "False" for the statement in User_Answer. When I run the code however, I get the "the answer is correct!"-part no matter what I write. The part I am having trouble with starts with "Test_Answer".
Could anyone help me with this?
name_list = ["Dean", "Bill", "John"]
enter_club = ["Enter", "enter"]
print ("THE CLUB - by Mads")
print (" ")
print ("""You approach a secret club called \"The club\". The club members are dangerous.
Make sure you tell the guard one of the members names.""")
print ("")
print ("Good evening. Before you are allowed to enter, we need to check if your name is on our list.")
def enter_the_club():
enter_now = input(" \nPress \"enter\" to enter the club... ")
if (enter_now in enter_club) == True:
print (" ")
print ("But as you enter, you are met with an intelegence test. \n It reads:")
check_name = input("What is your name? ")
def list_check():
if (check_name in name_list) == True:
print("Let me check.. Yes, here you are. Enjoy yourself, %s!" % check_name)
enter_the_club()
elif check_name.isalpha() == False:
print("Haha, nice try %s! Let's hear your real name." % check_name)
list_check()
elif (check_name in name_list) == None:
print ("You will need to give us your name if you want to come in.")
list_check()
else:
print ("I am sorry, but I can not find your name on the list, %s." % check_name)
print ("Are you sure that's your listed name?")
list_check()
list_check()
print ("But as you enter, you are met with an intelegence test.")
print (" ")
print ("It reads:")
Test_Answer = True
def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
print ("Great, %s, the answer is correct!" % check_name)
else:
print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
IQtest()
IQtest()
True is a boolean constant. What the user enters will be either "True" or "False", both character strings. Also, your elif condition cannot be true. What are you trying to do with three decision branches?
Without changing your code too much ... try this?
Test_Answer = "True"
def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
print ("Great, %s, the answer is correct!" % check_name)
else:
print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
IQtest()
Note that I've also corrected your "else" syntax.
Also, you have no value for check_name; I assume this is a global variable that you've handled elsewhere.

Looping with a while statement while reading a string for an integer

I need help encasing the:
if any(c.isdigit() for c in name):
print("Not a valid name!")
inside of a while statement. This pretty much just reads the input for the "name" variable and sees if there's an integer in it. How could I use that in a while statement? I just want it to be if the user inputs a variable into the input, it will print out the string up above and loop back and ask the user for their name again until they successfully enter in a string with no integer, then I want it to break. Any help?
print("Hello there!")
yn = None
while yn != "y":
print("What is your name?")
name = raw_input()
if any(c.isdigit() for c in name):
print("Not a valid name!")
print("Oh, so your name is {0}? Cool!".format(name))
print("Now how old are you?")
age = raw_input()
print("So your name is {0} and you're {1} years old?".format(name, age))
print("y/n?")
yn = raw_input()
if yn == "y":
break
if yn == "n":
print("Then here, try again!")
print("Cool!")
Use while True and a break to end the loop when a valid name has been entered:
while True:
name = raw_input("What is your name? ")
if not any(c.isdigit() for c in name):
break
print("Not a valid name!")
This is much easier than first initializing name to something that is invalid then using the any() expression in the while test.
Something like this:
name = input("What is your name? : ")
while any(c.isdigit() for c in name):
print ("{0} is invalid, Try again".format(name))
name = input("What is your name? : ")
demo:
What is your name? : foo1
foo1 is invalid, Try again
What is your name? : 10bar
10bar is invalid, Try again
What is your name? : qwerty
Are you just saying you want a continue after your print("Not a valid name!")?
print("Hello there!")
yn = None
while yn != "y":
print("What is your name?")
name = raw_input()
if any(c.isdigit() for c in name):
print("Not a valid name!")
continue
print("Oh, so your name is {0}? Cool!".format(name))
...
The continue will just go back to the top of your loop.

Categories