Python Forum
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Def Command
#1
I have a couple questions about the command "def". Once you define something, say "greeting", and you write your script in it:

def greeting():
name = input('What's your name?')
print('Hi,', name.title())
age = input('How old are you?')
if age > 18:
print('Nice.')
So you define greeting, but you want to continue that outside of the "def" command, like:

greeting()
else:
print('Oh')
Can I continue a "if then" statement outside of defining a variable? Also, I use "greeting somewhere, after python has run the script, will it continue down the script? Say I want to go to a specific spot of code depending on how the user input is answered, how would I do that? Thanks
Reply
#2
Def is technically a statement, not a command. And you need to indent your code under the def statement (and under the if statement:

def greeting():
    name = input('What's your name?')
    print('Hi,', name.title())
    age = input('How old are you?')
    if age > 18:
        print('Nice.')
Note that this won't work in Python 3.0+, because input returns a string for age, which you are comparing to an integer. You would want to change the if statement to if age > int(18):.

And no, you can't continue the if with an else that is outside the function definition. It all has to be inside the function definition.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(Jan-15-2019, 02:56 AM)ichabod801 Wrote: Def is technically a statement, not a command. And you need to indent your code under the def statement (and under the if statement:
 def greeting(): name = input('What's your name?') print('Hi,', name.title()) age = input('How old are you?') if age > 18: print('Nice.') 
Note that this won't work in Python 3.0+, because input returns a string for age, which you are comparing to an integer. You would want to change the if statement to if age > int(18):. And no, you can't continue the if with an else that is outside the function definition. It all has to be inside the function definition.

Thanks for the info. Wouldn't "if age > '18':" work as well?
Reply
#4
(Jan-15-2019, 03:33 AM)Trinx Wrote: Thanks for the info. Wouldn't "if age > '18':" work as well?

Nope. String inequalities compare alphabetically, which means that '2' > '18' is true, and '152' > '18' is false.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020