(Basic?) File compiles fine, doesn't execute as intended - python

I'm running this on cygwin using atom as my editor. Python3.
Hi,
Basic Python question that really baffles me. I've looked around on SO and found a lot of questions regarding similiar issues, but can't find one that covers the issue I'm facing.
Before I go into details; this is an assignment that I'm working on so if you don't want to spill "all the beans", then just give me some sort of guidance.
I've been tasked with splitting a chat-bot into two files, one that handles the main() function and one that handles all the possible functions that the input-choices from main() uses.
For some reason both files compile fine, but when I call main.py
(either by >python main.py // // // // or by > ./main.py)
I get no prompt at all. Neither do I get a prompt while trying the same with marvin.py.
Both files are in the same directory.
This is main():
#!/usr/bin/env python3
import marvin
def main():
"""
This is the main method, I call it main by convention.
Its an eternal loop, until q is pressed.
It should check the choice done by the user and call a appropriate
function.
"""
while True:
menu()
choice = input("--> ")
if choice == "q":
print("Bye, bye - and welcome back anytime!")
return
elif choice == "1":
myNameIs()
elif choice == "2":
yearsToSec()
elif choice == "3":
weightOnMoon()
elif choice == "4":
minsToHours()
elif choice == "5":
celToFahr()
elif choice == "6":
multiplyWord()
elif choice == "7":
randNumber()
elif choice == "8":
sumAndAverage()
elif choice == "9":
gradeFromPoints()
elif choice == "10":
areaFromRadius()
elif choice == "11":
calcHypotenuse()
elif choice == "12":
checkNumber()
else:
print("That is not a valid choice. You can only choose from the menu.")
input("\nPress enter to continue...")
if __name__ == "__main__":
main()
As you can see I do import marvin after the environment-variables have been loaded.
There are no indentation errors or anything else when compiling either files (as mentioned above).
Disclaimer: I don't think you need to read marvin, tbh...
And this is marvin.py:
#!/usr/bin/env python3
from random import randint
import math
def meImage():
"""
Store my ascii image in a separat variabel as a raw string
"""
return r"""
_______
_/ \_
/ | | \
/ |__ __| \
|__/((o| |o))\__|
| | | |
|\ |_| /|
| \ / |
\| / ___ \ |/
\ | / _ \ | /
\_________/
_|_____|_
____|_________|____
/ \
"""
def menu():
"""
Display the menu with the options that Marvin can do.
"""
print(chr(27) + "[2J" + chr(27) + "[;H")
print(meImage())
print("Welcome.\nMy name is Ragnar.\nWhat can I do for you?\n")
print("1) Present yourself to Ragnar.")
print("2) Have Ragnar calculate your minimum age (in seconds).")
print("3) Have Ragnar calculate weight on the moon.")
print("4) Try Ragnar's abilities by having him calculate minutes to hour(s).")
print("5) Have Ragnar calculate Fahrenheit from Celcius.")
print("6) See if Ragnar can multiply a word of your liking by a factor of your choice.")
print("7) Have Ragnar print 10 numbers within a range of your choice.")
print("8) Keep entering numbers and have Ragnar print their sum and average.")
print("9) Let Ragnar calculate your grade by entering your score!.")
print("10) Let Ragnar calculate the area of a circle with the radius of your choice.")
print("11) Let Ragnar calculate the hypotenuse of a triangle with the sides of your choice.")
print("12) Have Ragnar compare a given number to your previous number.")
print("q) Quit.")
def myNameIs():
"""
Read the users name and say hello to Marvin.
"""
name = input("What is your name? ")
print("\nMarvin says:\n")
print("Hello %s - your awesomeness!" % name)
print("What can I do you for?!")
def yearsToSec():
"""
Calculate your age (years) to seconds
"""
years = input("How many years are you?\n")
seconds = int(years) * (365 * 24 * 60 * 60)
print(str(years) + " would give you " + str(seconds) + " seconds.")
return
def weightOnMoon():
"""
Calculate your weight on the moon
"""
weight = input("What is your weight (in kiloes)?\n")
moonGrav = float(weight) * .2
print(str(weight) + " kiloes would weigh be the same as " + str(moonGrav) + " kiloes on the moon.")
def minsToHours():
"""
Calculate hours from minutes
"""
minutes = input("How many minutes would you want to converted to hour(s)?\n")
hours = float(format(float(minutes) / 60, '.2f'))
print(str(minutes) + " hours is " + str(hours) + " hours")
def celToFahr():
"""
Calculate celcius to Fahrenheit
"""
cel = input("Please insert Celcius to be calculated to Fahrenheit.\n")
fah = float(format(float(cel) * 1.8 + 32, '.2f'))
print(str(cel) + " is " + str(fah) + " in Fahrenheit units.")
def multiplyWord():
"""
Multiply word n-times
"""
word = input("Please enter the word.\n")
factor = input("And please give me the product to multiply it by!")
word *= int(factor)
print("The word is:\n" + str(word))
def randNumber():
"""
Adds 10 random numbers (depending on user range)
to a string.
"""
rangeMin = input("What is the lower number in your range?\n")
rangeMax = input("What is the higher number in your range?\n")
sequence = ""
for num in range(0, 10):
sequence += str(randint(int(rangeMin), int(rangeMax))) + ", "
num = num
print("The random sequence is:\n" + sequence[:-2])
def sumAndAverage():
"""
Adds numbers to the sum and calculate the average value of the input(s)
"""
summa = 0
count = 0
temp = input("Please enter a number to be added to the sum. \nEnter 'q' if you wish to finish!\n")
while True:
if temp == "q":
print("The sum of your numbers are: " + str(summa) + "\nAnd the average is: " + str(summa/count))
return
else:
try:
summa += int(temp)
count += 1
temp = input("Please enter a number to be added to the sum. \nEnter 'q' if you wish to finish!\n")
except ValueError:
print("That's not an int! \nPlease try again!")
def gradeFromPoints():
"""
Shows the user's grade based on his / her points
"""
points = input("How many points did you score?\n")
if(float(points) >= 1 and float(points) <= 100):
points = float(points) / 100
if float(points) >= 0.9:
print("You got an A!")
elif float(points) >= 0.8 and float(points) < 0.9:
print("You got a B!")
elif float(points) >= 0.7 and float(points) < 0.8:
print("You got a C!")
elif float(points) >= 0.6 and float(points) < 0.7:
print("You got a D!")
else:
print("You failed the class")
def areaFromRadius():
"""
Calculates a circles area based on it's radius
"""
radius = input("What is the circle's radius?\n")
area = (float(radius) * float(radius)) * 3.1416
print("The area of the circle is: " + str(format(area, '.2f')))
print("This was calculated with this formula: (radius^2) * 3.1416")
def calcHypotenuse():
"""
Calculates a triangle's hypotenuse based on it's sides
"""
side1 = input("How long is the first side?\n")
side2 = input("How long is the second side?\n")
hypotenuse = math.sqrt((float(side1) * float(side1)) + (float(side2) * float(side2)))
print("The hypotenuse is: " + str(hypotenuse))
def compareNumbers(a, b):
"""
Compares two numbers
"""
if (a > b):
print("Your previous number was larger!")
return a
elif (a < b):
print("Your new number was larger!")
return b
else:
print("They were equal!")
return a
def validateInt(a):
"""
Validates that an input is an integer
"""
if a == 'q':
return a
else:
flag = False
while (flag == False):
try:
a = int(a)
flag = True
except ValueError:
print("That's not an int! \nPlease try again!")
a = input("Try again!\n")
return a
def checkNumber(prev="first"):
"""
Checks the number
"""
print("\n=================\n")
if prev == "first":
prev = validateInt(input("Please input a number. Press 'q' if you wish to end\n"))
print("\n=================\n")
new = validateInt(input("Please input a number. Press 'q' if you wish to end\n"))
if new == 'q' or prev == 'q':
print("You have exited the loop\n")
return
else:
compareNumbers(int(prev), int(new))
checkNumber(str(new))
else:
new = validateInt(input("Please input a number. Press 'q' if you wish to end\n"))
if new == 'q':
print("You have exited the loop!\n")
return
else:
compareNumbers(int(prev), int(new))
checkNumber(str(new))
FULL DISCLAIMER: I'm sure there are bunches of improvments I can do,
but I'm only interested in understanding why the files won't execute
even though they compile fine...

if __name__ == "__main__":
main()
should not be indented.
In your current code, the main() method is run in the else block, but you never get there because the program won't start because you just define the main() method but never execute it.
Unindent it and it will be executed as it won't be in a function definition anymore.

The functions defined in marvin.py are not globals in main.py; they are members of the marvin module object. So, this:
elif choice == "1": myNameIs()
should be changed to this:
elif choice == "1": marvin.myNameIs()
The same goes for the rest of the places where main.py is using functions from marvin.py.

Related

designing a game in python where random mathematical problems appear for the user to solve

The code is supposed to generate random equations for the user to answer with num1 being in the range of 1 to 9 while num2 in the range 0,10
The user starts with 100 points
if user enters x the program terminates
if user enter wrong answer the score decreases by 10
if user enters correct answer the score increases by 9
I've been successful in doing steps one to 3 however when it comes to checking if the inputted answer by the user is correct it always returns it as wrong even if its correct example
I assume this is because my code doesn't evaluate the question and been trying to figure out why
import random
# set variables
score = 100 # score of user
operator = ["+", "-", "*", "/"] #operators
number_1 = random.randint(1, 9) # this variable will be a random number between 1 and 9
number_2 = random.randint(0, 10) # this variable will be a random number between 0 and 10
# this function prints the dashes
def dash():
print("-" * 50)
while score >= 0 and score <= 200:
dash()
print("You currently hold: ", score, " points")
print("Get more than 200 points you win, under 0 you lose")
sign = random.choice(operator) # chooses random operator
real_answer = number_1,sign,number_2
print(str(number_1) + str(sign) + str(number_2), "?")
dash()
print("Press x to close program")
answer = input("Enter your guess of number: ")
if answer == "x":
print("Program has been terminated properly")
break
elif answer == real_answer:
score = score + 9
continue
elif answer != real_answer:
score = score - 10
continue
if score < 0:
print("Unlucky, You lost")
elif score > 200:
print("CONGRATULATIONS YOU WON")
Issue was that real_answer and inputted answer were different data types, this should fix it by making them both floats.
import random
# set variables
score = 100 # score of user
operator = ["+", "-", "*", "/"] #operators
number_1 = random.randint(1, 9) # this variable will be a random number between 1 and 9
number_2 = random.randint(0, 10) # this variable will be a random number between 0 and 10
# this function prints the dashes
def dash():
print("-" * 50)
while score >= 0 and score <= 200:
dash()
print("You currently hold: ", score, " points")
print("Get more than 200 points you win, under 0 you lose")
sign = random.choice(operator) # chooses random operator
# make a variable called real answer equal to the answer of the equation
if sign == "+":
real_answer = number_1 + number_2
elif sign == "-":
real_answer = number_1 - number_2
elif sign == "*":
real_answer = number_1 * number_2
elif sign == "/":
real_answer = number_1 / number_2
print(str(number_1) + str(sign) + str(number_2), "?")
dash()
print("Press x to close program")
answer = input("Enter your guess of number: ")
if answer == "x":
print("Program has been terminated properly")
break
elif float(answer) == real_answer:
score = score + 9
continue
elif float(answer) != real_answer:
score = score - 10
continue
if score < 0:
print("Unlucky, You lost")
elif score > 200:
print("CONGRATULATIONS YOU WON")
The error here is that the variable real_answer is not an integer, but instead a tuple. For example, 1+7 gives (1, '+', 7), instead of 8.
Their are two main fixes to this:
The first fix is to create a dictionary which can contain the functions for each symbol. It would look something like this:
signs = {
'+': (lambda a, b: a + b),
'-': (lambda a, b: a - b),
'*': (lambda a, b: a * b),
'/': (lambda a, b: a // b)
}
Now, to call this function, you can do real_answer = signs[sign](number_1,number_2). Essentially, this calls the function from the dictionary depending on what the sign is. If the sign is / the code recognises that divide means lambda a, b: a // b and calls this function with number_1 and number_2
The other, but slightly more messy verisio is to use eval. What eval does is runs a string as code. For example, you could do:
real_answer = eval(f"{number_1}{sign}{number_2)")
While this does work, eval is generally not the best method.
The last thing to point out is that you don't cast your answer variables to an integer. When comparing numbers in your if statements, you want to use int(answer) to make sure you're using the integer version of your answer.
The full code should look something like this:
import random
# set variables
score = 100 # score of user
operator = ["+", "-", "*", "/"] #operators
number_1 = random.randint(1, 9) # this variable will be a random number between 1 and 9
number_2 = random.randint(0, 10) # this variable will be a random number between 0 and 10
signs = {
'+': (lambda a, b: a + b),
'-': (lambda a, b: a - b),
'*': (lambda a, b: a * b),
'/': (lambda a, b: a // b)
}
# this function prints the dashes
def dash():
print("-" * 50)
while score >= 0 and score <= 200:
dash()
print("You currently hold: ", score, " points")
print("Get more than 200 points you win, under 0 you lose")
sign = random.choice(operator) # chooses random operator
real_answer = signs[sign](number_1,number_2)
print(str(number_1) + str(sign) + str(number_2), "?")
dash()
print("Press x to close program")
answer = input("Enter your guess of number: ")
if answer == "x":
print("Program has been terminated properly")
break
elif int(answer) == real_answer:
score = score + 9
continue
elif int(answer) != real_answer:
score = score - 10
continue
if score < 0:
print("Unlucky, You lost")
elif score > 200:
print("CONGRATULATIONS YOU WON")

Why isnt the indexing in this python script working?

I'm writing this script for an assignment so I'd appriciate being talked through it rather than simply being handed an answer. Basically I'm trying to convert feet to meters, meters to feet, and provide a sum of the total converted distance in both at the end. Without the [] indexes, It was working perfectly. The new part I've only just added and am struggling with is the [] indexes, and to be honest I'm having a hell of a time groking how they work. Anyways heres the code:
MAX = 256
switch = ""
feet = [0.0] * MAX
meters = [0.0] * MAX
feetpermeter = 3.28084
metersperfoot = 0.3048
sum_meters = 0
sum_feet = 0
def main():
selector()
def selector():
while True:
print("Is your measurement in meters or feet?")
switch = input("Or would you like to quit?")
if (switch == "feet" or switch == "Feet"):
ftm()
elif (switch == "meters" or switch == "Meters"):
mtf()
elif (switch == "quit" or switch == "Quit"):
end()
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
def mtf():
try:
meters[sum_meters] = float(input("Enter the number of meters. "))
feet[sum_feet] = meters * feetpermeter
print("That is", feet, "feet.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
def ftm():
try:
feet[sum_feet] = float(input("Enter the number of feet. "))
meters[sum_meters] = feet * metersperfoot
print("That is", meters, "meters.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
ftm()
def end():
while True:
switch2 = input("Are you sure you want to quit(y/n)?")
if (switch2 == "y" or switch2 == "Y"):
print("you converted a total of ", sum(feet), "feet")
print("And", sum(meters), "meters.")
print("Bye!")
exit()
elif (switch2 == "n" or switch2 == "N"):
print("Ok, let's try that again.")
main()
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
main()
I did try having sum_feet + 1 and sum_meters + 1 after each result but that hadnt worked either.
You are not using the indexing in a proper way. For instance , look at the comments on your existing code:
def mtf():
try:
# Error 1. You stored all the inputs to index 0, as sum_meters is 0 always and its not incremented
# So, all the inputs are not recorded, only last one gets in index 0
meters[sum_meters] = float(input("Enter the number of meters. "))
# Error 2: You multiplied the whole list against the conversion parameter.
# Instead, you should multiply the value at current index
feet[sum_feet] = meters * feetpermeter
# This will print the whole list. Again use the current index here
print("That is", feet, "feet.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
A fixed version of your function will be like:
def mtf():
try:
# For modifying global variables in a function scope
global sum_meters
global sum_feet
meters[sum_meters] = float(input("Enter the number of meters. "))
feet[sum_feet] = meters[sum_meters] * feetpermeter
print(f"That is {feet[sum_feet]} feet.")
sum_meters += 1
sum_feet += 1
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
This fixes stands true for your other functions as well.
I also thought to give you another piece of advice, that you can use a good object oriented approach for such problems, which makes it simpler to implement. You can learn a lot about that, then you will feel more confident.
As an example, see the below code - which does almost same, but in a more crisp way.
class Converter:
FEET_PER_METER = 3.28084
METERS_PER_FOOT = 0.3048
def __init__(self):
self.feet_store = []
self.meter_store = []
self.curr_index = 0
self.menu_handlers = {
"feet": self.feet_to_meter,
"meters": self.meter_to_feet,
"quit": self.summary
}
def run_selection(self, selected):
#
selected = str.lower(selected)
if selected in self.menu_handlers:
# call the relevant function
return self.menu_handlers.get(selected)()
return False
def meter_to_feet(self):
meters_in = float(input("Enter the number of meters."))
to_feet = meters_in * self.FEET_PER_METER
self.meter_store.append(meters_in)
self.feet_store.append(to_feet)
print(f"In Feet : {to_feet}")
return to_feet
def feet_to_meter(self):
feet_in = float(input("Enter the number of feet."))
to_meters = feet_in * self.METERS_PER_FOOT
self.feet_store.append(feet_in)
self.meter_store.append(to_meters)
print(f"In Meters : {to_meters}")
return to_meters
def summary(self):
confirm = input("Are you sure you want to quit(y/n)?")
if confirm in ["y", "Y"]:
print("you converted a total of ", sum(self.feet_store), "feet")
print("And", sum(self.meter_store), "meters.")
print("Bye!")
exit()
else:
return False
def main():
converter = Converter()
while True:
choice = input("Is your measurement in meters or feet (meters/feet/quit)?")
converter.run_selection(choice)
I hope this gives you better insights.
So theres two problems with what you've tried to do here, in the lines:
meters[sum_meters] = float(input("Enter the number of meters. "))
feet[sum_feet] = meters * feetpermeter
meters * feetpermeter is multiplying an array by a number, you need to do meters[sum_meters] to get the number you want. Secondly as you said, you need to increment sum_meters each time, but because you're inside a function you will need to declare the variable as a global before you change it. Also since sum_meters and sum_feet are always going to be equal, you can just use a single variable to keep track of this:
def mtf():
try:
global index
meters[index] = float(input("Enter the number of meters. "))
feet[index] = meters[index] * feetpermeter
index += 1
print("That is", feet, "feet.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
def ftm():
try:
global index
feet[index] = float(input("Enter the number of feet. "))
meters[index] = feet * metersperfoot
index += 1
print("That is", meters, "meters.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
ftm()
I would also go a little further and say that the use of lists is unnecessary for this problem, you could simply have two numbers, total_meters and total_feet and add the values as you go. This would take less memory and also remove the arbitrary limit of 256 goes that has been imposed. So I would do:
import sys
MAX = 256
switch = ""
total_feet = 0
total_meters = 0
feetpermeter = 3.28084
metersperfoot = 0.3048
sum_meters = 0
sum_feet = 0
index = 0
def main():
selector()
def selector():
while True:
print("Is your measurement in meters or feet?")
switch = input("Or would you like to quit?")
if switch == "feet" or switch == "Feet":
ftm()
elif switch == "meters" or switch == "Meters":
mtf()
elif switch == "quit" or switch == "Quit":
end()
sys.exit(0)
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
def mtf():
try:
global total_feet
global total_meters
meters = float(input("Enter the number of meters. "))
feet = meters * feetpermeter
total_meters += meters
total_feet += feet
print("That is", feet, "feet.")
main()
except Exception as e:
print(e)
print("Sorry, I didn't quite get that, lets try again.")
mtf()
def ftm():
try:
global total_feet
global total_meters
feet = float(input("Enter the number of feet. "))
meters = feet * metersperfoot
total_meters += meters
total_feet += feet
print("That is", meters, "meters.")
main()
except Exception as e:
print(e)
print("Sorry, I didn't quite get that, lets try again.")
ftm()
def end():
while True:
switch2 = input("Are you sure you want to quit(y/n)?")
if switch2 == "y" or switch2 == "Y":
print("you converted a total of ", total_feet, "feet")
print("And", total_meters, "meters.")
print("Bye!")
exit()
elif switch2 == "n" or switch2 == "N":
print("Ok, let's try that again.")
main()
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
main()

There's an issue somewhere in my Python code.. I can't find where it's at

I don't know what's wrong with it.. I run it and I'm able to input a number but then it stops working. It says, "TypeError: play_game() missing 1 required positional argument: 'limit.' But I'm not sure what's missing there??
#!/usr/bin/env python3
import random
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess >= number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game()
again = input("Play again? (y/n): ")
print()
print("Bye!")
# if started as the main module, call the main function
if __name__ == "__main__":
main()
You have defined your play_game function to take limit as a parameter, but when you call this function in your main loop, you don't supply a value in the brackets of play_game().
You could either try adding that limit value that you've specified by calling it like
play_game(25)
Or, based on your code, since you're asking the user to provide a limit, call it like:
play_game(limit)
Or, if you want to be able to call play_game() without setting a limit, then change your play_game definition line to something like:
def play_game(limit=25):
Which will set a default value of 25 whenever that function is called without supplying the limit value.
Yes, play_game() needs the parameter limit. I've done a quick check on your code, and there is some additional problem
the count variable isn't initialized
you calculate the random number in every step
guess > number should be used instead of guess >= number
Here is the fixed code, it works for me. I hope it will be usefull:
import random
count = 0
number = -1
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
global number, count
if number == -1:
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess > number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(limit)
again = input("Play again? (y/n): ")
print()
print("Bye!")
In your main you are calling playgame() without providing a limit as an argument.
Your main should look something like
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(10)
again = input("Play again? (y/n): ")
print()
print("Bye!")

Why is the except statment in menu() getting triggered through normal use of the play() function?

This program is about storing the scores and weather related variables for someone playing a game of archery. The expept statment in menu() is to stop out of bounds inputs from being put into the program, but somehow when i'm using the play() function, when n = 0 the except statment is menu() is getting triggered and I can't understand why. all the functions that are being caled are below.
import time, datetime, statistics
from statistics import mean
def storeScore():
def Average(list):
return mean(list)
global score
list = []
list.insert(0, score)
global average
average = Average(list)
def Play():
if guest == False:
n = int(input("Please enter the number of shots you will be firing:"))
weather = input("Please enter the current weather, excluding wind:")
wind = input("Please enter the wind conditions:")
other = input("please enter any other conditions to be recorded:")
avgscore = 0
while n > 0:
print("Please fire your arrow now")
time.sleep(3)
global score
score = int(input("please enter the score for this arrow:"))
n = n-1
storeScore()
myList =[n, weather, wind, other, avgscore]
with open("data.txt", 'w') as f:
for s in myList:
f.append(str(s) + '\n')
print("Thanks you, your data was logged")
printAvg
time.sleep(3)
resetloop()
def menu():
print("*********************************************\n"
"* WELCOME, PLEASE CHOOSE AN OPTION *\n"
"* *\n"
"* 1. REGISTER A GUEST *\n"
"* 2. CREATE A FULL DATA EXPORT *\n"
"* 3. VIEW YOUR AVERAGE SCORE (50 SHOTS +) *\n"
"* 4. PLAY A ROUND *\n"
"* 5. CHECK COMPETITION READYNESS *\n"
"* 6. EXIT *\n"
"*********************************************\n")
Menu_Choice = input("please enter a number from 1-6 for your chosed option:")
try:
if Menu_Choice =="1":
Guest()
elif Menu_Choice =="2":
Data_Export()
elif Menu_Choice =="3":
Average()
elif Menu_Choice =="4":
Play()
elif Menu_Choice =="5":
Contest()
elif Menu_Choice =="6":
exit()
else:
raise Exception
except Exception:
print("This is an invalid input, please anter an interger number between 1-6 in number form")
time.sleep(2)
resetloop()
def resetloop():
print(" ")
menu()

While/if loop giving me trouble (beginner)

I have been trying to make my first "solo" python program, its a calculator where you pick what kind of formula you want it to calculate and then input the variables needed. I got issues with my while/for loop, when i run the program i get the correct menu: menu(), and then when I choose my next menu by inputting 1 i correctly get the "v_menu" however if I input 2, which should get me the "m_menu", I instead just get the v_menu like I would if I typed in a 1.
I hope my explanation made sense, im still very new to all of this. Appreciate any help I can get, been breaking my head over this for atleast one hour or so..
Cheers, and heres my code:
# coding=utf-8
#Menues
def menu():
print "Choose which topic you want in the list below by typing the corresponding number\n"
print "\t1) virksomhedsøkonomi\n \t2) matematik\n"
return raw_input("type the topic you want to pick\n >>")
def v_menu():
print "Choose which topic you want in the list below by typing the corresponding number"
print "\t1) afkastningsgrad\n \t2) overskudsgrad\n \t3) aktivernes omsætningshastighed\n \t4) Egenkapitalens forrentning\n \t5) return to main menu\n"
return raw_input("Type the topic you want to pick\n >>")
def m_menu():
print "Choose which topic you want in the list below by typing the corresponding number"
print "\t1) omregn Celsius til Fahrenheit\n \t2) omregn Fahrenheit til Celsius\n"
return raw_input("Type the topic you want to pick\n >>")
# - Mat -
#Celsius to Fahrenheit
def c_to_f():
c_temp = float(raw_input("Enter a temperatur in Celsius"))
#Calculates what the temperatur is in Fahrenheit
f_temp = c_temp * 9 / 5 + 32
#Prints the temperatur in Fahrenheit
print (str(c_temp) + " Celsius is equal to " + str(f_temp) + " Fahrenheit")
#Fahrenheit to Celsius
def f_to_c():
f_temp = float(raw_input("Enter a temperatur in Fahrenheit"))
#Calculates what the temperatur is in celsius
c_temp = (f_temp - 32) * (float(100) / 180)
#Prints the temperatur in celsius
print (str(f_temp) + " Fahrenheit is equal to " + str(c_temp) + " Celsius")
#Program
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == "1" or "1)":
v_menu()
elif choice == "2" or "2)":
m_menu()
if choice == "1":
c_to_f()
elif choice == "2":
f_to_c()
loop = 0
Your problem is in your if statements: if choice == "1" or "1)":
What you really need is: if choice == "1" or choice == "1)":
Everything after the or gets evaluated as another expression. You're saying "if choice is equal to one or if one exists."
"1)" evaluates to "true" in this instance, so you'll always hit that branch.
The problem is here;
if choice == "1" or "1)":
v_menu()
elif choice == "2" or "2)":
You have to write them like;
if choice == "1" or choice == "1)":
v_menu()
elif choice == "2" or choice == "2)":
Otherwise, all the time your if statement is True. And if first if statement is True, then your elif statement is not going to work. That's why you can't call v_menu()

Categories