Академический Документы
Профессиональный Документы
Культура Документы
print(10 % 3) gives 1. It makes 10 / 3 and outputs the reminder: 10/3 = 9. 1 more until 10.
pow = power
To access to more math functions add "from math import *" at the beginning of the code
sqrt(9) gives 3
Get input from user
Calculator
print(result)
If num1 is 1 and num2 is 2, it's going to output 12 (not 1+2=3). Python converts input to string.
Int convierte la variable en número entero. ¿Qué pasa si queremos un número decimal?
print(friends[0]) te da el primero
print(friends[-1]) te da el ultimo
friends[1] = "Paco"
FUNCIONES DE LISTAS
- Reverse: listname.reverse()
Is a type of data structure. Container to store values. Similar to list. Something between parenthesis
is tuple.
coordinates = (3, 5)
Tuples are inmutable. Cannot change content. Lists would use brackets. We can also create a variable
that consists of a list of tuples:
FUNCTIONS
def say_hi():
print("Hi!")
Everything after the “:” indented and in the next lines will be the code inside the function "say_hi".
To execute it add:
say_hi()
say_hi("Mike", "35")
It outputs "Hi Mike. You are 35"
RETURN STATEMENT
print(cube(3))
IF STATEMENTS
Execute certain code when some conditions are true and another one when they’re false.
is_male = True
is_tall = True
print(max_num(2, 1, 55))
This outputs the biggest number, in this case 55.
BUILD CALCULATOR
num1 = float(input("Enter the first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter the second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print (num1 * num2)
elif op == "/":
print (num1 / num2)
else:
print ("Invalid operator")
DICTIONARIES
Outputs “June”. If we enter a key not included in the dictionary, it will output “Not a valid key”.
WHILE LOOPS
i = 1
while i <= 10:
print(i)
i += 1
print("Done with loop")
Outputs all numbers from 1 to 10 and then “Done with loop”. i += 1 is the same as i = i + 1
GUESSING GAME
secret_word = "Franco"
guess = ""
guess_limit = 5
guess_count = 0
out_of_guesses = False
if out_of_guesses:
print("You lose.")
else:
print("You won.")
FOR LOOPS
print(raise_to_power(2, 3))
Outputs 8.
2D LISTS
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
TRANSLATOR
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou":
translation = translation + "g"
else:
translation = translation + letter
return translation
EXCEPT
try:
ans = 10/0
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError as err:
print(err)
except ValueError:
print("Invalid input.")
Except in general is too broad. You have to use a particular kind of except.
READ FILES
employee_file = open("things.txt", "r")
for emp in employee_file.readlines():
print(emp)
employee_file.close()
WRITE FILES
It’s the same but changing “r” for “w”. Then use employee_file.write(“Whatever”)
CLASSES
File guess.py
class Student:
def __init__(self, name, major, gpa, is_on_probation):
# This initialize defines what a student is.
self.name = name
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probation
# The object's name is equal to the name we introduced in the other file
in another file
from guess import Student
print(student2.is_on_probation)
Outputs True
QUIZ
This is question.py
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
Another file
from question import Question
question_prompts = [
"What is A?\n(a)\n(b)\n(c)\n\n",
"What is B?\n(a)\n(b)\n(c)\n\n",
"What is C?\n(a)\n(b)\n(c)\n\n"
]
# This is just an array of questions and possible answers
questions = [
Question(question_prompts[0], "a"),
Question(question_prompts[1], "b"),
Question(question_prompts[2], "c")
]
# This in an array of three objects of the class Question (containing prompt,
answer).
def run_test(questions):
score = 0
for question in questions:
answer = input(question.prompt)
# This shows each question.prompt (first one is Question(question_prompts[0])) and
asks for an answer.
if answer == question.answer:
score += 1
print("You got", str(score), "/", str(3), "bpoints.")
run_test(questions)
More on classes
student.py
class Student:
def __init__(self, name, major, gpa):
self.name = name
self.major = major
self.gpa = gpa
def on_honor_roll(self):
if self.gpa >= 3.5:
return True
else:
return False
We define a class student whose elements have 3 parameters. We can also define a function called
on_honor_roll.
app.py
from student import Student
print(student2.on_honor_roll())
Outputs True
Inheritance