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 am trying to improve this program. I am working with Linux. I want to add a menu function where the user can pick an option and based on the option call the respective function, but the program is not working, when I run it in the Terminal it doesn't do anything and doesn't show any errors. Please, I need help to solve the problem and make the program works. Thanks!
Here's what I have so far, still there are some functions that need to develop:
#! /usr/bin/python3
import sys
def menu(self):
print ("""
1. Add an Expense
2. Remove an Expense
3. Add revenue
4. Remove Revenue
5. Exit
""")
option = input ("What would you like to do [Number Only]?")
if option == "1":
self.add_expense()
elif option == "2":
self.remove_expense()
elif option == "3":
self.add_revenue()
elif option == "4":
self.remove_revenue()
else:
self.reset_program()
self.close_program()
return option
def add_expense(self):
def __init__(self):
self.month_balance = 0
self.expenses = 0
self.expense_list = []
self.expense_name = []
self.month_balance_name = []
self.month_balance_list = []
self.prompt_income()
def month_balance_ask(self):
add_month_balance = input('Add monthly balance? [y/n]: ')
return add_month_balance
def month_balance_sum(self):
self.month_balance = sum(self.month_balance_list)
def expense_ask(self):
add_expense = input('Add expense? [y/n]: ')
return add_expense
def expense_sum(self):
self.expenses = sum(self.expense_list)
def month_balance_check(self):
if not self.month_balance_list:
print('Please enter at least one monthly balance. ')
self.prompt_month_balance()
def expense_check(self):
if not self.expense_list:
print('Please enter at least one expense. ')
self.prompt_expense()
def prompt_month_balance(self):
x = False
while not x:
result = self.month_balance_ask()
if result == 'y':
month_balance_input = int(input('Enter monthly balance. [Numbers Only]: '))
self.month_balance_list.append(month_balance_input)
month_balance_name = input('Enter monthly balance name. [Name Only]: ')
self.month_balance_name.append(month_balance_name)
else:
self.month_balance_check()
x = True
self.month_balance_sum()
name = [name for name in self.month_balance_name]
month_balance = [month_balance for month_balance in self.month_balance_list]
month_balancedict = dict(zip(name, month_balance))
for k in incomedict:
print(k + ': ', '$' + str(month_balancedict[k]))
print('Total user monthly balance: ', '$' + str(self.month_balance))
self.prompt_expense()
def prompt_expense(self):
x = False
while not x:
result = self.expense_ask()
if result == 'y':
expense_input = int(input('Enter expense amount. [Numbers Only]: '))
self.expense_list.append(expense_input)
expense_name = input('Enter expense name. [Name Only]: ')
self.expense_name.append(expense_name)
else:
self.expense_check()
x = True
self.expense_sum()
name = [name for name in self.expense_name]
expense = [income for income in self.expense_list]
expensedict = dict(zip(name, expense))
for k in expensedict:
print(k + ': ', '$' + str(expensedict[k]))
print('Total user expenses: ', '$' + str(self.expenses))
self.added_expense()
def added_expense(self):
expenseadded = self.month_balance - self.expenses
if expenseadded < 0:
print('You are in the negative, you have a deficit of ' + '$' + str(expenseadded))
if expenseadded == 0:
print('You have broken even, you are spending exactly as much as you make.')
if expenseadded > 0:
print('You are in the positive, you have a surplus of ' + '$' + str(expenseadded))
another = input('Would you like to run another analysis? [y/n]: ')
if another == 'y':
self.menu()
else:
self.reset_program()
self.close_program()
def remove_expense(self):
print("code goes here")
def add_revenue(self):
print("code goes here")
def remove_revenue(self):
print("code goes here")
def reset_program(self):
self.month_balance = 0
self.expenses = 0
del self.expense_list[0:]
del self.expense_name[0:]
del self.month_balance_name[0:]
del self.month_balance_list[0:]
self.prompt_month_balance()
def close_program(self):
print('Exiting Program.')
sys.exit(0)
While programming in Python I got stuck in a case where the while loop is not terminating even after the condition is being satisified then also
the code is as follows:
print('--- Alex\'s Calculator ---')
print('1. ADDition')
print('2. SUBstraction')
print('3. MULtiply')
print('4. DIVide')
print('5. EXIT')
x = int(input())
command = ' Enter Your Two numbers To Perform The Operation : '
def ini():
a = int(input())
b = int(input())
return a, b
def resultoo():
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a,b,c))
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
while x < 5:
if x == 1:
print(command)
a, b = ini()
c = a + b
resultoo()
elif x < 5:
break
As kuro specified in the comment, x can't be seen by your while loop because it's local to resultoo().
To solve it easily just add :
return x
at the end of resultoo()
and
x = resultoo()
in your while loop
You can use global var to this, change the this:
def resultoo():
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a,b,c))
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
into:
def resultoo():
global x
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a,b,c))
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
Explnation:
x is a global argument, that will be the same out of the function closure, but not inside of it, the function has it own params, so if you want to change a global argument that is initalizing outside the function, you will need to call the global statement before, that will make x the global x
When option 5 is entered you want to exit.
I added
import sys
and changed
elif x < 5:
to
elif x == 5:
and added
sys.exit(0)
I also added the getMenu() function
This is the complete code that is working in my editor:
import sys
def ini():
command = ' Enter Your Two numbers To Perform The Operation : '
print(command)
a = int(input())
b = int(input())
return a, b
def resultoo(a, b, c):
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a, b, c))
def getMenu(x):
if x == 0:
print("Choose menu item")
x = int(input())
elif x != 0:
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
return x
def main():
x = 0
while x < 5:
print('\n\n1. ADDition')
print('2. SUBstraction')
print('3. MULtiply')
print('4. DIVide')
print('5. EXIT\n')
x = getMenu(x)
if x == 1:
a, b = ini()
c = a + b
resultoo(a, b, c)
elif x == 5:
sys.exit(0)
else:
print("No valid menu item")
if __name__ == '__main__':
print('----------------------------------------------------------------------------------------------------------')
print('-------------------------------------------- Alex\'s Calculator -------------------------------------------')
main()
I also formatted your code (alt+Enter in Pycharm) to comply to PEP8 standards ;)
Trying to create a fill in the blanks quiz.
If I use a for loop when the answer is incorrect will always return to FIRST element on the list, is there any way to bypass this? or use a different loop?
See my full code below.
IT IS NOT FINAL
Will only work on EASY answer selection.
The issue will appear when answering correctly FIRST blank(Imagine) and failing on the second one.
Any help will be highly apreciatted.
imag = '***1*** there is no heaven, It is ***2*** if you try, No hell below us, Above us only sky, ***1*** all the people living for today, ***1*** there is no ***3***, It is not hard to do, Nothing to kill or die for, And no religion too, ***1*** all the people living life in ***4***.'
imag_ans = ['Imagine', 'easy', 'heaven', 'peace']
blanks = ['***1***', '***2***', '***3***', '***4**']
def level():
print 'Please select Level? (Easy / Medium / Hard)'
global a
a = raw_input()
if a == 'Easy':
return attempts()
if a == 'Medium':
return 'Med'
if a == 'Hard':
return 'Hard'
else :
print 'Invalid option'
print '\n'
return level()
def attempts():
print 'How many attempts will you need?'
global numberofatt
numberofatt = raw_input()
try:
float(numberofatt)
except ValueError:
print "Please enter a number for attempts"
return attempts()
numberofatt = int(numberofatt)
if numberofatt <= 0 :
print 'Please enter a positive number'
return attempts()
else :
return quiz(a)
def quiz(level):
i = 0
global user_ans
global i
print 'Please fill in the blanks, you have ' + str(numberofatt) + ' attempts'
for blank in blanks:
print 'Fill in blank' + blank
user_ans = raw_input()
if user_ans == imag_ans[i]:
i = i + 1
global imag
imag = imag.replace(blank, user_ans)
print "Correct!"
print imag
else :
return att()
n = 1
def att():
if n == numberofatt :
return 'Game Finished'
if user_ans != imag_ans[i]:
global n
n = n + 1
#blank = 0
print 'Try Again'
return quiz(a)
print level()
You could use while loop:
def level():
global a
a = raw_input('Please select Level? (Easy / Medium / Hard): ')
pending = True
while pending:
if a == 'Easy':
pending = False
return attempts()
elif a == 'Medium':
pending = False
return 'Med'
elif a == 'Hard':
pending = False
return 'Hard'
else :
print 'Invalid option'
print '\n'
Something similar could be applied for quiz(). As commented, you should check how global works. Also, revise the indentation (e.g.: in att()).
Im new to programming and I wrote a program to solve different variables in an equation. I have "if" "elif" and "else" set up to solve for different parts of the equation. For some reason though, it will only solve for the first part (the "if" part) I'll copy and paste the program below.
import math
print 'A=Pert Calculator'
print ''
print 'Created by Triton Seibert'
print ''
Y = raw_input('What letter would you like to solve for?: ')
if Y == 'A' or 'a' or '1':
print 'Solving for A'
print ''
P = float(raw_input('Set value for P (initial investment):'))
e = 2.71828
print ''
r = float(raw_input('Set value for r (rate):'))
print ''
t = float(raw_input('Set value for t (time in years):'))
print ''
ert = e**(r*t)
answer = P*ert
print 'A equals:'
print answer
elif Y == 'P' or 'p' or '2':
print 'Solving for P'
print ''
A = float(raw_input('Set value for A (Final answer):'))
e = 2.71828
print ''
r = float(raw_input('Set value for r (rate):'))
print ''
t = float(raw_input('Set value for t (time in years):'))
print ''
answer = A / math.e**(r*t)
print 'P equals:'
print answer
elif Y == 'R' or 'r' or '3':
print 'Solving for r'
print ' '
A = float(raw_input('Set value for A (Final answer): '))
P = float(raw_input('Set value for P (initial investment):'))
e = 2.71828
print ' '
t = float(raw_input('Set value for t (time in years):'))
print ' '
almost = A/P
getting_there = math.log10(almost)/math.log10(e)
answer = getting_there/t
print 'r equals:'
print answer
elif Y == 'T' or 't' or '4':
print 'Solving for t'
print ' '
A = float(raw_input('Set value for A (Final answer): '))
P = float(raw_input('Set value for P (initial investment):'))
e = 2.71828
print ' '
r = float(raw_input('Set value for r (rate):'))
print ' '
#equation here (not done yet)
print 't equals:'
print answer
else:
print 'Not yet'
#change log to ln : log base e (x) = log base 10 (x) / log base 10 (e)
This part always evaluates to True:
if Y == 'A' or 'a' or '1':
It's not doing what you think it's doing; it's doing this:
if (Y == 'A') or ('a') or ('1'):
and 'a' evaluates to True, so it passes. What you probably want is:
if Y in ['A', 'a', '1']: