Вы находитесь на странице: 1из 10

Numbers

print(10 % 3) gives 1. It makes 10 / 3 and outputs the reminder: 10/3 = 9. 1 more until 10.

To print numbers as text we have to convert them to strings

print(str(4) + "is a good number") gives "4 is a good number"

Functions for numbers:

abs = absolute number

print (abs(-5)) gives 5

pow = power

print (pow(3, 2)) gives 9 (3^2)

max = highest number

min = lowest number

print (max(4, 5)) gives 5

print (round(3.2)) gives 3

print (round(3.6)) gives 4

To access to more math functions add "from math import *" at the beginning of the code

floor(5.3) gives the first number, 5

sqrt(9) gives 3
Get input from user

name = input("Enter your name: ")

# The variable name will store the input.

name = input("Enter your name: ")

print ("Hello " + name + "!")

Calculator

num1 = input("Enter a number: ")

num2 = input("Enter another one: ")

result = num1 + num2

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.

We have to convert the string from the user into numbers

result = int(num1) + int(num2)

Int convierte la variable en número entero. ¿Qué pasa si queremos un número decimal?

result = float(num1) + float(num2)


LISTS

Lists are structures we can use to store data.

friends = ["Franco", "Hitler"]

tambien pueden ser True/False o números.

acceder a elementos particulares de una list:

print(friends[0]) te da el primero

print(friends[-1]) te da el ultimo

print(friends[1:]) te da desde el 1 en adelante

print(friends[1:3]) te da desde el 1 al 3 sin incluir el 3

se pueden modificar valores en listas

friends[1] = "Paco"

FUNCIONES DE LISTAS

- Add two lists: listname.extend(otherlist)

- Add individual elements: listname.append("Element")

- Add individual element in a particular place: listname.insert(1, "Element")

- Remove element: listname.remove("Element")

- Remove everything: listname.clear()

- Remove last element: listname.pop()

- Check if a particular element is in the list:

print(friends.index("Element") this outputs the position of that element

- Count how many elements inside a list: print(listname.count("Element"))

- Sort the list in ascending alphabetical order: listname.sort()

- Reverse: listname.reverse()

- Copy list: listname2 + listname.copy()


TUPLES

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:

coordinates = [(3, 5), (4,6), (6,3)]

FUNCTIONS

"def" keyword means function.

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()

to the code. Without indentation.

A parameter is a piece of info we give to the function. If we write

def say_hi(name, age):

print("Hi " + name + ". You are " + age)

say_hi("Mike", "35")
It outputs "Hi Mike. You are 35"

RETURN STATEMENT

Return keyword allows Python to return information from a function.


def cube(num):
return num*num*num

print(cube(3))

Without “return” is doesn’t give anything back.


def cube(num):
return num*num*num
result = cube(4)
print(result)
This way the variable result stores the value that returns from the function cube with the parameter
4. That is 64.

You cannot add any code after the return statement.

IF STATEMENTS

Execute certain code when some conditions are true and another one when they’re false.
is_male = True
is_tall = True

if is_male and is_tall:


print("You are a male and tall")
else:
print("You are either not male or not tall")
You can also use “or” instead of “and”. “elif” adds else if. “else” is like “otherwise”.
is_male = True
is_tall = False

if is_male and is_tall:


print("You are a male and tall")
elif is_male and not(is_tall):
print("You are a not tall male")
elif not(is_male) and is_tall:
print("You are not a male but are tall")
else:
print("You are not a male and not tall")

IF STATEMENTS AND COMPARISONS


def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3

print(max_num(2, 1, 55))
This outputs the biggest number, in this case 55.

def max_num(num1, num2, num3):


if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3

n1 = input("Give me a number: ")


n2 = input("Give me another: ")
n3 = input("Give me another: ")

print(max_num(n1, n2, n3), "is the biggest one")

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

It allows us to store info in “key value pairs”.


monthConversions = {
"Jan": "January",
"Feb": "February",
"Mar": "March",
"Apr": "April",
"May": "May",
"Jun": "June",
}

print(monthConversions.get("Jun", "Not a valid key"))

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

while guess != secret_word and not out_of_guesses:


if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
else:
out_of_guesses = True

if out_of_guesses:
print("You lose.")
else:
print("You won.")

FOR LOOPS

Loops over different collections of items.


for x in range(3, 10):
print(x)
Outputs all numbers between 3 and 10 not including 10.
friends = ["Jim", "Karen", "Kevin"]
for x in friends:
print(x)
Outputs everything in the friends var. x can be anything.

friends = ["Jim", "Karen", "Kevin"]


len(friends)
for index in range(len(friends)):
print(friends[index])
range(len(friends)) gives a number between 0 and the total number of elements in the list friends. 3
is not included!!! Then friends[index] outputs each one.
EXPONENT WITH FOR
def raise_to_power(base, power):
result = 1
for index in range(power):
result = result * base
return result

print(raise_to_power(2, 3))
Outputs 8.

2D LISTS
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]

for row in number_grid:


for col in row:
print(col)
Outputs all the elements.

TRANSLATOR
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou":
translation = translation + "g"
else:
translation = translation + letter
return translation

print(translate(input("Enter a phrase: ")))


Esto cambia todas las vocales por una “g”.

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

Classes are data-types. Objects are elements of a certain data-type.

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

student1 = Student("Jim", "Business", 3.1, False)


student2 = Student("Pam", "Art", 2.5, True)

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

student1 = Student("Oscar", "Accountant", 3.1)


student2 = Student("Phylis", "Whatever", 3.5)

print(student2.on_honor_roll())
Outputs True

Inheritance

Вам также может понравиться