#def Statements with Parameters
Deduplication makes your programs shorter, easier to read, and easier to update.
import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Reply hazy try again'
elif answerNumber == 5:
return 'Ask again later'
elif answerNumber == 6:
return 'Concentrate and ask again'
elif answerNumber == 7:
return 'My reply is no'
elif answerNumber == 8:
return 'Outlook not so good'
elif answerNumber == 9:
return 'Very doubtful'
r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)
Note that since you can pass return values as an argument to another function call, you could shorten these three lines:
r = random.randint(1, 9)
fortune = get answer(r)
print(fortune)
to this single equivalent line:
print(getAnswer(random.randint(1, 9)))
##The None Value
##Keyword Arguments and print()
#Local and Global Scope
I learned how local and global scope is different and could imagine how return function can be used.
A variable that exists in a local scope is called a local variable, while a variable that exists in the global scope is called a global variable.
Local Variables Cannot Be Used in the Global Scope
Local Scopes Cannot Use Variables in Other Local Scopes
Global Variables Can Be Read from a Local Scope
Local and Global Variables with the Same Name
The global Statement
#Exception Handling
#A Short Program: Guess the Number
# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
#Short Practice: the Collatz Sequence
'''
If number is even, then collatz() should print number // 2 and return this value.
If number is odd, then collatz() should print and return 3 * number + 1.
'''
def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
'''
Lets the user type in an integer and that keeps calling collatz() on that number
until the function returns the value 1.
'''
print('Enter number:')
try:
info = int(input())
while info != 1:
info = collatz(info)
print(info)
except ValueError:
print('You must enter integer')