[Tutor] Input handling?
eryksun
eryksun at gmail.com
Tue Sep 18 21:48:46 CEST 2012
On Tue, Sep 18, 2012 at 1:23 PM, Scott Yamamoto
<scott.yamamoto at yahoo.com> wrote:
>
> 1) expect: raw_input to assign the variable to ""
> 2)No output to stderr; has a loading symbol after hitting enter without input
> (tried both input and raw_input)
> Doesn't affect active interpreter. Only affects the screen with the run option.
> 3)
Except for a bug your code worked for me in Python 2.7.3.
> def simulation():
> import random
> from random import randrange
> from time import sleep
You're not using randrange, plus you should move the imports to the
top of your module.
> gender = raw_input("Gender: male/female \n")
> if gender != "male" or "female":
> gender = "male"
This is the bug. You have the test expression "expr1 or expr2" where
expr1 is "gender != male" and expr2 is "female". A non-empty string is
always True by definition, so your test amounts to "expr1 or True",
which means the "if" block always executes.
> Mlist = ["Jacob", "Mason", "William", ...]
> Flist = ["Sophia", "Isabella", "Emma", ...]
> Llist = ["Smith", "Johnson", "Williams", ...]
Consider moving these lists out of the function. They can all go
nicely in a dict, which you can set as a default argument.
> username = raw_input("Input your full name: \n")
> if username == "":
> if gender == "male":
> username = random.choice(Mlist) + " " + random.choice(Llist)
> else:
> username = random.choice(Flist) + " " + random.choice(Llist)
Using a dict for the names eliminates the need to test gender here. For example:
import random
import time
names = {
"male": [
"Jacob", "Mason", "William", "Jayden", "Noah", "Michael",
"Ethan", "Alexander", "Aiden", "Daniel", "Anthony",
"Matthew", "Elijah", "Joshua", "Liam", "Andrew", "James",
"David", "Benjamin", "Logan",
],
"female": [
"Sophia", "Isabella", "Emma", "Olivia", "Ava", "Emily",
"Abigail", "Madison", "Mia", "Chloe", "Elizabeth", "Ella",
"Addison", "Natalie", "Lily", "Grace", "Samantha", "Avery",
"Sofia", "Aubrey",
],
"last": [
"Smith", "Johnson", "Williams", "Jones", "Brown", "Pavis",
"Miller", "Wilson", "Moore", "Taylor", "Anderson", "Thomas",
"Jackson", "White", "Harris", "Martin", "Thompson", "Garcia",
"Martinez", "Robinson",
],
}
def simulation(names=names):
print "Welcome to The World."
time.sleep(1)
print "Now Loading..."
time.sleep(1.5)
# Intro page
gender = raw_input("\nGender [male|female]:\n").strip()
if gender not in ("male", "female"):
gender = "male"
username = raw_input("Input your full name:\n")
if not username:
username = " ".join(
random.choice(n) for n in (names[gender], names["last"]))
print "\nUsername: %s. Gender: %s." % (username, gender)
More information about the Tutor
mailing list