(use the Space key to navigate through all slides)
Prof. Andrea Gallegati |
Prof. Dario Abbondanza |
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.
Is a rule that assigns:
each valid input (from domain)
exactly one output (into range)
Input:
any real number
Output:
the square of that number
Input:
any real number
Output:
that number increased by 2
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!
Programming languages are usually able to manipulate variables.
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
A combination of values, variables, and operators.
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.
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.
# 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!
a named sequence of statements that performs a task.
To define a function specify:
Later, you can “call” the function by name.
FUNCTION CALLS
type:
the name of the function
argument:
the value passed
(aka input)
result:
the return value
(aka output)
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")
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.")
# --------------------------------------------------------------------------------
# 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.")
void functions might:
Assigning the result to a variable, you get a special value called None.
you usually want to do something with it:
We will see it.
divide a program into functions:
Well-designed functions are then reusable.
A Framework created by Hakim El Hattab and contributors
to make stunning HTML presentations