INTRO   O

PROBLEM SOLVING AND

PROGRAMMING IN PYTHON

 

(use the Space key to navigate through all slides)

Prof. Andrea Gallegati
tuj81353@temple.edu

Prof. Dario Abbondanza
tuk96119@temple.edu

CIS 1051 - VARS & FUNCTS

THE "Hello, World!"

print()

A built-in Python function to display output.

 

"Hello, World!"

A string (text enclosed in quotes).

Better, a string litteral or an anonymous string.

HACK THE FUNCTION

Is a rule that assigns:


each valid input (from domain)
exactly one output (into range)

WHY print() ?

in mathematics

Input:
any real number

 

Output:
the square of that number

Input:
any real number

 

Output:
that number increased by 2

f(x) = x^2
g(x) = x+2

INTERACTIVE

vs SCRIPTING

MODES

Try it out into your Codespace!

# main.py - We'll start by printing
# the classic "Hello, World!" message.

print("Hello, World!")  # inline comment.

# Storing a name (string) into a variable
# and concatenate it to the string "Hello, "
# to use in a print statements.

name = "Alice"
print("Hello, " + name + "!") # <--- Here!

# Assign two integer variables and
# print their sum directly.

num1 = 5  # First integer variable
num2 = 7  # Second integer variable
print("Their sum is:", num1 + num2)

# Assign the sum to a third integer
# variable and then print it.

total = num1 + num2  # Storing their sum.
print("The sum (stored) is:", total)

# This script is made of 24 lines + an 
# empty one + these 5 lines of comments.
# Copy paste it into your GitHub codespace
# creating a new file named "main.py" and
# go to the next slide to see how to run it!

VARIABLES

A name that refers to a value.

Assignment

Programming languages are usually able to manipulate variables.

Variable Names

  • as long as you like
  • both letters and numbers
  • never begin with numbers
message = "Hello, World!"
n = 110 # Integer number
pi = 3.141592653589793

try out names like: 101dalmatians, b@tman, class, import , ...

# These keywords cannot be used to name variables and
# most IDE usually highlight them with different colors

False      class      finally    is         return
None       continue   for        lambda     try
True       def        from       nonlocal   while
and        del        global     not        with
as         elif       if         or         yield
assert     else       import     pass
break      except     in         raise

EXPRESSIONS

A combination of values, variables, and operators.

STATEMENTS

Units of code with an effect, e.g. assigning a variable.

The interpreter executes statements, doing whatever they say.

 

Most of the times it evaluates expressions.

Order of Operations

For mathematical operators, Python follows mathematical convention (PEMDAS).

  • Parentheses (highest precedence).

  • Exponentiation.

  • Multiplication and Division.

  • Addition and Subtraction.

#COMMENTS

Formal languages are dense:

difficult to say what a piece of code is doing.

 

Explain in natural language:

add notes to your programs to explain what they are doing.

 

They start with the # symbol.

a trade-off

  • document non-obvious features
  • avoid redundant comments
  • good variable names reduce needs for comments
  • avoid long complex variable names
# main.py - We'll start by printing
# the classic "Hello, World!" message.

print("Hello, World!")  # inline comment.

# Storing a name (string) into a variable
# and concatenate it to the string "Hello, "
# to use in a print statements.

name = "Alice"
print("Hello, " + name + "!") # <--- Here!

# Assign two integer variables and
# print their sum directly.

num1 = 5  # First integer variable
num2 = 7  # Second integer variable
print("Their sum is:", num1 + num2)

# Assign the sum to a third integer
# variable and then print it.

total = num1 + num2  # Storing their sum.
print("The sum (stored) is:", total)

# This script is made of 24 lines + an 
# empty one + these 5 lines of comments.
# Copy paste it into your GitHub codespace
# creating a new file named "main.py" and
# go to the next slide to see how to run it!

FUNCTIONS

a named sequence of statements that performs a task.

 

To define a function specify:

  • the name
  • the sequence of statements

 

Later, you can “call” the function by name.

Similar to what we said for values and variables.

type(110)
type("Hi!")

FUNCTION CALLS

type:

the name of the function

 

argument:

the value passed

(aka input)

 

result:

the return value

(aka output)

A function “takes” an argument and (often) “returns” a result.

DEFINING

FUNCTIONS

  • function name
  • sequence of statements

 

header:

starts with def keyword
and ends with a colon.

 

body:

has to be indented.

# main.py - A script to demonstrate the concept of
# functions: reusable blocks of code. Functions 
# help us organize our code and avoid repetition.

# ------------------------------------------------
# 1) A Simple Function.
#   - This function doesn't take any parameters.
#   - It simply prints "Hello, World!" to console.

def greet():
    print("Hello, World!") 

# Let's call it:
greet()

# ------------------------------------------------
# 2) A Function with Parameters.
#   - This function takes strings as parameter.
#   - It prints a personalized greeting message.

def greet_person(name):
    print("Hello, " + name + "!")

# Let's call it:
greet_person("Alice")

RECURSION

def greet():
    """
    - Prints a basic greeting message.
    - Calls greet_morning to continue the chain.
    """
    print("Hello! Welcome to the greeting chain.")  # First greeting
    greet_morning()  # Call the next function

def greet_morning():
    """
    - Prints a 'Good morning' message.
    - Calls greet_evening to continue the chain.
    """
    print("Good morning! Have a great start to your day.")  # Morning greeting
    greet_evening()  # Call the next function

def greet_evening():
    """
    - Prints a 'Good evening' message.
    - Ends the chain here.
    """
    print("Good evening! Have a restful night.")  # Evening greeting

# ---------------------------------------------------------------
# Start the chain by calling greet.
# ---------------------------------------------------------------
greet()
print("End of script. All functions in the chain have been executed.")

you don’t always want to read a program
from top to bottom.

... it makes more sense to follow the flow of execution!

Each function definition has to run before the function gets called!

VARIABLES SCOPE

# --------------------------------------------------------------------------------
# Simulating a conversation between two persons using functions with arguments.
# --------------------------------------------------------------------------------

def start_conversation(person1, person2):
    """
    - Prints a greeting from person1 to person2 and "ask_question" to continue.
    """
    print(f"{person1}: Hi {person2}! How are you doing today?")
    ask_question(person2, person1)  # Pass the names in reverse order to simulate a reply

def ask_question(person1, person2):
    """
    - person1 asks person2 a question and "give_answer" to continue the.
    """
    print(f"{person1}: I'm good, {person2}! What are your plans for the weekend?")
    give_answer(person2, person1)  # Pass the names in reverse order to simulate a response

def give_answer(person1, person2):
    """
    - person1 gives an answer to person2's question.
    """
    print(f"{person1}: I’m planning to go hiking, {person2}. What about you?")

start_conversation("Alice", "Bob")
print("End of conversation. The simulation is complete.")

When you create a variable inside a function, it is local.

This means that it only exists inside the function.

The functions we have seen
so far are:

VOID FUNCTIONS

perform an action but don’t return a value.

void functions might:

  • display something on the screen
  • have some other effect

 

Assigning the result to a variable, you get a special value called None.

if your function returns a value

you usually want to do something with it:

  • assign to a variable
  • use within an expression

 

We will see it.

WHY FUNCTIONS?

divide a program into functions:

  • name a group of statements
  • makes a complex
    programs simpler
  • eliminate repetitive code

 

Well-designed functions are then reusable.

This was crafted with

A Framework created by Hakim El Hattab and contributors
to make stunning HTML presentations

variables-functions

By Andrea Gallegati

variables-functions

  • 100