I am trying to get user input with error checking using a while loop to make sure the user always enters something with more than 2 characters. However the Python program never asks me for input. Help?
first_names = ['fred', 'bob', 'mary', 'john', 'frank', 'james', 'joe', 'jay']
last_names = ['jones', 'smith', 'doe', 'cardinal', 'jesus', 'watson', 'blogs', 'harris']
full_names = ['empty_name']*len(first_names)
i = 0
while True:
full_names[i] = (first_names[i] + " " + last_names[i])
print full_names[i]
i = i + 1
if i == (len(last_names) + len(first_names))/ 2:
True = not True
name = 'placeholder_name_for_user_input_via_console'
while True:
name = raw_input("please enter a new name")
if len(name) < 2 :
print " please enter a name longer than 2 characters"
else:
True = not True
print "thank you for entering a long name"
full_names.append(name)
print(full_names)
I'm using Python 2.7 if that makes any difference.
edit:
I fixed my code. After the first while loop = need to write True = not False to make it work.
You can't change the value of True. True is the Trueest thing. Instead use break.
while True:
full_names[i] = (first_names[i] + " " + last_names[i])
print full_names[i]
i = i + 1
if i == (len(last_names) + len(first_names))/ 2:
# True = not True; some_int / 0
break
break exits the innermost loop it's found in.
I fixed my code. After the first while loop i need to write True = not False to make it work:
first_names = ['fred', 'bob', 'mary', 'john', 'frank', 'james', 'joe', 'jay']
last_names = ['jones', 'smith', 'doe', 'cardinal', 'jesus', 'watson', 'blogs', 'harris']
full_names = ['empty_name']*len(first_names)
i = 0
while True:
full_names[i] = (first_names[i] + " " + last_names[i])
print full_names[i]
i = i + 1
if i == (len(last_names) + len(first_names))/ 2:
True = not True
name = 'placeholder_name_for_user_input_via_console'
True = not False
while True:
name = raw_input("please enter a new name")
if len(name) < 2 :
print " please enter a name longer than 2 characters"
else:
True = not True
print "thank you for entering a long name"
full_names.append(name)
print(full_names)
Related
I am trying to print an output but I just can't figure out method.
keepAsking = True
author = ""
booktitle = ""
purchaseprice = float()
sellprice = float()
stockcount = int()
margin = float()
bookList = []
priceList = []
while keepAsking == True :
print("Enter Book Data: -")
author = input("Author: ")
if author == "" :
print("Blank Entry")
else :
booktitle = input("Title: ")
if booktitle == "" :
print("Blank Entry")
else :
purchaseprice = input("Purchase Price: ")
if purchaseprice == "" :
print("Incorrect Value")
else :
sellprice = input("Sell Price: ")
if sellprice == "" :
print("Incorrect Value")
else :
bookList.append(author)
bookList.append(booktitle)
if purchaseprice > sellprice :
bookList.remove(author)
bookList.remove(booktitle)
else :
priceList.append(purchaseprice)
priceList.append(sellprice)
stockcount = input("In Stock: ")
if stockcount == "" :
print("Incorrect Value")
else :
priceList.append(stockcount)
margin = ((float(sellprice)-float(purchaseprice))/float(purchaseprice))*100
marginround = round(margin,2)
priceList.append(marginround)
checkContinue = True
while checkContinue == True :
continues = input("Continue? [y/n]")
continuesLower = continues.lower()
if continues == "y" :
checkContinue = False
if continues == "n" :
checkContinue = False
keepAsking = False
and I am trying to get an output like this:
output
I don't really understand array and I have tried a few methods but failed to output it as the image shows. If possible, I would need some explanation too because I want to learn rather than get the answer straight out. So, if you have a solution, I might ask for more information on it too. (you don't have to explain it if you are not comfortable, but I just wish to learn more)
Thank you for attempting to help me. I am sorry if this is just a simple task but I am less than a beginner and trying to improve myself.
I am currently not outputting anything enter image description here
my print code is
for a in bookList :
counter = 0
while counter == len(bookList) :
print(bookList[0] + bookList[1])
print("Purchase Price: " + priceList[0] + "Sell Price: " + priceList[1] + "In Stock: " + priceList [2] + "Margin: " + priceList [3])
If you want to print multiple Book names and prices, etc you should put each one of them into a separate list in this case. (with append)
If you want to print them out you can do like this:
for i in range(0, len(booklist)):
print(author[i] + ' Purchase:' + purchase[i] + ' Sell:' + sell[0]))
... etc to the right format in wich purchase and sell are all lists. Don't forget to add spaces.
To check if the person actually input numbers you can use the method .isdigit()
if purchaseprice.isdigit() != true :
print("Incorrect Value, input numbers")
I am working on a username generator in Python, and everything is going well but one thing: the "IF" statement at the very end of the code is malfunctioning. The first part of the code works, but the last paragraph kicks in, even when I have typed in a supposedly valid choice.
The code:
[import random, tkinter
#variables that make up the name. the "1" symbolises the first part and the "2" symbolises the last part of the username
general1 = \["noob","baby","dude","soldier","discount"\]
general2 = \["kid","plant","painter","officer","conscience"\]
animal1 = \["frantic","fiesty","quick","quiet","loud"\]
animal2 = \["ferret","dog","hampster","cat","rabbit"\]
food1 = \["delicious","disgusting","stinky","fried","bitter"\]
food2 = \["pickle","chocolate","rice","water","lemonade"\]
name1 = \["dylan","eve","chris","simon","adele"\]
name2 = \["christopher","sharp","smith","james","baker"\]
#the main part
category = str(input("**USERNAME GENERATOR**\n\nWhat category do you want?\n1 for general\n2 for animals\n3 for food\n4 for human names\n\n"))
if category == "1":
output1 = random.choice((general1))
output2 = random.choice((general2))
endNumber = random.randint(0, 100)
print("\nYour random username is: ",output1,output2,endNumber)
if category == "2":
output1 = random.choice((animal1))
output2 = random.choice((animal2))
endNumber = random.randint(0, 100)
print("\nYour random username is: ",output1,output2,endNumber)
if category == "3":
output1 = random.choice((food1))
output2 = random.choice((food2))
endNumber = random.randint(0, 100)
print("\nYour random username is: ",output1,output2,endNumber)
if category == "4":
output1 = random.choice((name1))
output2 = random.choice((name2))
endNumber = random.randint(0, 100)
print("\nYour random username is: ",output1,output2,endNumber)
if category != ("1","2","3","4"):
print("\nPlease enter a valid option:")
category = str(input("What category do you want?\n1 for general\n2 for animals\n3 for food\n4 for human names\n\n"))][1]
if category != ("1","2","3","4"):
This only checks if category is equal to the tuple ("1","2","3","4"). You want to check if category is equal to any value of the tuple. Do that by changing that line to this:
if category not in ("1","2","3","4"):
After an if statement ends, the next line is executed.
In your case, the next line is the next if paragraph.
And after that the next one and so on.
e.g.:
if a:
do_action_a()
if b:
do_action_b()
if c:
do_action_c()
if not(a or b or c):
do_action_all_others()
Here you will always execute each paragraph independently of the previous one(s).
To avoid this, you can put each of the following statements in the
else of the previous if statement:
if a:
do_action_a()
else:
if b:
do_action_b()
else:
if c:
do_action_c()
else:
do_action_all_others()
However, there is an idiom for this: elif
so the pythonic is to use:
if a:
do_action_a()
elif b:
do_action_b()
elif c:
do_action_c()
else:
do_action_all_others()
Change the last conditional statement to
if category not in ('1', '2', '3', '4'):
print('\nPlease enter a valid option:')
category = str(input('. . .'))
My Refined Implementation of your code
import random
general_first = ['noob', 'baby', 'dude', 'soldier', 'discount']
general_last = ['kid', 'plant', 'painter', 'officer', 'conscience']
animal_first = ['frantic', 'fiesta', 'quick', 'quiet', 'loud']
animal_last = ['ferret', 'dog', 'hamster', 'cat', 'rabbit']
food_first = ['delicious', 'disgusting', 'stinky', 'fried', 'bitter']
food_last = ['pickle', 'chocolate', 'rice', 'water', 'lemonade']
name_first = ['dylan', 'eve', 'chris', 'simon', 'adele']
name_last = ['christopher', 'sharp', 'smith', 'james', 'baker']
def endNumber(): return str(random.randint(0, 100))
def firstName(values): return random.choice(values)
def lastName(values): return random.choice(values)
def generate_usernames(category):
if category == 1:
return firstName(general_first) + lastName(general_last) + endNumber()
elif category == 2:
return firstName(animal_first) + lastName(animal_last) + endNumber()
elif category == 3:
return firstName(food_first) + lastName(food_last) + endNumber()
elif category == 4:
return firstName(name_first) + lastName(name_last) + endNumber()
else:
return None
input_prompt = "What category do you want?" \
"\n'1' for general" \
"\n'2' for animals" \
"\n'3' for food" \
"\n'4' for human names" \
"\n\nCHOICE : "
invalid_prompt = "\nPlease enter a valid option"
print('\tUSERNAME GENERATOR')
while True:
input_category = int(input(input_prompt))
username = generate_usernames(input_category)
if username is not None:
print(f'Your Random Username is : {username}')
break
else:
print(invalid_prompt)
I'm trying to figure out how to use binary search on a list that was already sorted so I can have the user search for a name that was entered by the user and have it display the name if it's there or tell the user if it's not.
I cannot use built-in sort functions.
I have the bubble search setup to sort the list of names entered by the user, which is the code below:
def names():
members = []
done = False
while done != True:
mem = input("Enter a name, enter 'done' when finished: ")
if mem == "done":
done = True
else:
members.append(mem)
print(members)
index = len(members) - 1
sort = False
while not sort:
sort = True
for j in range(0, index):
if members[j] > members[j + 1]:
sort = False
members[j], members[j + 1] = members[j + 1], members[j]
#Here is the output for the first code:
Enter a name, enter 'done' when finished: Bob
['Bob']
Enter a name, enter 'done' when finished: George
['Bob', 'George']
Enter a name, enter 'done' when finished: Mike
['Bob', 'George', 'Mike']
Enter a name, enter 'done' when finished: Zed
['Bob', 'George', 'Mike', 'Zed']
Enter a name, enter 'done' when finished: Vorp
['Bob', 'George', 'Mike', 'Zed', 'Vorp']
Enter a name, enter 'done' when finished: done
['Bob', 'George', 'Mike', 'Vorp', 'Zed']
I created another function for searching the sorted list and this is where I'm stuck. I've attempted to take the sorted list and place it in my main() function but it's not printing anything.
def main(members):
name_search = input("Please enter the name you're looking for: ")
print(name_search)
begin_index = 0
end_index = len(members) -1
while begin_index <= end_index:
midpoint = begin_index + (end_index - begin_index) // 2
midpoint_value = members[midpoint]
if midpoint_value == members:
return midpoint
elif members < midpoint_value:
end_index = midpoint - 1
else:
begin_index = midpoint + 1
print(members)
return None
names()
Does anyone mind helping?
It's basically the same algorithm for regular binary search, simply replace the number list with the name list:
def binary(lst, sml, bg, x):
if bg >= sml:
mid = (bg + sml) // 2
if lst[mid] == x:
return mid
elif lst[mid] > x:
return binary(lst, sml, mid - 1, x)
else:
return binary(lst, mid + 1, bg, x)
else:
return -1
lst = ['Bob', 'George', 'Mike', 'Vorp', 'Zed']
x = input('Input the name: ')
index = binary(lst, 0, len(lst)-1, x)
if index != -1:
print(index)
else:
print("Not in list.")
Input:
Input the name: Mike
Output:
2
You are comparing the midpoint_value against the whole list instead of name_search. Try with this:
if midpoint_value == name_search:
return midpoint
elif name_search < midpoint_value:
end_index = midpoint - 1
else:
begin_index = midpoint + 1
Also for your future questions, make sure you provide a minimal reproducible example, e.g.:
def search(name_search, members):
begin_index = 0
end_index = len(members) -1
while begin_index <= end_index:
midpoint = begin_index + (end_index - begin_index) // 2
midpoint_value = members[midpoint]
if midpoint_value == name_search :
return midpoint
elif name_search < midpoint_value:
end_index = midpoint - 1
else:
begin_index = midpoint + 1
return None
members = ['Bob', 'George', 'Mike', 'Vorp', 'Zed']
name_search = 'George'
print(search(name_search, members))
# Kinematics clculator
print('Kinematics Calculator')
print('If either one of the three values(s,v,t) is not given then put its value = 1')
s = float(input('Enter your distance = '))
print(s)
t = float(input('Enter your time = '))
print(t)
v = float(input('Enter your velocity = '))
print(v)
if 'v == 1' :
print('velocity = '+ str(s/t))
elif 't == 1' :
print('time = '+ str(s/v))
else :
's == 1'
print('distance = '+ str(v*t))
Help me correct this code. Whenever I try to calculate anything else than "velocity" it always uses the first print command i.e
print('velocity = '+ str(s/t))
'v == 1' always evaluates to true, because it's a non-empty string. You should use
if v == 1:
print('velocity = '+ str(s/t))
elif t == 1:
print('time = '+ str(s/v))
else:
print('distance = '+ str(v*t))
input("Would you like to read: comedy, political, philisophical, or tragedy?")
a = "comedy"
b = "political"
c = "philisophical"
d = "tragedy"
if a:
input("Would you like the author's nationality to be: English or French?")
e = "French"
d = "English"
if e:
print("Tartuffe")
elif d:
print("Taming of the Shrew")
When I run the program is just defaults to comedy and then to Tartuffe.
How do I get it to recognize the difference genres in the string?
you need to store the input and then compare it to what you want, for example:
a = "comedy"
b = "political"
c = "philisophical"
d = "tragedy"
user_input = input("Would you like to read: comedy, political, philisophical, or tragedy?")
if user_input == a:
user_input = input("Would you like the author's nationality to be: English or French?")
if user_input == e:
#do more stuff
A better way to do this (in my opinion) would be to do something like:
def comedy():
print("comedy")
def political():
print("political")
def philisophical():
print("philisophical")
def tragedy():
print("tragedy")
types = {"comedy":comedy,
"political":political,
"philisophical":philisophical,
"tragedy":tragedy
}
user_input = input()
types[user_input]()
because its easier to manage and read the different inputs.
You are just testing if the value of e is true (the string is not null, hence it is true).
You are not storing the input either.
selection = input("Would you like the author's nationality to be: English or French? ")
if selection == e:
print("Tartuffe")
elif selection == d:
print("Taming of the Shrew")
Highly extensible code.
choices = {'e': ('French', 'Tartuffe'), 'd': ('English', 'Taming of the Shrew')}
cstr = ', '.join('%r = %s' % (k, choices[k][0]) for k in sorted(choices))
prompt = 'What would you like the author\'s nationality to be (%s): ' % cstr
i = input(prompt).lower()
print('%s: %s' % choices.get(i, ('Unknown', 'Untitled')))