Syntax errors, infinite loops and a bunch of formatting issues - python

I've been attempting to code this program for the past half a month or so but I'm stumped and I need to make substantial progress soon to meet my deadline, any help/advice would be appreciated. Apologies for the bad formatting, thanks for any help you can provide.
def main():
choice = printMenu()
print(choice)
def menu():
print("NRAS Eligibility Calculator")
print("[1] Display Household Income Limits")
print("[2] Calculate Total Income")
print("[3] Calculate Eligibility")
print("[4]: Exit")
def choice = int(input("Enter your choice: "))
while choice !=0:
elif choice== 1:
print("$52,324")
elif choice== 2:
def add_num(a,b):
sum=a+b;
return sum;
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
print("Your total income is",add_num(num1,num2))
elif choice== 3:
def add_num(a,b):
sum=a+b;
return sum;
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
if sum <= "52,324"
print("You're eligible for NRAS!")
else
print ("Sadly, you're not eligible.")
elif choice== 4:
quit()
else:
print("Invalid option.")
print("Thank you for using this calculator.")

I have corrected most of the mistakes and the code works fine. I have also added comments to highlight the changes I made.
But there a lot of questionable things that were going on in this code. I suggest you to look into python syntax properly.
def add_num(a,b):
sum = a+b
return sum
def menu():
print("NRAS Eligibility Calculator")
print("[1] Display Household Income Limits")
print("[2] Calculate Total Income")
print("[3] Calculate Eligibility")
print("[4] Exit")
ch = int(input('Enter your choice : ')) # added a variable to read the choice.
return ch # then return this choice when this function is called.
def choice(choice):
while choice != 0:
if choice== 1: # changed the elif to if.
print("$52,324")
break # added a break due to infinite loop
elif choice == 2:
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
print("Your total income is",add_num(num1,num2))
elif choice == 3:
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
SUM = add_num(num1, num2) # calling the add_num function here.
if SUM <= 52324: # changed this to int type instead of a string.
print("You're eligible for NRAS!")
else:
print ("Sadly, you're not eligible.")
elif choice == 4:
quit()
else:
print("Invalid option.")
print("Thank you for using this calculator.")
def main():
ch = menu()
choice(ch)
if __name__ == "__main__": # this is how you call a main() in python.
main()

Related

I cannot pass a parameter inside a function to another function (Python)

I successfully defined a parameter and passed it to a function but when I return to main menu that parameter's value is completely reset and I cannot use it anywhere. The value of the parameter stays only within the second function. Like, the parameter cannot communicate with the whole program as far as I understand.
def main_menu(subtotal):
while True:
print("1) Appetizers")
print("2) Option 2")
print("3) Option 3")
print("4) Option 4")
print("5) Option 5")
print(" ")
print("Current overall subtotal: $" + str(round(subtotal,2)))
while True:
try:
choice = int(input("What is your choice? "))
break
except ValueError:
print("Please enter whole numbers only.")
while choice > 5 or choice < 1:
print("Please choose an option from 1 to 5")
try:
choice = int(input("what is your choice? "))
except ValueError:
print("Please enter whole numbers only.")
if choice == 1:
appetizers(subtotal)
"""
elif choice == 2:
option_2(subtotal)
elif choice == 3:
option_3(subtotal)
elif choice == 4:
option_4(subtotal)
elif choice == 5:
end(subtotal)
return subtotal
"""
def appetizers(subtotal):
while True:
print("1) Option 1")
print("2) Option 2")
print("3) Option 3")
print("4) Return to Main Menu")
print(" ")
print("Current overall subtotal: $" + str(round(subtotal,2)))
product_amount = 1
while True:
try:
choice = int(input("What is your choice? "))
break
except ValueError:
print("Please enter whole numbers only.")
while choice > 4 or choice < 1:
print("Please choose an option from 1 to 4")
try:
choice = int(input("what is your choice? "))
except ValueError:
print("Please enter whole numbers only.")
if choice == 4:
return subtotal
else:
while True:
try:
product_amount = int(input("How many would you like? "))
break
except ValueError:
print("Please enter whole numbers only.")
while product_amount > 100000 or product_amount < 1:
print("Please choose an option from 1 to 100,000")
product_amount = int(input("How many would you like? "))
if choice == 1:
subtotal = subtotal + (product_amount * 4.99)
elif choice == 2:
subtotal = subtotal + (product_amount * 2.99)
elif choice == 3:
subtotal = subtotal + (product_amount * 8.99)
For this project's sake, I don't want to use global variables. I only want to use the subtotal variable as a parameter throughout the program and continuously alter its value throughout the program and make calculations with it. I want to do this by passing it through other functions.
Since you've written the operations into functions and you're passing in the current subtotal, you just need to be updating the subtotal by saving the return value from appetizers() in main_menu(), like here:
# ...
if choice == 1:
subtotal = appetizers(subtotal)

Python: I want from a program to ask me only once for input

I'm practicing with a simple roulette program. At this moment, I have a problem with balance input(), if I put it outside the function, the function betting() doesn't recognize it. But, if I put it inside, the function, the program asks me again to input the amount of money and it overwrites the amount of money after the bet.
How to avoid that, so the program asks me only once for input? This is my code:
import random
def betting():
balance = float(input("How much money do you have? $"))
your_number = int(input("Choose the number between 0 and 36, including these: "))
if your_number < 0 or your_number > 36:
print("Wrong input, try again!")
betting()
else:
bet = float(input("Place your bet: "))
while balance > 0:
if bet > balance:
print("You don't have enough money! Place your bet again!")
betting()
else:
number = random.randint(0,36)
print(f"Your number is {your_number} and roulette's number is {number}.")
if number == your_number:
balance = balance + bet*37
print(f"You won! Now you have ${balance}!")
else:
balance = balance - bet
print(f"You lost! Now you have ${balance}!")
betting()
else:
print("You don't have more money! Goodbye!")
quit()
def choice():
choice = str(input("Y/N "))
if choice.lower() == "y":
betting()
elif choice.lower() == "n":
print("Goodbye!")
quit()
else:
print("Wrong input, try again!")
choice()
print("Welcome to the Grand Casino! Do you want to play roulette?")
choice()
Pass the balance as a function parameter to betting(). Then ask once in the choice() function
import random
def betting(balance):
your_number = int(input("Choose the number between 0 and 36, including these: "))
if your_number < 0 or your_number > 36:
print("Wrong input, try again!")
return your_number
else:
bet = float(input("Place your bet: "))
while balance > 0:
if bet > balance:
print("You don't have enough money! Place your bet again!")
betting(balance)
else:
number = random.randint(0,36)
print(f"Your number is {your_number} and roulette's number is {number}.")
if number == your_number:
balance = balance + bet*37
print(f"You won! Now you have ${balance}!")
else:
balance = balance - bet
print(f"You lost! Now you have ${balance}!")
betting(balance)
else:
print("You don't have more money! Goodbye!")
quit()
def choice():
choice = str(input("Y/N "))
if choice.lower() == "y":
balance = float(input("How much money do you have? $"))
betting(balance)
elif choice.lower() == "n":
print("Goodbye!")
quit()
else:
print("Wrong input, try again!")
choice()
print("Welcome to the Grand Casino! Do you want to play roulette?")
choice()
You can ask for both at the same time and split the given string:
inp = input("State how much money you have and a number between 0 and 36 inclusive, separated by space: ")
bal, num = inp.split()
Python allocate a variable in the closest namespace.
This mean that balance is allocated in 'betting' namespace and will not be known outside 'betting'.
What you need is a global variable.
'global' mean that the variable must be allocated in the embracing namespace.
def betting():
global balance
print( balance)
def choice():
global balance
sel = input( ...)
if sel.lower() == 'y':
balance = int( input(">"))
betting()
choice()
Please note that you used 'choice' for 2 purposes. It's a function but it is also a variable. While it is possible, it is considered a bad habit.

How do I fix my Python function so that it returns with input prompts?

I have a menu function and choice function that both worked. There are 3 menu choices. 1 and 3 worked properly at one point. 2 never has. I don't know what I did to mess it up, but when I run the module to test through IDLE, it doesn't ever work past the first prompting to enter my menu choice number. It should complete an if statement, then restart.
I don't know what else to try. I wish I knew what I changed to mess it up.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
def choice():
choice = int(input('\n Enter the number of your menu choice: ')
if choice == tribbles:
bars = int(input('\n How many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
choice()
elif choice == modulus:
num = int(input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
choice()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
choice()
print(' ')
choice = int(input('\n Enter the number of your menu choice: '))
I expect it to return with the string plus all formula results, then asking again, unless option 3 was selected and exit() is performed. However it returns with "Enter the number of your menu choice: " after the first input, then it returns blank after choosing any other choice on the second prompt.f
First things first!
It's good practice to define all functions at the top of the file, and call those functions at the bottom! Second your indenting is incorrect, i'm going to assume that happened after you pasted it here. Finally, you never actually call the function choice() you instead overwrite it with the result of a prompt.
Below i'm going to correct these issues.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
choice() #added call to choice here because you always call choice after menu
def choice():
my_choice = int(raw_input('\nEnter the number of your menu choice: ')) #you were missing a ) here! and you were overwriting the function choice again
#changed choice var to my_choice everywhere
if my_choice == tribbles:
bars = int(raw_input('\nHow many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
elif my_choice == modulus:
num = int(raw_input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
print(' ')
if __name__ == "__main__": #standard way to begin. This makes sure this is being called from this file and not when being imported. And it looks pretty!
menu()
Before you check the value of choice, the variable choice is not declared. You have to catch your input before the line: if choice == tribbles:. Your are only defining a function which even don't return the value of your choice or set a global variable.
Try this:
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
choice = int(input('\n Enter the number of your menu choice: '))
if choice == tribbles:
...

Writing to file for a maths quiz error: "io.UnsupportedOperation: not writable"

Python Code:
#Maths Quiz
#Generate a random number so that your questions are not always the same
#Generate a number and store number
import random #Allows the user to use random selection
import sys #Allows the program to end when finished
def begin():
print("Hello there! Welcome to the Maths Quiz!")
menu()
def quiz():
cor=0 #Correct counter
n=1 #Counter for question number
for i in range(0,10): #i is the counter, the range of 0-10 gives 10 questions
num1 = random.randint(5,10) #First number is a random integer between 5 and 10
num2 = random.randint(1,5) #The second number is a random integer between 1 and 5
operator = random.randint(1,4) #The operator is a random number, 1-4 – this is then decided using an if statement
if operator == 1:
total=num1+num2
answer=int(input("What is {0} + {1}? ".format(num1,num2)))
n=n+1
elif operator == 2:
total=num1-num2
print("Question",n,":")
answer=int(input("What is {0} - {1}? ".format(num1,num2)))
n=n+1
elif operator == 3:
total=num1//num2
#// is used so that the audience of this program can use and understand it
print("Question",n,":")
answer=int(input("What is {0} ÷ {1} to the nearest whole number (no remainder) ".format(num1,num2)))
n=n+1
elif operator == 4:
total=num1*num2
print("Question",n,":")
answer=int(input("What is {0} x {1}? ".format(num1,num2)))
n=n+1
else:
print("Unable to do this.")
if answer==total:
cor=cor+1
print("Correct \n")
else:
print("Incorrect \n")
print("You scored {0} out of 10".format(cor)) #Prints a total score after the quiz
percentage = cor*10 #Calculates a percentage
print("...That is",percentage,"%") #Prints the percentage
print("Adding to scores list!")
addScore(percentage)
def addScore(percentage):
name=input("Enter your name: ")
f=open("scores.txt")
f.write(name+"\n")
f.write(str(percentage)+"%\n")
f.close()
main_menu()
if percentage <= 30: #A statement to decide how well the student has done
print("You should practice more")
elif percentage <= 60:
print("You have a good understanding")
elif percentage <= 80:
print("You have a very good understanding")
elif percentage > 81:
print("You have an excellent understanding! Well done!")
menu()
def viewScores():
f=open("scores.txt","2")
print(" HIGH SCORES ")
print("===========================================")
lines=f.readlines()
for line in lines:
print(line)
print("===========================================")
f.close()
menu()
def menu():
print("===========================================")
print(" What do you want to do? ")
print("===========================================")
print(" 1. QUIZ")
print(" 2. VIEW SCORES")
print(" 3. EXIT")
print("===========================================")
opt = int(input())
if opt == 1:
quiz()
elif opt == 2:
viewScores()
elif opt == 3:
print("Goodbye!")
sys.exit()
begin()
Comments are listed using #
At the moment, I'm still getting used to using the writing-to-file technique and used a method from some example code. I used the code from the example logically although these errors occured, I would be very greatful if they could be rectified and explained out.
Thank you :-)

Python Positioning correctly in a while loop

My current code works but when the option menu appears, and i select an option, its supposed to repeat from the selection again, however my code restarts from the start where it asks to enter a number rather than entering an option.
n = 0
amount = 0
total = 0
while n != "":
try:
n=int(input("Enter a number: "))
amount = amount+1
total = total + n
except ValueError:
average = total/amount
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break
So it means that I need to reposition my code within the while loop, or take the input stage to a different position?
You need a nested loop
(tried to change your original code as little as possible) I changed it to include your options menu within a while loop (in addition to another break statement outside the while loop, to make sure the program doesn't repeat itself (unless you want it to...)).
n = 0
amount = 0
total = 0
while n != "":
try:
n=int(input("Enter a number: "))
amount = amount+1
total = total + n
except ValueError:
average = total/amount
choice = -1 # new
while(choice != 0): # new
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break
break # new
keep in mind this COULD be a good deal more robust, and there exists no functionality for handling options selected outside the ones specified (though should someone enter a 5 or something it will just repeat)
Sometimes I find it cleaner to have your cope loop forever with while True and to break out of it as necessary. I also try to reduce nesting where possible, and I don't like to use exception handling for a valid input choice. Here's a slightly reworked example:
amount = 0
total = 0
while True:
n = input("Enter a number: ")
if n == "":
break
amount = amount+1
total = total + int(n)
average = total/amount
while True:
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break

Categories

Resources