Is it possible to reuse an 'if' statement? - python

So I am working on a project and I was wondering if it is possible to reuse an 'if' statement. For example, my code right now is
import re
import string
userinput=''
print "Hello! What is your name?"
userinput = str(raw_input("My name is "))
if not re.search(r'[A-Za-z]', userinput):
print "That isn't a name!"
print str(raw_input("My name is "))
and it prints
Hello! WHat is your name?
My name is 86124674983#
That isn't a name!
My name is 986421674941
986421674941
As you can see, it recognizes anything other than letters as an invalid entrance, but it only does it once. If you input symbols the second time it prompts you for a name, it takes that random input and prints it. I want it to print
Hello! WHat is your name?
My name is 86124674983#
That isn't a name!
My name is 986421674941
That isn't a name!
My name is Eli
Sorry if this confuses anyone. If you need anything clarified don't hesitate to ask. Thanks very much in advance!!

Use a while loop:
print "Hello! What is your name?"
while True:
userinput = raw_input("My name is ")
if not re.search(r'[A-Za-z]', userinput):
print "That isn't a name!"
else:
break
print userinput
Note you don't print a raw_input() - or make it str (it already is). All you need is the raw_input('text') and it will display text.

Use a while-loop:
print "Hello! What is your name?"
while True:
userinput = raw_input("My name is ")
if re.search(r'[A-Za-z]', userinput):
break
print "That isn't a name!"
print userinput

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

I cannot use a input check to verify if the person has put in the correct code

This is my code
name=""
name=input("What is your name?")
print ("For clarification, is your name",name,"?")
input("Please enter yes or no")
if input==("yes"):
print ("Thank you")
else:
name=input("What is your name?")
and I was wondering if anyone could help me sort it out. In the lines below.
input("Please enter yes or no")
if input==("yes"):
print ("Thank you")
else:
name=input("What is your name?")
print ("Thank you",name,)
I am trying to ask people if they have put the correct names by asking them directly. If the answer is yes, they can move on, otherwise they will have to input their name again. Unfortunately I am not able to find the way to do it. Can anyone send me a correct code version. (An explanation would be nice but not necessary.)
Try :
while True:
n = input("Please enter yes or no")
if n == "yes":
print ("Thank you")
break
else:
name = input("What is your name?")
print ("Thank you",name)
You need to remember the second input to use it in the if statement.
response = input("Please enter yes or no")
if response == "yes":
print("Thank you")
else:
name = input("What is your name?")
You could use a recursive function.
It will loop until it returns the name.
#!python3
def get_name():
name=input("What is your name?")
print("For clarification, is your name",name,"?")
sure = input("Please enter yes or no")
if sure==("yes"):
print("Thank you")
return name
else:
get_name()
name = get_name()

Alphabet check as input

Hi I just start learning python today and get to apply what I learning on a flash cards program, I want to ask the user for their name, and only accept alphabet without numbers or symbols, I've tried several ways but there is something I am missing in my attempts. Here is what I did so far.
yname = raw_input('Your Name ?: ')
if yname.isdigit():
print ('{0}, can\'t be your name!'.format(yname))
print "Please use alphbetic characters only!."
yname = raw_input("Enter your name:?")
print "Welcome %s !" %yname
but I figured in this one is if the user input any character more than one time it will eventually continue...So I did this instead.
yname = raw_input("EnterName").isalpha()
while yname == True:
if yname == yname.isalpha():
print "Welcome %s " %(yname)
else:
if yname == yname.isdigit():
print ("Name must be alphabetical only!")
yname = raw_input('Enter Name:').isalpha()
This while loop goes on forever, as well as I tried (-) and (+) the raw input variable as I've seen in some tutorials. So I thought of using while loop.
name = raw_input("your name"):
while True:
if name > 0 and name.isalpha():
print "Hi %s " %name
elif name < 0 and name.isdigit():
print "Name must be Alphabet characters only!"
try:
name != name.isalpha():
except (ValueError):
print "Something went wrong"
This will check for both alphabet in the raw_input and check for the length of the name as I see you tried to do in your last try.
import string
import re
name = re.compile(r'[a-zA-Z]+') #This will check for alphabet.
yname = raw_input("Your Name:") #ask the user for input.
while not name.match(yname):
print "invalid characters"
yname = raw_input("Your Name:")
if 5<=len(yname)<=10:
print "Hi,", yname, "!"
elif len(yname)>10:
print "too long!"
elif len(yname)<5:
print "too short!"
You can rearrange your last attempt a bit to get what you want:
while True:
name = raw_input("your name") # ask inside the loop
if name and name.isalpha():
print "Hi %s " %name
break # leave the loop if done
elif name and name.isdigit():
print "Name must be Alphabet characters only!"
else:
print "Please enter something"
Note that if name will be True if name != "".
name = raw_input('Enter your name: ')
while not name.isalpha():
print 'Invaid characters in name'
name = raw_input('Enter your name: ')
Use regexes:
import re
regex = re.compile("^[a-zA-Z]+$")
valid_name = False
while not valid_name:
user_name = raw_input("EnterName")
if not regex.search(user_name):
print "this can't be your name"
else:
print "Hi there, {0}".format(user_name)
valid_name = True
Also, please take note that programmers often make false assumptions about human names
Edit: as an alternative you can skip compiling a regex and just use the pattern in place:
if not re.search("^[a-zA-Z]+$", user_name):
...
However, since you're doing it in a loop compiled version would have slightly better performance, since re.search actually compiles a regex behind the scenes each time invoked.
Also, please note I've changed match to search and slightly modified a regex since there're some differences and it appears tome me that search suits your situation more.

How would I disallow numbers as input?

Alright, so I defined a function where the user can input his/her name. I want to make it so that the user is not allowed to input a number like "69" for his/her name. How would I go about doing this? Here is the code I used:
def name():
while True:
name = input("What is your name? "))
try:
return str(name)
break
except TypeError:
print("Make sure to enter your actual name.")
You can use isalpha() to check name:
Return true if all characters in the string are alphabetic and there
is at least one character, false otherwise.
>>> "69".isalpha()
False
>>> "test".isalpha()
True
Here's your code with modifications:
while True:
name = input("What is your name? ")
if name.isalpha():
break
else:
print("Make sure to enter your actual name.")
continue
Or:
name = input("What is your name? ")
while not name.isalpha():
print("Make sure to enter your actual name.")
name = input("What is your name? ")
You can use str.isdigit() method to check if the string contains just digits:
name = input("What is your name? ")
while name.isdigit():
print("Make sure to enter your actual name.")
name = input("What is your name? ")
Note that this will allow names like - "Rohit1234". If you just want to allow alphabetic characters, then you can use str.isalpha() method instead.
Invert your logic:
while True:
name = ...
try:
int(name)
print "Name can't be a number."
except TypeError:
return str(name)
Mind you, this will accept any input that is not a valid integer, including 123abc or so.

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