Python is overlooking this section of code - python

I am trying to get python to loop a section of code by naming that piece of code and trying to loop it back when the else is called. But, I don't even have to put the code to loop in for python to overlook the defined code. It is almost like I made it invisible:
def main(): from here
weight = int(input("How much do you weigh?: "))
unit = input("Lbs or Kgs?: ")
if unit.upper() == ("KGS"):
converted = weight * 2.2
print("Your weight in pounds is: " + str(converted) + "pounds")
elif unit.upper() == ("LBS"):
converted = weight / 2.2
print("Your weight in kilograms is: " + str(converted) + "pounds")
to here
correct = input("Does This Look Correct? ")
if correct.upper() == "NO":
print("Let's try again then")
weight = float(input("How much do you weigh: "))
unit = input("Kgs or Lbs?: ")
if unit.upper() == "KGS":
converted = weight * 2.2
print("Your weight in pounds is: " + str(converted) + " pounds")
elif unit.upper() == ("LBS"):
converted = weight / 2.2
print("Your weight in kilos is: " + str(converted) + " kilograms")
else:
print("Have A Great Day Then!")

Functions only run when they're called. You have to call main() in the loop.
while True:
main()
correct = input("Does this look correct? ")
if correct.upper() == "NO":
print("Let's try again then")
else:
print("Have a great day then!")
break

Related

While loop is not executing at all and everything else looks right

I cannot get this while loop to work. Every time, it says something is wrong with it and I have NO idea what. I've tried capitalizing and uncapitalizing, tabbing, just about everything. I'm truly at my wits end, please help
def inputM():
print("Enter weight in kg")
weightm = float(input())
print("Enter heigh in meters")
heightm = float(input())
return weightm, heightm
def inputI():
print("Enter weight in pounds")
weighti = float(input())
print("Enter height in inches")
heighti = float(input())
return weighti, heighti
def healthindex (BMIList, BMINum, bmi, healthy):
if healthy == "b":
print (str(bmi))
elif healthy == "h":
index = 0
print ("Your bmi is" + (str(bmi))
while index < len(BMIList):
if bmi < BMINum[index]:
print ("And, you are " + BMIList[index])
return
index = index + 1
print("You are Obese")
return
BMIList = ["severly underweight", "underweight", "healthy", "overweight", "obese"]
BMINum = [12, 18.4, 24.9, 29.9, 200]
print("Welcome to BMI Calculator!")
print("Enter I for Imperial or M for Metric")
request = input().upper()
if request == "M":
weightm, heightm = inputM()
bmi = weightm/(heightm**2)
elif request == "I":
weighti, heighti = inputI()
bmi = (703*weighti)/(heighti**2)
else:
print("Invalid input")
print("Enter b to only see your bmi or enter h if you would like to see your bmi and health index")
healthy= input()
healthindex (BMIList, BMINum, bmi, healthy)
You have a syntax error in the print statement above the while loop. You are missing the closing parenthesis as you can see from the following snippet of your code:
print ("Your bmi is" + str(bmi)
while index < len(BMIList):

Running try and except in a function and re-running results in a NoneType return. How do I fix this?

I'm working on a simple program that allows the user to bet some virtual currency on a coin toss. Everything works fine, except for when the user inputs something incorrectly. For example: if a question asks for y/n response and the user puts 'd' or something as the response, the program will use the except ValueError and rerun the function. However, when the function is rerun and the user finally inputs something correctly, it will result in a further error.
Error:
> AttributeError: 'NoneType' object has no attribute 'lower'
Code:
import time
import random
money = 5000
last_interest_time = time.time()
def interest():
global money, last_interest_time
if time.time() - last_interest_time > 5:
prev_money = money
money *= 0.1
last_interest_time = time.time()
print("You now have " + str(money) + " monies (+" + str(money - prev_money) + ") from interest")
def game():
global money, last_interest_time
print("You have " + str(money) + " monies.")
choice = get_choice("Want to bet on a coin toss?", 'y','n')
if choice.lower() == 'y':
print("That's great!")
choice = get_choice("What side do you want to bet on?", 'h', 't')
bet_amount = get_bet()
print('Flipping the coin...')
time.sleep(1)
side = random.choice(['h', 't'])
if side == 'h':
print("The coin landed heads!")
elif side == 't':
print('The coin landed tails!')
if side == choice:
print("You won and received " + str(bet_amount) + " monies!")
money += bet_amount
else:
print("You lost the bet and " + str(bet_amount) + " monies!")
money -= bet_amount
game()
elif choice.lower() == 'n':
input('Oh well. Just type something if you want to bet again. ')
game()
def get_choice(question, response_1, response_2):
choice = input(question+" ("+response_1+'/'+response_2+'): ')
if choice != response_1 and choice != response_2:
print('Input is invalid. Must be '+response_1+'/'+response_2)
get_choice(question, response_1, response_2)
else:
return choice
def get_bet():
bet_amount = input("What amount do you want to bet?: ")
try:
if int(bet_amount) > money:
print("You don't have enough money!")
get_bet()
else:
return int(bet_amount)
except ValueError:
print('Invalid input. Must be a number')
get_bet()
game()
Debugging tip:
Print choice every time so you can see why it's crashing! You can take the print statement out later.
What I found was this:
get_choice() returned None.
In get_choice, if the input is invalid, it doesn't actually return anything. Oh no! So you're returning None, and calling .lower() on None throws the exception.
Solution:
You are on the right track when you run get_choice a second time if the input is invalid. One small tweak: instead of just running get_choice, return get_choice.
There is a similar bug in get_bet(), just a heads up, and you can solve it the same way.
Overall, great game.
.lower() runs on strings only and defining a variable with input() makes it not register as a string. Instead try something like this.
def set_choice():
choice = input("Want to bet on a coin toss?", 'y','n')
def choice():
choice = set_choice()
return choice
choice = choice.lower()

Outer Loop of nest won't trigger

This is some of my homework but i am really stuck and can't find any advice online.
def main():
endProgram = 'n'
print()
while endProgram == 'n':
total = 0
totalPlastic = 0
totalMetal= 0
totalGlass = 0
endCount = 'n'
while endCount == 'n':
print()
print('Enter 1 for Plastic')
print('Enter 2 for Metal')
print('Enter 3 for Glass')
option = int(input('Enter now: '))
if option == 1:
totalPlastic = getPlastic(totalPlastic)
elif option == 2:
totalMetal = getMetal(totalMetal)
elif option == 3:
totalGlass = getGlass(totalGlass)
else:
print('You have entered an invalid input')
return main()
endCount = input('Do you want to calculate the total? (y/n): ')
print()
total = calcTotal(totalPlastic, totalMetal, totalGlass)
printNum(total)
break
endProgram = input('Do you want to end the program? (y/n): ')
def getPlastic(totalPlastic):
plasticCount = int(input('Enter the number of Plastic bottles you have: '))
totalPlastic = totalPlastic + plasticCount * .03
return totalPlastic
def getMetal(totalMetal):
metalCount = int(input('Enter the number of Metal cans you have: '))
totalMetal = totalMetal + metalCount * .05
return totalMetal
def getGlass(totalGlass):
glassCount = int(input('Enter the number of Glass bottles you have: '))
totalGlass = (totalGlass + glassCount * .10)
return totalGlass
def calcTotal(totalPlastic, totalMetal, totalGlass):
total = totalPlastic + totalMetal + totalGlass
return total
def printNum(total):
print('Your total recyclable value is $', total)
main()
My problem is I run the code and it works fine for 99% of it. The program will ask any type and amount of bottle, and it totals it correctly too, the issue is that the outer loop never gets asked. After it prints the total it just goes right back to asking what type of bottle you have instead of asking you whether or not you want to end the program. Any help is appreciated thanks.
Remove the break just before Do you want to end the program? (y/n)
print()
total = calcTotal(totalPlastic, totalMetal, totalGlass)
printNum(total)
break
Here you are using break and the loop gets out and does not go forward.
break is used in while loop endProgram == 'n' and it breaks and never goes forwards.
One more thing it is a bad habbit of making defining first. Always define main after the other functions and do not just call main().
Use this -
if(__name__ == '__main__'):
main()
The break statement was exiting your script, therefore your line endProgram = input('Do you want to end the program? (y/n): ') was unreachable, that is why it was never "asked".
Also, fixed some of your indentation, give it a go.
def main():
endProgram = 'n'
print()
while endProgram == 'n':
total = 0
totalPlastic = 0
totalMetal = 0
totalGlass = 0
endCount = 'n'
while endCount == 'n':
print()
print('Enter 1 for Plastic')
print('Enter 2 for Metal')
print('Enter 3 for Glass')
option = int(input('Enter now: '))
if option == 1:
totalPlastic = getPlastic(totalPlastic)
elif option == 2:
totalMetal = getMetal(totalMetal)
elif option == 3:
totalGlass = getGlass(totalGlass)
else:
print('You have entered an invalid input')
return main()
endCount = input('Do you want to calculate the total? (y/n): ')
print()
total = calcTotal(totalPlastic, totalMetal, totalGlass)
printNum(total)
endProgram = input('Do you want to end the program? (y/n): ')
def getPlastic(totalPlastic):
plasticCount = int(input('Enter the number of Plastic bottles you have: '))
totalPlastic = totalPlastic + plasticCount * .03
return totalPlastic
def getMetal(totalMetal):
metalCount = int(input('Enter the number of Metal cans you have: '))
totalMetal = totalMetal + metalCount * .05
return totalMetal
def getGlass(totalGlass):
glassCount = int(input('Enter the number of Glass bottles you have: '))
totalGlass = (totalGlass + glassCount * .10)
return totalGlass
def calcTotal(totalPlastic, totalMetal, totalGlass):
total = totalPlastic + totalMetal + totalGlass
return total
def printNum(total):
print('Your total recyclable value is $', total)
main()

Game of Chance in Python 3.x?

I have this problem in my python code which is a coinflip game, the problem is that when It asks, "Heads or Tails?" and I just say 1 or Heads(same for 2 and Tails) without quotation marks and with quotation marks, it does not give me an answer that I am looking for.
I've Tried using quotation marks in my answer which didn't seem to work either.
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails?")
coinnum = random.randint(1, 2)
if coinnum == 1:
return 1
elif coinnum == 2:
return 2
win = bet*2
if choice == "Heads" or "1":
return 1
elif choice == "Tails" or "2":
return 2
if choice == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
elif choice != coinnum:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
The expected output was either "Well done! You have won 200 Dollars!" or "Sorry, you lost 100 Dollars!"
The first thing to note here is that your usage of return seems to be wrong. Please look up tutorials about how to write a function and how to use return.
I think this is what you were trying to do:
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails? ")
coinnum = random.randint(1, 2)
win = bet*2
if choice == "Heads" or choice == "1":
choicenum = 1
elif choice == "Tails" or choice == "2":
choicenum = 2
else:
raise ValueError("Invalid choice: " + choice)
if choicenum == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
else:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
Now, lets go through the mistakes I found in your code:
return was totally out of place, I wasn't sure what you were intending here.
if choice == "Heads" or "1" is invalid, "1" always evaluates to true. Correct is: if choice == "Heads" or choice == "1":
elif choice != coinnum: is unnecessary, if it doesn't run into if choice == coinnum: a simple else: would suffice.

Score system in game. PYTHON 3.5

def LoginScreen():
global User_Points
User_Points = 5
print("Welcome to Area Trainer")
print("Please enter the username for your account")
global user_name
user_name = str(input())
save = open(user_name + '.txt', 'w')
points = open(user_name + 'Score' + '.txt', 'w+')
points.write(str(User_Points))
PasswordCheck= True
while PasswordCheck:
user_password = input("type in your password: ")
if len(user_password) < 8:
print("your password must be 8 characters long")
elif not any(i.isdigit() for i in user_password):
print("you need a number in your password")
elif not any(i.isupper() for i in user_password):
print("you need a capital letter in your password")
elif not any(i.islower() for i in user_password):
print("you need a lowercase letter in your password")
else:
PasswordCheck = False
def MenuTriangle():
global User_Points
print('''Here is a triangle with a height of 12cm and a width of 29cm
/\ | *Not to scale.
/ \ |
/ \ | 12cm
/ \ |
<------->
29cm
You must find out the area and select the correct answer from these options''')
print('''A) 175
B) 174
C) 2000
D) 199
''')
user_input = input().upper()
if user_input == "A":
print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
MenuTriangle2()
elif user_input == "C":
print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
MenuTriangle2()
elif user_input == "D":
print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
MenuTriangle2()
elif user_input == "B":
print("Congratulations! You got it right, someone's a smart cookie. Here have two points!")
reading = open(user_name + 'Score' + '.txt')
score = reading.read()
score = int(score) + 2
print("Your score is", score)
points = open('ok' + 'Score' + '.txt', 'w+')
points.write(str(score))
MenuStart()
def MenuStart():
print("Welcome to the mathematical area game!")
print("In this game you will be required to calculate the area of multiple shapes.")
print("To do this you must know how to calculate the area of different shapes with increasing difficulty")
print('''Please select a shape you want to play,
A) Triangle
B) Square
C) Circle''')
user_input = input().upper()
if user_input == "A":
print("You have chosen to calculate the area of a triangle!")
MenuTriangle()
elif user_input == "B":
print("You have chosen to calculate the area of a square!")
MenuSquare()
elif user_input == "C":
print("You have chosen the calculate the area of a circle!")
MenuCircle()
else:
print("Oops! I didn't understand that >:")
MenuStart()
LoginScreen()
MenuStart()
Hello, I am trying to make a small game where the user has to guess what the area of the shape is and if they get it right then they get 2 points however, I am using an external file to store the score of the game in but every time I play through the game by entering my name, password I will see that the value of the score will be changed to 2 after I get the answer right but then when it calls the menu function the score in the file is reset and I don't know why
CORRECT ANSWER TO SAVE PRESSING BUTTONS IS B
THE ONLY OPTION AVAILABLE TO PLAY IS TRIANGLE FOR NOW. If anyone could please figure this out it would be greatly appreciated.
This is because Python automatically overrides data in a file every time it is being opened. You are opening the file multiple times by calling the function multiple times.

Categories

Resources