Python 02

Python Functions 01

This posting series is based on Python tutorials by Clever Programmer and Nomad Coder, and it aims to study two materials and provide a comprehensive explanation of fundamental concepts to beginners.

If, else statement

Let’s build some logic for a very simple number guessing.

# number = winning_number
# If the number is right
  # then you are the winner
# else
  # you are not a winner; try next time

In CS, we call this logic build-up or description of the code Pseudocode

#  If the number is right
  # > True or False?
  # then you are the winner
# else
  # you are not a winner; try next time

If else statement checks the condition if it is true or false. With this statement, we are going to create a weather function.

Baby Weather APP

The logic will be as follows:

# Takes the input about the weather
# If it is raining outside, print an umbrella
# else if cloudy, print cloud
# else if the weather with the thunderstorm, print thunderstorm
# otherwise, print sunglasses

If the condition is three or more, use elif to check if the condition does not fit into it or else.

weather = input('What is the weather like? : ')

if weather == 'rain':
  print('☔')
elif weather == 'cloudy':
  print('☁️')
elif weather == 'thunderstorm':
  print('⚡')
else:
  print('😎')

comparison operators

In Python, there are some comparison operators.

(>, <, ==, <=, >=)

  • single = is the assignment operator which assigns the value of the right side of expression to left side operand (not comparison operator)
  • double == is checking if first varible is equals to second argument

Baby Grades App

Let’s build another app that will help to understand the if-else statement and comparison operators.

Pseudocode for baby grade checker

# Put the user score
# >=90: A
# >=80: B
# >=70: C
# >=60 : D
# <60: F
score = int(input('Put in your score here: '))

if score >= 90:
  print('A')
elif score >= 80:
  print('B')
elif score >= 70:
  print('C')
elif score >= 60:
  print('D')
else:
  print('F')

What about checking passing grades? Check either a SUPER PASS, passing, or failing grade.

if score > 100:
  print('SUPER PASS')
elif score >= 60 and score <= 100:
  print('passed')
else:
  print('failed')

Instead of using score >= 60 and score <= 100 let’s use more pythonic code

Pythonic code: clean code in Python way

if score > 100:
  print('Excellent')
elif 60 <= score <= 100:
  print('passed') # pythonic
elif score < 60 or score > 100:
  print('You either failed or SUPER PASSED')

If you run the code above, you will see the last line is not working properly.

It is because Python reads from top to bottom. That means when the condition matches the first one, python executes the code and stops there.

And & or

If you look at the above example, we have used and and or inside of the code. Did you feel any inconvenience reading those lines of code? Probably not, because Python is a high-level programming language, meaning Python code is close to what humans speak. This fact makes Python a straightforward programming language to read and write.

True and True == True
True and False == False
False and True == False
----------------------
True or False == True

Remember and needs both sides to be true or false. or needs only one side to be true.

Functions

Let’s talk about our main topic functions. Functions make developers more productive. The function is reusable code, allowing us to choose the data input we want to use for the result.

Define Function

Functions have a special syntax. Write a def in front of the function and space. The function name cannot have the whitespace, and ends with ():

def my_function():
  print("my_name")
# ❌ don't start function names with numbers.
# ❌ don't include whitespaces. Same as variable

Indentation

The function has two spaces(one tab) under the function name. See the above example. Python is sensitive to whitespace. Make sure to keep those rules. Otherwise, it will cause an error with your functions.

def right_function():
  print("✅")
# prints check mark
def wrong_function():
print("❌")
# prints nothing

Arguments (Parameters)

We already know the most used Python function. That is print() What we put inside of the print() is the function’s argument.

def say_hello(params):
  print("hello" + params)

say_hello(args)

The argument is what we pass in the function, and the parameters are the placeholders that receive the data from outside the function.

  • No arguments

    unlike print() to use function we need to call the function at the end.

def say_my_name():
  print('Josh Bang')
  print('Lisa')
  print('Jenny')
  print('Rose')

say_my_name() # 👈 "call" function
# call the function with trailing ()
  • One argument

    The function takes the argument inside of the parentheses function(arg).

def say_my_name(name):
  print(name)

say_my_name("Bob")
  • Multiple Arguments/default arguments

The function can take multiple arguments. Also, we can set default arguments for the function.

def greeting(name, greet='Hey Hey'):
  '''
  greeting takes two arguments, greet and name, and it greets the user
  >>> greeting('aloha', 'John')

  "aloha John!"
  '''
  print(f'{greet} {name}!')

greeting('aloha', 'Jane')
greeting('Flash')
greeting('Bob', 'Hello')

Run the code to check the results. greeting('Flash') doesn’t have enough argument, but because of the default value greet='Hey Hey' you should be able to see "Hey Hey Flash!"

  • Named Arguments / positional arguments

Assume that we use the same function above. If we run greeting('Hola', 'hola'), it will be very confusing. To avoid this, we can name the arguments.

# greeting('Hola', 'hola')
greeting(greet='Hola', name='Sancho')

'''
The result will be "Hola Sancho!"
'''

Apply

Let’s make a function to apply what we’ve learned so far.

Create a function that takes two numbers and sums two value.

Click me
def sum(a, b):
  '''
  Takes two integers and returns their sum
  '''
  return a + b

print(sum(1,3))

return

By far, we just print the result of the function. But what if we want to send the data outside of the function?

def tax_cal(money):
  print(money * 0.38)

tax_cal(9999999)

def paid_tax(tax):
  print(f"Thanks for paying ${tax}.")

paid_tax(3799999.62)

Alt text

Do we want to grab the value of the tax_cal(9999999) from the terminal and paste it in paid_tax again? That would be very inefficient. To use tax_cal(money) again in a different function, we need to return a result instead of print()

def tax_cal(money):
  return money * 0.38

def paid_tax(tax):
  print(f"Thanks for paying ${tax}.")

pay_tax = tax_cal(9999999)
paid_tax(pay_tax)

Alt text

Categories:

Updated:

Comments