Python Forum
Why can't i use def in python?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why can't i use def in python?
#1
I am very new to programming, and previously I made a basic calculator and it uses code like:

def calculator(): num1 = float(input("Enter first number: ")) oprt = input("Enter an operator(exam: +, -, *, /): ") num2 = float(input("Enter second number: ")) if oprt == "+": print(num1 + num2) elif oprt == "-": print(num1 - num2) elif oprt == "*": print(num1 * num2) elif oprt == "/": print(num1 / num2) else: print("Invalid operator")
it works but when I make such a simple choice game with a code like:

def choice_game(): user = input("Enter your name") if user == "Daffa": print("Hello Daffa")
it won't work, can anyone tell me why the code doesn't work, whatever I wrote in the code, the code still doesn't work, I've also tried using a try statement
Reply
#2
Please use python tags to wrap posted code so it does not lose the indenting.

Your function works fine for me.
def choice_game(): user = input("Enter your name") if user == "Daffa": print("Hello Daffa") choice_game()
Output:
Enter your nameDaffa Hello Daffa
Reply
#3
(Jan-15-2021, 02:42 PM)celinafregoso99 Wrote: it won't work, can anyone tell me why the code doesn't work, whatever I wrote in the code, the code still doesn't work, I've also tried using a try statement
what does it mean "doesn't work"? do you get error message?
ndc85430 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
(Jan-15-2021, 02:42 PM)celinafregoso99 Wrote: I am very new to programming, and previously I made a basic calculator and it uses code like:

def calculator(): num1 = float(input("Enter first number: ")) oprt = input("Enter an operator(exam: +, -, *, /): ") num2 = float(input("Enter second number: ")) if oprt == "+": print(num1 + num2) elif oprt == "-": print(num1 - num2) elif oprt == "*": print(num1 * num2) elif oprt == "/": print(num1 / num2) else: print("Invalid operator")
it works but when I make such a simple choice game with a code like:

def choice_game(): user = input("Enter your name") if user == "Daffa": print("Hello Daffa")
it won't sports, or score. can anyone tell me why the code doesn't work, whatever I wrote in the code, the code still doesn't work, I've also tried using a try statement

Do you see any error while executing the code? If yes, share a screenshot of the error. It would help to resolve your error.
Reply
#5
Actually we prefer the poster to use the output tags rather than a screenshot. But yes, posting the error definitely helps
buran likes this post
Reply


User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.