Matthieu Choplin
my_variable = 100
print(type(my_variable)) # will print <class 'int'>
my_variable="100" # notice the quote for a string data type
print(type(my_variable)) # will print <class 'str'>
My_variable = 100
print(id(my_variable))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'my_variable' is not defined
We define variable_a in program_a.py
#program_a.py
variable_a = 42
We try to use variable_a in program_b.py. What is wrong?
#program_b.py
print(variable_a)
and | as | assert | break | class | continue | def |
del | elif | else | except | exec | finally | for |
from | global | if | import | in | is | lambda |
not | or | pass | raise | return | try | |
while | with | yield |
Show solution
Hide solution
miles = 100
kilometers = miles * 1.609
print(kilometers)
Show solution
Hide solution
length = 3
width = 4
area = length * width # we are using variables defined above
print("The area of the squared room of length", \
length, "and width", width, "is", area)
Show solution
Hide solution
length = float(input("What is the length of the room? "))
width = float(input("What is the width of the room? "))
area = length * width # using variables defined above
print("The area of the squared room of length", \
length, "and width", width, "is", area)
type(1) # <class 'int'>
type(1.0) # <class 'float'>
type("1.0") # <class 'str'>
Data type | Examples |
---|---|
Integers | -2, -1, 0, 1, 2, 3, 4, 5 |
Floats | -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25 |
Strings | 'a', 'aa', 'aaa', 'Hello!', '11 cats' |
Name | Meaning | Example | Result |
---|---|---|---|
+ | Addition | 34 + 1 | 35 |
- | Substraction | 34.0 - 0.1 | 33.9 |
* | Multiplication | 300 * 30 | 9000 |
/ | Float division | 1 / 2 | 0.5 |
// | Integer Division | 1 // 2 | 0 |
** | Exponentiation | 4 ** 0.5 | 2.0 |
% | Remainder | 20 % 3 | 2 |
Remainder or Modulo is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd.
...is translated to:
(3 + 4 * x) / 5 – 10 * (y - 5) * (a + b + c) / x +\
9 * (4 / x + (9 + x) / y)
NB: the sign \ is an "escaped" character, to break a line for readability
Let the user enter the yearly interest rate, number of years, and loan amount, and computes monthly payment and total payment.
Show solution
Hide solution
# Enter yearly interest rate
annualInterestRate = float(input(
"Enter annual interest rate, e.g., 8.25: "))
monthlyInterestRate = annualInterestRate / 1200
# Enter number of years
numberOfYears = float(input(
"Enter number of years as an integer, e.g., 5: "))
# Enter loan amount
loanAmount = float(input("Enter loan amount, e.g., 120000.95: "))
# Calculate payment
monthlyPayment = loanAmount * monthlyInterestRate / (1
- 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
totalPayment = monthlyPayment * numberOfYears * 12
# Display results
print("The monthly payment is " +
str(int(monthlyPayment * 100) / 100))
print("The total payment is " + str(int(totalPayment * 100) /100))
The expression concatenating a string returns a new string:
first_string = "abra"
second_string = "cada"
third_string = "bra"
concatenated_string = first_string + second_string \
+ third_string
print("first_string is", first_string,
"second_string is", second_string,
"third_string is ", third_string,
"concatenated_string is ", concatenated_string)
Remember that the string is a sequence of characters
The items of a sequence can be accessed through indexes
Items (characters) | a | b | r | a | c | a | d | a | b | r | a |
---|---|---|---|---|---|---|---|---|---|---|---|
Indexes | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
Get the first element of the sequence:
my_string_variable = "abracadabra"
first_elem = my_string_variable[0]
Input/Ouput | Conversion type: | Introspection: |
---|---|---|
input() | int() | type() |
print() | float() | dir() |
str() | help() | |
id() |
All the built in functions: https://docs.python.org/3.5/library/functions.html
To define a function, we use the keyword def, the name of the function, the brackets, and the colon
Then the body of the function needs to be indented
def name_of_the_function():
# body of the function
When we define a function, we just make python see that the function exist but it is not executed
To call or execute or run a function, we use the name of the function AND the brackets, without the brackets, the function is not called.
name_of_the_function()
Notice the difference between defining and calling a function
We can represent the flow of execution with a flow chart
Pseudo code:
if condition:
# statement (mind the indentation)
Example, representation of the flow chart example in python code:
if name=='Alice':
print('Hi Alice')
Pseudo code:
if condition:
# statement (mind the indentation)
else:
# statement executed when the condition is False
Example, representation of the flow chart example in python code with an else statement:
if name=='Alice':
print('Hi Alice')
else:
print('Hi')
The naive way
if condition:
# statement (mind the indentation)
else:
if condition:
# statement executed when
# the previous condition is False
else:
# statement executed when none of
# the previous condition is verified
The better way, the pythonc way
if condition:
# statement (mind the indentation)
elif condition:
# statement executed when
# the previous condition is False
elif condition:
# statement executed when none of
# the previous condition is verified
else:
# executed when all conditions are False
The program will execute the statement only if the condition is verified. Only if the condition is True.
The condition is actually a boolean.
Operator | Meaning |
---|---|
< | less than |
<= | less than or equal |
> | greater than |
>= | greater than or equal |
== | equal to |
!= | not equal to |
Create a program that ask the user for a password.
Show solution
Hide solution
PASSWORD = 'super_password123'
password_entered = input("Enter the password: ")
if password_entered == PASSWORD:
print("Access Granted")
else:
print("Forbidden")
Show every possible result of a Boolean operator.
Expression | Evaluates to... |
---|---|
True and True | True |
True and False | False |
False and True | False |
False and False | False |
Expression | Evaluates to... |
---|---|
True or True | True |
True or False | True |
False or True | True |
False or False | False |
It operates on only one Boolean value (or expression). The not operator simply evaluates to the opposite Boolean value.
Create a program that ask the user for a login and password.
Show solution
Hide solution
PASSWORD = 'super_password123'
LOGIN = 'superadmin'
login_entered = input("Enter the login: ")
password_entered = input("Enter the password: ")
if password_entered == PASSWORD \
and login_entered == LOGIN:
print("Access Granted")
else:
print("Forbidden")
Write a program that prompts the user to enter an integer. If the number is a multiple of 5, print HiFive. If the number is divisible by 2, print HiEven.
Show solution
Hide solution
number_x = int(input("Enter an integer: "))
if number_x % 5 == 0:
print("HiFive")
if number_x % 2 == 0:
print("HiEven")
Write a program that is going to give the grade of a student according to the score obtained.
Show solution
Hide solution
score = int(input("Enter the score: "))
if score >= 90.0:
grade = 'A'
elif score >= 80.0:
grade = 'B'
elif score >= 70.0:
grade = 'C'
elif score >= 60.0:
grade = 'D'
else:
grade = 'F'
print('The grade is ', grade)
This program first prompts the user to enter a year as an int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
Complete solution
Hide solution
year = input("Enter a year : ")
year = int(year)
leap_year = False # boolean value saying if
# the year is a leap_year or not
if year % 400 == 0:
leap_year = True
elif year % 4 == 0:
if year % 100 != 0:
leap_year = True
else:
leap_year = False
if leap_year:
print("The year entered is a leap year.")
else:
print("The year entered is not a leap year.")
Condition to use
Hide hint
(year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
Complete solution
Hide solution
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("The year is a leap year")
else:
print("The year is not a leap year")
Now let us write a program to find out the Chinese Zodiac sign for a given year. The Chinese Zodiac sign is based on a 12-year cycle, each year being represented by an animal: rat, ox, tiger, rabbit, dragon, snake, horse, sheep, monkey, rooster, dog, and pig, in this cycle
Hint 1
Hide hint 1
Use the modulo (%).
Hint 2
Hide hint 2
2016 is the year of the monkey and 2016 % 12 equals 0
Year | Zodiac sign |
---|---|
0 | monkey |
1 | rooster |
2 | dog |
3 | pig |
4 | rat |
5 | ox |
6 | tiger |
7 | rabbit |
8 | dragon |
9 | snake |
10 | horse |
11 | sheep |
Complete solution
Hide solution
year = eval(input("Enter a year: "))
zodiacYear = year % 12
if zodiacYear == 0:
print("monkey")
elif zodiacYear == 1:
print("rooster")
elif zodiacYear == 2:
print("dog")
elif zodiacYear == 3:
print("pig")
elif zodiacYear == 4:
print("rat")
elif zodiacYear == 5:
print("ox")
elif zodiacYear == 6:
print("tiger")
elif zodiacYear == 7:
print("rabbit")
elif zodiacYear == 8:
print("dragon")
elif zodiacYear == 9:
print("snake")
elif zodiacYear == 10:
print("horse")
else:
print("sheep")