Why am I getting a " Traceback (most recent call last):" error? - python

I'm sorry for asking, but I can't find why I'm getting this errors, especially after the program is running.
The erros to be exact are:
>>>
Welcome! This program will convert measures for you.
Select operation.
1.Miles to Kilometers
2.Fahrenheit to Celsius
3.Gallons to liters
4.Pounds to kilograms
5.Inches to centimeters
Enter your choice by number: 1
Traceback (most recent call last):
File "C:\Users\Levhitor\Downloads\Mario_Gomez_Lab2.py", line 112, in <module>
intro()
File "C:\Users\Levhitor\Downloads\Mario_Gomez_Lab2.py", line 12, in intro
main()
File "C:\Users\Levhitor\Downloads\Mario_Gomez_Lab2.py", line 25, in main
convertMK()
File "C:\Users\Levhitor\Downloads\Mario_Gomez_Lab2.py", line 44, in convertMK
input_M = float(raw_input(("Miles: ")))
TypeError: 'int' object is not callable
I don't understand what's happening here. Can anyone help me?
raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(raw_input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: %f\n" % M_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(raw_input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: %f\n") % F_conv
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(raw_input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: %f\n" % G_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(raw_input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: %f\n" % P_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(raw_input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: %f\n" % inches_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I do not know what is wrong... can anyone help me?
Thanks you!

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(raw_input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: %f\n" % M_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(raw_input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: %f\n") % F_conv
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(raw_input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: %f\n" % G_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(raw_input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: %f\n" % P_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(raw_input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: %f\n" % inches_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:
TypeError: 'int' object is not callable
My code for Python 3 is as follows:
# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error
raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: {M_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: {F_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: {G_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: {inches_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
# Printing error in the line below
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
I hope this helps.

Related

how to loop from the start when i want to keep using my calculator. and after i use it i want it to close if i type 9

When I want to quit my calculator it works, but when I want to keep using it there comes a problem:
File "main.py", line 54, in <module>
main()
NameError: name 'main' is not defined
I want to keep looping it from the start if I type y or Y so that I could keep using it.
And if I type 9 after I use it, I can't come to the closing screen. So I want it to show the close screen and stop looping.
here's my code:
print("calculator")
print("1.Pluss")
print("2.Minus")
print("3.Ganging")
print("4.Deling")
print("9.Avslutt")
chr=int(input("1-4 eller Avslutt: "))
while True:
if chr==1:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=b+a
print("sum = ", c)
elif chr==2:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=a-b
print("sum = ", c)
elif chr==3:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=a*b
print("sum = ", c)
elif chr==4:
a=int(input("Number 1:"))
b=int(input("Number 2:"))
c=a/b
print("sum = ", c)
elif chr==5:
print("1-4 idiot")
elif chr==6:
print("1-4 idiot")
elif chr==7:
print("1-4 idiot")
elif chr==8:
print("1-4 idiot")
else:
print("Thank you for using my calculator!")
again = input("Do you want to keep using my calculator? y/n")
if again == "y" or again == "Y":
main()
else:
print("Thank you!")
break
It works if I want to quit, but it can't keep looping from the start after it comes to.
print("Thank you for using my calculator!")
again = input("Do you want to keep using my calculator? y/n")
if again == "y" or again == "Y":
main()
else:
print("Thank you!")
break
If you are offering an option to terminate (9. Avslutt) you don't need to ask user for confirmation of iteration. Just repeat the input prompts.
There's no need to convert the user input to int as the values are not used in any arithmetic context - i.e., they're just strings.
You may find this pattern useful:
from operator import add, sub, mul, truediv
OMAP = {'1': add, '2': sub, '3': mul, '4': truediv}
while True:
print("calculator")
print("1. Pluss")
print("2. Minus")
print("3. Ganging")
print("4. Deling")
print("9. Avslutt")
if (option := input('1-4 eller avslutt: ')) == '9':
break
if (op := OMAP.get(option)) is None:
print('Ugyldig alternativ')
else:
x = float(input('Number 1: '))
y = float(input('Number 2: '))
print(f'Resultat = {op(x, y):.2f}')

How to loop in python multiples times

i have assignment and we need to convert celsius to fahrenheit and vice versa. i have to loop the program but i dont know how.
my code is working but its still wrong.
def main():
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return((9/5)*C) + 32
temp =float(input("Enter Temp: "))
print(temp,"Celsius is",c_to_f(temp),"Fahrenheit")
if choice =="b":
def f_to_c(F):
return (5/9)*(F-32)
temp =float(input("Enter Temp: "))
print(temp,"Fahrenheit is",f_to_c(temp),"Celsius")
repeat = input("Do you want to convert again? (Yes/No): ")
for _ in range(10):
if repeat == "yes":
main()
else:
exit()
main()
Hi that's because variable has scope in which you can read their modifications, repeat modification in main() are not visible outside of their scope: here the main function.
Variables thatcan be "inspect" everywhere are called globals, and you should declare them at the beggining of a file outside of a function.
You have many solution to your problem, if you want to stay close from your actual code, here is one:
from sys import exit
def main():
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return((9/5)*C) + 32
temp =float(input("Enter Temp: "))
print(temp,"Celsius is",c_to_f(temp),"Fahrenheit")
if choice =="b":
def f_to_c(F):
return (5/9)*(F-32)
temp =float(input("Enter Temp: "))
print(temp,"Fahrenheit is",f_to_c(temp),"Celsius")
return input("Do you want to convert again? (Yes/No): ")
for _ in range(10):
repeat = main()
if repeat.lower() == 'no':
exit()
The problem with your code is that you ran main() after finishing in your last line of code
This will work great for you:
def main():
for _ in range(10):
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return ((9 / 5) * C) + 32
temp = float(input("Enter Temp: "))
print(temp, "Celsius is", c_to_f(temp), "Fahrenheit")
if choice == "b":
def f_to_c(F):
return (5 / 9) * (F - 32)
temp = float(input("Enter Temp: "))
print(temp, "Fahrenheit is", f_to_c(temp), "Celsius")
repeat = input("Do you want to convert again? (Yes/No): ")
if repeat == "yes":
main()
else:
exit()
if __name__ == '__main__':
main()
The problem with your code is your last user input.
This will work great for you:
def main():
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return((9/5)*C) + 32
temp =float(input("Enter Temp: "))
print(temp,"Celsius is",c_to_f(temp),"Fahrenheit")
if choice =="b":
def f_to_c(F):
return (5/9)*(F-32)
temp =float(input("Enter Temp: "))
print(temp,"Fahrenheit is",f_to_c(temp),"Celsius")
repeat = str(input("Do you want to convert again? (Yes/No): "))
for _ in range(10):
if repeat == "yes" or repeat == "Yes":
main()
else:
exit()
if __name__ == '__main__':
main()
Have Fun with CODE :)
This code should work
choice = 'y';
while choice != 'e':
choice = input('If you want to convert c to f press a\nIf you want to convert f to c press b\nIf you want to exit press e');
if choice == 'a':
c = int(input('Enter temp in C'));
print("F =", c*1.8+32);
elif choice == 'b':
f = int(input('Enter temp in F'));
print("C =", (F-32)/1.8);

Python - Replaying While Loop Dice Roll Game

How should I get the below loop to replay if the user types in an invalid response after being asked if they want to roll the dice again?
I can't get it to work without messing with the while loop. Here's what I have so far
# Ask the player if they want to play again
another_attempt = input("Roll dice again [y|n]?")
while another_attempt == 'y':
roll_guess = int(input("Please enter your guess for the roll: "))
if roll_guess == dicescore :
print("Well done! You guessed it!")
correct += 1
rounds +=1
if correct >= 4:
elif roll_guess % 2 == 0:
print("No sorry, it's", dicescore, "not", roll_guess)
incorrect += 1
rounds +=1
else:
print("No sorry, it's ", dicescore, " not ", roll_guess, \
". The score is always even.", sep='')
incorrect += 1
rounds +=1
another_attempt = input('Roll dice again [y|n]? ')
if another_attempt == 'n':
print("""Game Summary""")
else:
print("Please enter either 'y' or 'n'.")
I would suggest you do it with two while loops, and use functions to make the code logic more clear.
def play_round():
# Roll dice
# Compute score
# Display dice
# Get roll guess
def another_attempt():
while True:
answer = input("Roll dice again [y|n]?")
if answer == 'y':
return answer
elif answer == 'n':
return answer
else:
print("Please enter either 'y' or 'n'.")
def play_game():
while another_attempt() == 'y':
play_round()
# Print game summary

Name 'y' is not defined, python code to find even or odd numbers

I am writing a simple code to find even or odd numbers, the code was working just fine but maybe I did something wrong and it started giving me this error.
File "d:\Python\EvenOddFinder.py", line 12, in restart
restartornot = input()
File "", line 1, in
NameError: name 'y' is not defined
#Even or Odd Number Finder.
def start():
userInput = input("Please input your number:")
userInput = int(userInput)
if userInput %2 == 0:
print("The number " + str(userInput) + " is Even.")
else:
print("The number " + str(userInput) + " is Odd.")
def restart():
print("Do you want to restart?")
print("Y/N")
restartornot = input()
if restartornot == "Y":
start()
elif restartornot == "y":
start()
elif restartornot == "N":
exit()
elif restartornot == "n":
exit()
else:
print("Invalid Input.")
restart()
restart()
start()
Please help me I am quite new to Python.
Assuming you are using Python 2 you should try using
restartornot = raw_input()

Python program asks for input twice, doesn't return value the first time

Here is my code, in the get_response() function, if you enter 'y' or 'n', it says invalid the first time but then works the second time.
How do I fix this?
import random
MIN = 1
MAX = 6
def main():
userValue = 0
compValue = 0
again = get_response()
while again == 'y':
userRoll, compRoll = rollDice()
userValue += userRoll
compValue += compRoll
if userValue > 21:
print("User's points: ", userValue)
print("Computer's points: ", compValue)
print("Computer wins")
else:
print('Points: ', userValue, sep='')
again = get_response()
if again == 'n':
print("User's points: ", userValue)
print("Computer's points: ", compValue)
if userValue > compValue:
print('User wins')
elif userValue == compValue:
print('Tie Game!')
else:
print('Computer wins')
def rollDice():
userRoll = random.randint(MIN, MAX)
compRoll = random.randint(MIN, MAX)
return userRoll, compRoll
def get_response():
answer = input('Do you want to roll? ')
if answer != 'y' or answer != 'n':
print("Invalid response. Please enter 'y' or 'n'.")
answer = input('Do you want to roll? ')
main()
answer != 'y' or answer != 'n': is always true; or should be and.
It should be answer != 'y' and answer != 'n':
You're logically thinking that "answer is not y OR n", but in code that is
not (answer == 'y' or answer == 'n')
Apply DeMorgans' rule you get
answer != 'y' and answer != 'n'
Perhaps you should restructure using in.
You'll also want to return answer
def get_response():
while True:
answer = input('Do you want to roll? ')
if answer not in {'y', 'n'}:
print("Invalid response. Please enter 'y' or 'n'.")
else:
return answer

Categories

Resources