Part 1 - Basic Concepts: Input, Output, and Data Types Explained


A good first program is having your computer ask you for input and react to your answers. This will teach you valuable tips and tricks, like printing text to your terminal.
We will create a small program that asks the user for personal info and greets him accordingly. Then, we'll refine our program as an excuse to cover some interesting subjects.
What’s a program?
At its core, a program is an algorithm acting on data. An algorithm is a series of instructions to accomplish a task. An everyday example of an algorithm is when you tell a friend the way to your house:
From your house, drive to Main Street
Drive up to the department store, then take a left turn
Drive up to the next crossing, then turn left
Go another for a mile
Etc etc.
Computer chips can be instructed in the same way. You give them instructions and hope they don't get lost on the way. The difference with your friend is that computers (barring artificial intelligence, I guess) are very rigid regarding the instructions they accept. You need to teach them with special purpose programming languages, like Python.
Data, too, needs to be structured in a way pleasing to your computer.
Python uses an interpreter to run your code, a special program that runs other programs.
The first naive version
Type this into your favorite editor, and then execute it. If you don't understand a line, try to delete it or change it and watch what happens. Don't be afraid to experiment. I've added comments to explain the code as it unfolds before you. Those start with a #
. They don't execute and are there only to help us understand the code better. The """
delimit docstrings. Just like comments, docstrings don't execute. But unlike docstring, they get attached to a particular piece of code (a module, a function, a class, or a method — if that makes no sense, don't worry, that's not important right now.)
IMPORTANT!
Pay attention to white space and indentation! It holds meaning in Python. Every time you indent some code, it should be four spaces. When a statement is indented, it's subordinate to the code above, which is one level of indentation lower.
"""
Project1.py
Prompts the user for name, age, and job, then greets them appropriately.
"""
# Everything to the right of a '#' is a comment.
# It won't affect your program.
# Try to delete these lines. Nothing will happen…
def main(): # Our main function
print("Please type your info.")
name = input("Name: ")
age = input("Age: ")
job = input("Job: ")
print(f"Hello, {name}! I see you're {age} years old and your job is {job}.\nThat's great!")
if __name__ == '__main__': # This part makes main available to our OS.
main()
There are already quite a lot of things to unpack here. First, our code sits inside a main function, which is not entirely necessary but a personal habit. You could have written the program like this:
print("Please type your info.")
name = input("Name: ")
age = input("Age: ")
job = input("Job: ")
print(f"Hello, {name}! I see you're {age} years old and your job is {job}.\nThat's great!")
Statements
Our main function contains a bunch of statements. They are parts of a program that do something. They are evaluated in order, from first to last. For example, print("Hello")
is a statement that prints Hello
to the terminal. "Hello"
is a string.
Strings
A simple way to define a string is simply a sequence of characters. In most programming languages, strings are represented by putting the string's contents in quotes. Both simple and double quotes are valid in Python as long as the opening and closing quotes match.
Examples:
"Hello, world"
‘Aîjfzî. &àé\"çczn 1233. \n azdfoijaemdofij’
"Here is a string, containing a ‘smaller string’"
Assignment and Variables
The statement name = input("Name")
contains several interesting parts.
The =
operator is the assignment operator. It doesn't test for equality (that's the role of ==
, which we'll meet later) but assigns a value to a name. This name, which can refer to a value, is called a variable. Using the variable's name in Python is the same as using the value it holds. Here, the variable's name is name. Other variables in our program are age and job.
input()
is a function. It lets the program communicate with the user through the command line interface (CLI). For example, when you type your name, the computer turns it into a string. This string is the value of the expression input("Name")
. When you write name = input("Name")
, this value gets stored in the variable name.
So, we have three variables, each containing a string: name
, age
, and job
. Now, we want to do something (semi-)useful with our values. We'll use the print
function. You use it by putting what you want to print inside the parentheses. You can put whatever you wish to as the function's argument as long as it evaluates to a string. Here, we use a special type of string, the format string. The opening quotes are f"
, while the closing quotes are normal, plain double quotes. Format strings provide some flexibility to strings by letting you add code that gets evaluated when your computer evaluates the string (in our case, when it runs the function print). You put the code inside curly braces {}
. We kept things simple here and only used variables inside the curly braces.
Let's try out the program:
% python3 Project1.py
Please type your info.
Name: Marc
Age: 33
Job: Accountant
Hello, Marc! I see you're 33 years old and your job is Accountant.
That's great! It works!
But what if we don't provide any info?
% python3 Project1.py
Please type your info.
Name:
Age:
Job:
Hello, ! I see you're years old and your job is .
That's great!
Input validation
Our program's output doesn't make sense. While our code was neat and tidy, it didn't validate the inputs. Here's a handy rule of thumb. When your code deals with data from outside it (e.g., User input like in our example, data from a file saved on disk, data from the internet, etc.), you should validate it to ensure it's not bogus.
If, elif, else
Let's rework our code to ensure the variables name, age, and job exist. For that, we'll introduce another concept: conditionals. Conditionals are the way programs can branch out and make choices. Without them, programs would be a rigid sequence of orders. Not very interesting! The simplest conditional is the if statement. It has the following form:
if <condition A>: # This part is mandatory. You need an if clause
<some code A>
elif <condition B>: # This means "else if". Optional.
<some other code B> # You can have as many elif statements as needed.
else: # catch-all part. Optional but recommended.
<some code C>
This can be read as:" If condition A is met, execute the code A below. If condition A is not met, but condition B is, execute code B below. If neither condition A nor condition B are met, execute code C. Note that conditions are evaluated in order. When the Python interpreter meets a condition that evaluates to True, it evaluates the code below and doesn't bother with the elif and the else. Condition B could very well be True, but it doesn't matter if condition A is True because the interpreter will never look at it. Else is True by default and is a catch-all statement. The code below the else: will be executed if none of the if and elif statements are evaluated as True.
If this seems complex, don't worry; it'll get clearer when we see the if statements in action.
Booleans
The condition in an if
or elif
statement is any expression that can be evaluated as True
or False
. True
and False
are a type of value called booleans.
You get boolean values when you test for equality or inequality.
1 == 1
means 'does 1 equal 1?' It evals to True
, obviously.
1 == "a"
means 'does 1 equal the string "a"?' It equals to False
.
1 != 3
means 'is 1 different from 3? It evals to True
.
Other boolean operators are <
, >
, <=
(less or equal), and >=
(greater than or equal).
Here, we won't use a boolean operator to create a condition. Instead, we'll take advantage of non-empty strings evaluating to True
. If the user types something for the name, it will be a non-empty string and thus True
, but if he types nothing, the name will be False
.
Logic Operators
You can combine booleans with logic operators like and
, or
, xor
, not
.
These operators are so crucial in programming that we'll review them individually. Below are their truth tables. The first one is for the and operator.
A | B | A and B |
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
Each row is a possible combination of True and False for the expression A and B. Since both A and B are either True or False, we get four possible combinations: True and True, True and False, False and True, and finally False and False. The result of the evaluation of the expression A and B is in the third column.
Here is the truth table for or (this is inclusive or, meaning either A or B, or both):
A | B | A or B |
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
Here is the table for xor (exclusive or, meaning either A or B, but not both):
A | B | A xor B |
TRUE | TRUE | FALSE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
And here's the table for not:
A | not A |
TRUE | FALSE |
FALSE | TRUE |
Revised Version with Basic Input Validation
Here's our revised program, testing if it actually received an input.
"""
Prompts the user for name, age, and job, then greets them appropriately.
"""
def main():
print("Please type your info.")
name = input("Name: ")
age = input("Age: ")
job = input("Job: ")
if name and age and job: # Notice the : at the end
print(f"Hello, {name}! I see you're {age} years old and your job is {job}.\nThat's great!")
else: # There’s an : at the end too!
print("The input was trash!")
if __name__ == '__main__':
main()
Still works great for valid input:
% python3 Project1.py
Please type your info.
Name: Ellen
Age: 41
Job: Part-time snorkeler
Hello, Ellen! I see you're 41 years old and your job is Part-time snorkeler.
That's great
And our if statement seems to have solved the problem of missing input!
% python3 Project1.py
Please type your info.
Name:
Age:
Job:
The input was trash!
Let's unpack what happens in the statement if name and age and job
. Our three variables can either be evaluated to True or False. Here, True or False are not the values associated with these variables (those values are, for example, respectively, the strings "Ellen", "41", and "Part-time snorkeler".) In the context of a conditional, the values of our three variables can be considered either True or False: True if there's something in the variable, False if they are the empty string. Here, you see, we also are chaining two logical operators. This is valid in Python.
Here's another truth table for you:
name | age | job | name and age and job |
TRUE | TRUE | TRUE | TRUE |
TRUE | TRUE | FALSE | FALSE |
TRUE | FALSE | TRUE | FALSE |
TRUE | FALSE | FALSE | FALSE |
FALSE | TRUE | TRUE | FALSE |
FALSE | TRUE | FALSE | FALSE |
FALSE | FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE | FALSE |
You see that you get a greeting message only if you provided all the info that’s asked of you.
3rd Version: Nested if statements and methods
But what if I want to show a different message for each type of missing user input? And it'd be nice to ensure the age is actually a number (what if a user typed mzeof' ()à)-nqzefn
as an age?)
"""
Prompts the user for name, age, and job, then greets them appropriately.
"""
def main():
print("Please type your info.")
name = input("Name: ")
if not name:
print("That's not your name, weirdo!")
else:
age = input("Age: ")
if not age or not age.isdigit():
print("That's no age!")
else:
job = input("Job: ")
if not job:
print("Get a job...")
else:
print(f"Hello, {name}! I see you're {age} years old and your job is {job}.\nThat's great!")
if __name__ == '__main__':
main()
There’s a lot to unpack here, but before we get into it, let’s test if the program still works fine.
% python3 Project1.py
Please type your info.
Name:
That's not your name, weirdo!
OK, it seems fine for name.
% python3 Project1.py
Please type your info.
Name: Tom
Age:
That's no age!
Seems fine for age, too.
% python3 Project1.py
Please type your info.
Name: Tom
Age: 32
Job:
Get a job...
And for job… Now let’s see if the code isn’t broken for normal cases.
python3 Project1.py
Please type your info.
Name: Tom
Age: 32
Job: Dish washer
Hello, Tom! I see you're 32 years old and your job is Dish washer.
That's great!
Nested ifs
The code looks much more complicated now. It’s because we introduced nested ifs:
if not name:
print(<message 1>)
else:
age = input("Age: ")
if not age or not age.isdigit():
print(<message 2>)
else:
job = input("Job: ")
if not job:
print(<message 3>)
else:
print(<our big formatting string>)
The way to read this is if we don't input a name, we get an error message, and the rest doesn't get executed. If you input a name, the program executes the else branch. It asks your age. If you don't give a valid age, you get an error message, and the program stops. If the age is valid, you get asked for your job. If you don't give a job, you get an error message, and the program stops. If you provide a job, the last else executes, and you get your long greeting message.
Generally, you don't want to nest if statements too deep because it's easy to make errors and introduce bugs in your programs. At some point, it gets confusing as to which if or which else statement is responsible for which code block. A good rule of thumb is to nest at most two ifs.
Methods
An interesting new feature is age.isdigit()
. isdigit()
is called a method. We'll look at methods in another article, but for now, let's oversimplify things and say they are one of the ways to apply changes to your data (the others being functions and operators.) Methods (isdigit here) are associated with objects (age in our example.) Methods are linked to their object by a dot (dot notation.)
isdigit
checks if age is a number.
4th Version: return statements
Our last version with nested ifs was quite ugly. Let’s set it straight.
"""
Prompts the user for name, age, and job, then greets them appropriately.
"""
def main():
print("Please type your info.")
name = input("Name: ")
if not name:
print("That's not your name, weirdo!")
return
age = input("Age: ")
if not age.isdigit() or int(age) <= 0:
print("That's no age!")
return
job = input("Job: ")
if not job:
print("Get a job...")
return
print(f"Hello, {name}! I see you're {age} years old and your job is {job}.\nThat's great!")
if __name__ == '__main__':
main()
This introduces return
statements. Functions are called by their callers. In our program, the main function is called by the code main()
at the end of the program:
if __name__ == '__main__':
main()
A function's return value is the value it yields to the caller. If you don't provide an explicit return value, the default is None
. In our example, we didn't provide any values to the return statements because we were only interested in getting their program termination functionality.
Below is a little program using just two functions to illustrate return values further:
def f1(x):
return x + 1
def f2(x):
return x * 2
print(f2(f1(3)))
Can you guess what gets printed? (Hint: it equals (3 + 1) x 2.)
A word on None
: it indicates the absence of a value. As such, it is the default return value and a popular placeholder. It is not the same as False
or 0
.
Thus, return
is the same as return None
. You can use None as a placeholder like this:
data = None
When you want to test if a value is None, you don't use == like you would for a number or a string. You use the keyword is
like this:
if value is None:
some_code
We'll get to see much more of None in later posts.
5th Version: dealing with trailing whitespace
Let's give our program's last version some subtly misformed inputs.
We'll first add whitespace either before or after the answer's letters. Whitespace means tabs and spaces.
% python3 Project1.py
Please type your info.
Name: Tim # There are some spaces after the letter m
Age: 34
Job: Cook
Hello, Tim ! I see you're 34 years old and your job is Cook.
That's great!
As we can see, the output is ugly. The whitespace doesn't get automatically removed and stays in the output.
What if we add trailing whitespace after the age's number?
% python3 Project1.py
Please type your info.
Name: Bob
Age: 129
That's no age!
We get an error because since we mix whitespace and digits, age.isdigit()
is False. This is a worse result than merely ugly formatting in the output. Here's a version of our program that fixes the issue.
"""
Prompts the user for name, age, and job, then greets them appropriately.
"""
def main():
print("Please type your info.")
name = input("Name: ").strip()
if not name:
print("That's not your name, weirdo!")
return
age = input("Age: ").strip()
if not age.isdigit() or int(age) <= 0:
print("That's no age!")
return
job = input("Job: ").strip()
if not job:
print("Get a job...")
return
print(f"Hello, {name.capitalize()}! I see you're {age} years old and your job is {job.capitalize()}.\nThat’s great!")
if __name__ == '__main__':
main()
We used the method strip()
to automatically remove whitespace before and after our input string's contents.
We also included a minor cosmetic enhancement in our formatted output: we added a method to capitalize both name and job.
Below is the same version with the capitalize()
method changed to title()
.
Try to play around with these methods to explore their differences.
Remember, methods are separated from their object by a dot.
% python3 Project1.py
Please type your info.
Name: jane
Age: 27
Job: journalist
Hello, Jane! I see you're 27 years old and your job is journalist.
That's great!
% python3 Project1.py
Please type your info.
Name: mary ann
Age: 35
Job: postmaster general
Hello, Mary ann! I see you're 35 years old and your job is Postmaster general.
That's great!
"""
Prompts the user for name, age, and job, then greets them appropriately.
"""
def main():
print("Please type your info.")
name = input("Name: ").strip()
if not name:
print("That's not your name, weirdo!")
return
age = input("Age: ").strip()
if not age.isdigit() or int(age) <= 0:
print("That's no age!")
return
job = input("Job: ").strip()
if not job:
print("Get a job...")
return
print(f"Hello, {name.title()}! I see you're {age} years old and your job is {job.title()}.\nThat's great!")
if __name__ == '__main__':
main()
6th Version: Floats, Booleans
OK, the last version was great. But we can add some new questions; it will be a good opportunity to discuss floats and see more bools.
Floats are floating point numbers are real numbers with decimal points: e.g. 0.1537, 3.1415, 3.0, etc. Our new version will ask for the user's height in meters (a float like 1.78), and we'll separate the meters from the centimeters, presenting them as integers.
We'll also do some input validation for yes/no answers.
"""
Prompts the user for name, age, and job, then greets them appropriately.
"""
def main():
print("Please type your info.")
name = input("Name: ").strip()
if not name:
print("That's not your name, weirdo!")
return
age = input("Age: ").strip()
if not age.isdigit() or int(age) <= 0:
print("That's no age!")
return
height = input("Height in meters: ").strip()
if height:
height = float(height)
if height <= 0.0:
print("That's just too small.")
return
height_m_part = int(height // 1)
height_cm_part = int((height % 1) * 100)
else:
print("Please answer")
return
job = input("Job: ").strip()
if not job:
print("Get a job...")
return
student = input("Are you a student? (yes/no): ").strip().lower()
if student == "yes":
is_student = True
elif student == "no":
is_student = False
else:
print("Please provide an answer next time :(")
return
print(f"Hello, {name.title()}! I see you're {age} years old and {height_m_part} meters and {height_cm_part} cm.\nYour job is {job.title()}.\nThat's great!")
if __name__ == '__main__':
main()
Does it work?
% python3 Project1.py
Please type your info.
Name: Alex
Age: 29
Height in meters: 1.78
Job: Doll-maker
Are you a student? (yes/no): no
Hello, Alex! I see you're 29 years old and 1 meters and 78 cm.
Your job is Doll-Maker.
That's great!
Let’s unpack what’s happening.
Floats
The simplified code below takes a string stripped from its whitespace and stores it in height (e.g., "1.78" or "2"). The next line will attempt to turn the string into a floating point number with the float function. It is very important to understand that this new value is not the same anymore: a string is not a float and a float is not a string! For example, if you inputted 1.88, the first value of height would be "1.88" and would be changed to 1.88 by the float function. The first value is the character "1", followed by the character "." followed by the character "8", followed by the character "8". The second value is a number. The code works as long as what you wrote as an answer can be transformed into a number, even if what you wrote looks like an integer: for example, 2 can easily be converted into 2.0. You'll get an error message if you enter something that cannot become a float (e.g., "Izefjùqzeifjqzfie").
height = input("Height in meters: ").strip()
height = float(height)
height_m_part = int(height // 1)
height_cm_part = int((height % 1) * 100)
// and %
There's a simple trick to separate the integer part from the decimal part in a float. The //
operator is integer division (ie. You divide a number by another and only keep the integer part of the result), while %
is the remainder. Using 1 as the divisor is equivalent to selecting everything on one side of the period (// for the integer part and % for the decimal part.)
More booleans
Booleans are not possible to input directly for the user. There's no straightforward way to turn a string into either True or False. So, we need to ask the user for a string (here, "yes', or "no") and test this string to decide which boolean we store in a variable. We could have stored the boolean value back into student, but we created a new variable is_student.
To make the testing more straightforward, we apply the lower() method to our input so that "Yes", "YES", and "yes" all look the same for the if student == "yes":
test. The same goes for "no".
student = input("Are you a student? (yes/no): ").strip().lower()
if student == "yes":
is_student = True
elif student == "no":
is_student = False
As always, we add an else statement (not shown here) to catch wrong input.
7th Version: datetime
Our next and last version will check if the user's provided age matches with the provided birthdate.
"""
Prompts the user for name, age, and job, then greets them appropriately.
"""
from datetime import datetime
DAYS_IN_YEAR = 365.15
def main():
print("Please type your info.")
name = input("Name: ").strip()
if not name:
print("That's not your name, weirdo!")
return
age = input("Age: ").strip()
if not age.isdigit() or int(age) <= 0:
print("That's no age!")
return
print("Is that true? Let's check your birthdate...")
birthdate = input("Enter it now (YYYY-MM-DD): ").strip()
if not birthdate:
print("Type something")
return
birthdate = datetime.strptime(birthdate, "%Y-%m-%d")
today_date = datetime.today()
dates_difference = today_date - birthdate
years = int((dates_difference.days / DAYS_IN_YEAR) // 1)
if years != age:
print(f"LIAR! YOU ARE {years} YEARS OLD!")
height = input("Height in meters: ").strip()
height = float(height)
if not height or height <= 0.0:
print("That's just too small.")
return
height_m_part = int(height // 1)
height_cm_part = int((height % 1) * 100)
job = input("Job: ").strip()
if not job:
print("Get a job...")
return
student = input("Are you a student? (yes/no): ").strip().lower()
if student == "yes":
is_student = True
elif student == "no":
is_student = False
else:
print("Please provide an answer next time :(")
return
print(f"Hello, {name.title()}! I see you're {years} years old and {height_m_part} meters and {height_cm_part} cm.\nYour job is {job.title()}.\nThat's great!")
if __name__ == '__main__':
main()
% python3 Project1.py
Please type your info.
Name: Alex
Age: 33
Is that true? Let's check your birthdate...
Enter it now (YYYY-MM-DD): 2000-01-05
LIAR! YOU ARE 24 YEARS OLD!
Height in meters: 1.99
Job: Doctor
Are you a student? (yes/no): no
Hello, Alex! I see you're 24 years old and 1 meters and 99 cm.
Your job is Doctor.
That's great!
Python has built-in types to handle time; they are placed in the datetime
module. Some of them are time
, date
, datetime
, timedelta
, tzinfo
, and timezone
. Our example will use only one of these: datetime. It's a combination of time and date. We don't use it directly, but strptime
converts a string to a datetime object.
birthdate = input("Enter it now (YYYY-MM-DD): ").strip()
birthdate = datetime.strptime(birthdate, "%Y-%m-%d")
With these two lines, birthdate now contains the birthdate in a way that Python can efficiently work with.
We ask for the user's input in a specific format in our input function because the datetime.strptime
function needs a properly formatted date string. This is indicated by %Y-%m-%d
. There are a lot of different ways to format dates. They are documented in the Python docs (https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes). Since strptime comes from a module we imported, we must prefix it with the module's name, separated by a dot.
Next, we need to compute the difference between today's date and the birthdate. When we turn this difference in a number of years, we can compare it to the user's provided age.
today_date = datetime.today()
This line creates a variable holding today’s date and time.
dates_difference = today_date - birthdate
Datetime objects can be added, substracted, etc. The result is a particular type: the typedelta type. typedeltas hold a duration in the form of days, seconds, and microseconds. We can access the number of days between two dates with the days method. Dividing this number by 365.15 gives us a number of years. We use the same trick as before (integer division by one) to extract the integer part of the number of years.
years = int((dates_difference.days / DAYS_IN_YEAR) // 1)
Constants
Our program also introduces the concept of constants with DAYS_IN _YEAR
. Constants are a way to store immutable data (data you don't intend to change). It's a good idea to store hard values in constants and to refer to them by name. Let's say we used the number of days in a year in several places in our code. For some reason, one day, people decided we would have longer years (say, we as a species migrated to Pluto… The years would now last 90,560 Earth days.) We would have to go over our whole code to change the value. This is a great way to make mistakes and introduce bugs in our program! This example is silly but illustrates the importance of defining numerical constants in one place.
In Python, constants have names in capital letters, like DAYS_IN_YEARS
.
Conclusion
There are still many things we could do to improve our program, but it would go well beyond the scope of this post. You can try adding to it on your own and returning to it as you learn new programming concepts.
Here's a recap of what we've learned so far.
Comments and Docstrings
When you return to your code a few weeks after you've written it, or if you need to communicate with other programmers, adding comments is helpful. The Python interpreter does not execute comments; they're only there for your future self and your colleagues. You need to add a # to signal them.
Docstrings are very much like comments. They sit inside triple quotes """
.
Whitespace and indentation
Python is a special programming language in the sense that it uses significant whitespace. This means you need to properly indent your code for it to work. Some people think it's a disadvantage, but it's more of a feature that forces users to properly format their code, making it more easily readable.
Indentation defines the beginning and the end of code blocks.
The traditional way to intend code is with 4 spaces. Usually, your code editor will do that for you.
For example:
def example():
if condition:
do_something
do_another_thing
else:
do_yet_another_thing
return something
Data
Programs do stuff to things.
The things are data. We saw two ways to store data in our programs: constants and variables. To assign a value to a variable, you use the =
operator like this:
a = 1
Or like this:
user_input = input("say something")
Constants are even easier to use: you only define them once!
PI = 22 / 7
We've seen several types in our program:
None: represents the absence of a value
int: whole numbers without decimal points
float: real numbers with decimal points
booleans: True or False
strings: sequences of characters (letters, numbers, symbols, spaces) enclosed in single or double quotes
f-strings (formatted strings): strings with embedded expressions. The expressions are inside curly braces {}.
2 datetime types: datetime and timedelta. From the datetime module.
You can access an object's type with the function type()
and can check whether an object is a specific type with isinstance()
. type()
returns the type of the object (e.g., int, float, etc.), while isinstance()
returns True or False.
Acting on data
There are several options available to you to act on data.
There are methods, functions, and operators (we could also add control structures like if/elif/else or comprehensions, which we've not yet seen.)
Methods | Functions | Operators | |
Definition | Bound to objects (e.g. strings, lists) and perform actions specific to that object type | Independent blocks of code that take inputs and return outputs | Symbols that perform operations on values or variables |
Syntax | object.method() | function_name(arguments) | operand1 operator operand2 |
Return Value | Either modifies the object or returns a new value | Returns a value if a return statement is specified | Result based on the operator |
Example | "Hello".upper() returns "HELLO" | int("3") returns 3 | 5 + 3 returns 8 |
We saw methods like isdigit, strip, capitalize, title, lower, and datetime.today, functions like input, print, int, float, datetime.strptime, datetime.today, and operators like //, %, =, +, /, *, <=, or, and, xor, not, etc.
The main function is particular: where specified, it's the entry point of a program.
If statements
If statements are a way to help your program execute code depending on predetermined conditions. It takes this form:
if test_1:
code_1
elif test_2:
code_2
else:
code_3
You can add as many elif statements as you like. Both elif and else statements are optional.
Note the indentation of code blocks under their respective if statements.
Input validation
Input from outside your program should be viewed with suspicion. It could be malformed, absent, or even dangerous. Therefore, you validate this input before you use it. The input validation we saw was very basic and only covered part of all the possible problematic cases. Once a bad input is caught, the program needs to act accordingly. We solved this problem by printing statements telling the user that his input was bad. The program terminated abruptly afterward. This is not very useful, and we'll go over more elegant ways to deal with bad input later.
I hope this article gave you a taste of programming and made you curious to read on. I'd be happy to know what you thought about it. If you have any questions, do ask them in the comments.
Exercises
1. Simple input and output
Write a program that asks the user for his favorite color, then prints a message with the form
"Your favorite color is <color>!"
<color> should be replaced with the actual input.
2. Validating input
Modify the program to validate the input. It should check if the user entered a color. If not, the program should output:
"You didn’t tell me your favorite color!"
The program should also check if the user input is a string. If not (for example, the user enters an empty string, or an int, etc..), it should print
"That’s not a color!"
3. Booleans
Write a program that asks the user if he likes programming. If he types ‘yes’, print
"That’s great to hear!"
If he types ‘no’, print
"That’s okay. Programming is not for everyone."
If he enters any other input, print
"Please answer with ‘yes’ or ‘no’.
(You can easily write the program without using booleans, but for the sake of learning, try to create a boolean variable representing user input)
4. Numbers
Write a program that asks the user for his age. The program should expect an integer. It should print
"You are <age> years old!"
If the user enters something other than an integer (e.g., ‘Twenty’), print
"That’s not an age!"
5. Strings and numbers
Modify the program to ask for the user’s age and name, then print
"Hi <name>, in 5 years, you will be <age+5> years old!"
6. Working with methods
Modify the program above to capitalize the user’s name and strip any excessive whitespace.
7. Floating point numbers
Ask the user for his height in meters. Separate the meters and centimeters and print
"You are <meters> meter(s) and <centimeters> centimeter(s) tall."
8. Logical operators
Ask the user if he likes pizza and ice cream. If he likes both, print
"Great tastes"
If he likes only one, print
"That’s cool."
Else print
"Really? That’s strange…"
9. Datetime
Ask the user for his birth date and a date of his choice. Check that the second date is later than the birth date, and print
"On the <date>, you will be <age> year old."
Subscribe to my newsletter
Read articles from Had Will directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
