Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
51 views

Python

The document provides an overview of key concepts in Python including: 1. Printing and string formatting using variables. 2. Conditional statements using if/elif/else and converting variables to the proper data type. 3. Common sequences like lists, tuples, sets, and dictionaries along with examples of using them. 4. Looping using for loops over lists, strings, and ranges. 5. Defining functions and calling functions from other files using import. 6. Object oriented programming concepts like classes, objects, properties, and methods.
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Python

The document provides an overview of key concepts in Python including: 1. Printing and string formatting using variables. 2. Conditional statements using if/elif/else and converting variables to the proper data type. 3. Common sequences like lists, tuples, sets, and dictionaries along with examples of using them. 4. Looping using for loops over lists, strings, and ranges. 5. Defining functions and calling functions from other files using import. 6. Object oriented programming concepts like classes, objects, properties, and methods.
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 5

Python

print(“hello world”)

For adding the value of a variable

print(“hello, ” + [variable])

example:

name = input(“Name: “)
print (“hello, ” + name) [+ is used for concatenation]

There’s a formated form which is better

print(f”hello, {name}”) [the curly brackets specify the value of a variable. I’m telling the
string to substitute the value of the variable]

So It would be

name = input(“Name: ”)
print(f“hello, {name}”)

CONDITIONS:

***INDENTATION IS NECESSARY IN PYTHON

n = input(“Number: ”)

if n > 0:
print(“n is positive”)

elif n < 0: [it’s like else if. It’s another check before the else statement]
print(“n is negative”)

else:
print(“n is zero”)

This gives us a problem. I can’t compare n and 0 because n is a str and 0 is a number, so I need to
modify the input in order to convert the variable into a int. That’s why I’ve got to modify it as
follows:
n = int(input(“Number: ”))

SEQUENCES

There are a number of sequences that can be used in Python


1.-List (sequence of mutable values):

# Hashtag is used for adding comments. The First part is for defining the list of names
names = [“Harry”, “Ron”, “Seba”]
print(names[0]) #the number between the square brackets is used for defining which element from
the list you want to print.

names = [“Harry”, “Ron”, “Seba”]

names.append(“Draco”) #la funcion append añade a la lista


names.sort() #ordena la lista
print(names)

2.- tuple (sequence of immutable values)

3.-set (collection of unique values. You don’t care about the order)

#create an empty set


s = set()

# Add elements to set


s.add(1)
s.add(2)
s.add(3)
s.add(4)
s.add(3) # No element ever appear twice in a set, because of set’s nature. So in the output I’ll only
get one instance of 3.
s.remove(2) #it removes elements from the set. In this case, 2
print(s)

len function = Gives you the length of a saquence (number of items inside a list, number of
characters inside a string, number of elements inside a set )

print(f“the set has {len(s)} elements”)

4.- dict (collection of key-value pairs)

LOOPING

The simplest loop in python is as follows:

for i in [0, 1, 2, 3, 4, 5]
print(i)

-What happens here is that we have a list and we’re telling python that for every element in the list,
call it i then print it (i is just the convention)

for i in range(6):
print(i)

range is a built in function which gives you a range of whatever amount is specified inside the
parenthesis
Loops can loop over any type of list

names = [“Seba”, “Ron”, “Peter”]

for name in names:


print(name)

-------------------------------------------------------

name = “”Harry”

for character in name:


print(character)
#it will loop over every character in the variable name and print it

DICTiONARIES

Data structure to store values, similar to an actual dictionary. We look for a key word and it shows a
particular value joined to that key

houses = {“Seba”: “calle 99”, “Draco”: “Peru”} #We specify a Key calling to a value

(#Margin note:When we call the Keys, we get the value.)

print(houses[“Harry”]) #square braquet spacifies what to look for inside a list

------------------------------------------------------------------------------------------------------------

houses = {“Seba”: “calle 99”, “Draco”: “Peru”}

houses[“Pedro”] = “Chile” #this can add or change a value to a dictionary

print(houses[“Pedro”])

-------------------------------------------------------------------------------------------------------------

FUNCTIONS

in order to define a function you have to use (we are gonna create a function that squares any input
number):

def square(x): #the name of the function is square and it takes an input which in this case is called
x. If there are multiple inputs they can be separated by coma. Ex. (x, y, z)
(the function can have any logic indented beneath it)

def square(x):
return x * x

for I in range(10):
print(f“the square of {I} is {square(I)}”)
CALLING THE FUNCTION FROM ANOTHER FILE

-you define the function in one individual file (module), then you can import it to another file:

-NameError: name ‘[the name of the variable]’ is not defined. This error happens when you are
calling a function from another file which you haven’t defined. That’s because you need to import
any given function that you’d like to use inside a file:

from functions import square #functions is the name of the file (don’t add extention) import square
(state here the name of the defined function inside the file mentioned before )

for I in range(10):
print(“the square of {I} is {square(I)}”)
-----------------------------------------------------------------------------------------------
Another way for doing the same:

import functions

for I in range(10):
print(“the square of {I} is {functions.square(I)}”) #in this case you need to tell it to go to
functions then inside that module go to the square function, thus functions.square

----------------------------------------------------------------------------------------------

You can import functions written by someone else

OBJECT ORIENTED PROGRAMING

We think of it as objects that can store data inside of them and solo support the ability to perform
some types of operations

***Class: Classes are blueprints for creating objects. They have determined characteristics that then
we are going to incorporate in as many objects as we want

class Point(): #Point can be any name you might want to give to the class
def __init__(self, x, y) : #__init__ is a reseved method (function)in python classes.
It is called as a constructor in object oriented terminology. This method is called when an
object is created from a class and it allows the class to initialize the attributes of the class.
#Self should always be included because is the way for self referring to the object so it
can store the values in itself. Always use it.
#x, y can be any value we want to give.

self.x = x
self.y = y

# here we state that the value of each point is refering to what’s stored inside the object
itself (the = something part is referring to the values we stated in (self, x, y) they are
properties)
p = Point(2, 8) #I’m calling the class that I created in the previous part

print(p.x)
print(p.y)

#in (p.x) and (p.y) we are telling the program to access to the variable p (which contains
the class inside of it) and show what the properties x and y are.
----------------------------------------------------------------------------------------------------------------

Example: create a program for booking flights in an airline.

Class Flight():

def __init__(self, capacity):


self.capacity = capacity
self.passengers = [] #it creates a list for storing the passengers

def add_passengers(self, name):


self.passengers.append(name)

You might also like