Python Course

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 6

Python

Import
Modules
import math
print math.sqrt(13689)

Universal imports

from module import * (to import everything)


And: from math import *(to import everything from the math).

Import in a list
import math
everything = dir(math)
print everything

Functions
max()
min()
abs() - abs(-42) absolute equal to the absolute value of -42 = 42
Type
the type() function return the type of the data it receives as an argument

Exercise:
First, def a function, shut_down, that takes one argument s. Don’t forget the
parentheses or the colon!

Then, if the shut_down function receives an s equal to "yes", it should return


"Shutting down"

Alternatively, elif s is equal to "no", then the function should return "Shutdown
aborted".

Finally, if shut_down gets anything other than those inputs, the function should
return "Sorry"

def shut_down (s):


if s == "yes":
return "Shutting down"
elif s == "no":
return "Shutdown aborted"
else:
return "Sorry"
Exercise:
First, def a function called distance_from_zero, with one argument (choose
any argument name you like).

If the type of the argument is either int or float, the function should return the
absolute value of the function input.

Otherwise, the function should return "Nope"

def distance_from_zero(lop):
if type(lop) == int or type(lop) == float:
return abs(lop)
else:
return "Nope"
Plan a Trip (taking a vacation)

def hotel_cost(nights):
return 140 * nights

def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475

def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost

def trip_cost(city, days, spending_money):


return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(city) +
spending_money

print trip_cost("Los Angeles", 5, 600)

List

Access by index
Index is like an address that identifies the item's place in the list.

Examples:
numbers = [5, 6, 7, 8]

print "Adding the numbers at indices 0 and 2..."


print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
print numbers[1] + numbers[3]

Python List and Dictionaries


Excersie
zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
zoo_animals[2] = "hyena"
zoo_animals[3] = "lion"

Late Arrival & List Length


suitcase = []
suitcase.append("sunglasses")

suitcase.append("shirt")
suitcase.append("pants")
suitcase.append("shoes")

list_length = len(suitcase)

print "There are %d items in the suitcase." % (list_length)


print suitcase
Display:
There are 4 items in the suitcase.
['sunglasses', 'shirt', 'pants', 'shoes']

List Slicing
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]

# The first and second items (index zero and one)


first = suitcase[0:2]

# Third and fourth items (index two and three)


middle = suitcase[2:4]

# The last two items (index four and five)


last = suitcase[4:6]

Slicing Lists and Strings


animals = "catdogfrog"
cat = animals[:3]
dog = animals[3:6]
frog = animals[6:]

Maintaining Order
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")
animals.inser(duck_index,"cobra")
print animals
#Con esto se busca posicionar una palabra delante de la que se esta buscando.

For One and All


my_list = [1,9,3,8,5,7]
for number in my_list:
print 2 * number
Display. 2 18 6 16 10 14
# multiplica la lista con el valor dado.

More with 'for'


start_list = [5, 3, 1, 2, 4]
square_list = []

for number in start_list:


square_list.append(number ** 2)
square_list.sort()

print square_list
# se agrega los valores cuadraticos de la lista inicial a la siguiente lista
y luego se ordena.

Assigning a dictionary with three key-values pair

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} print


residents['Puffin']
print residents['Sloth']
print residents['Burmese Python']
Display. 104 105 106

New Entries
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']

# Your code here: Add some dish-price pairs to menu!


menu['Hamburger'] = 8.50
menu['Pizza Slice'] = 3.50
menu['Salad'] = 10.00

print "There are " + str(len(menu)) + " items on the menu."


print menu
Deleted in dictionary
zoo_animals = { 'Unicorn' : 'Cotton Candy House','Sloth' : 'Rainforest
Exhibit','Bengal Tiger' : 'Jungle House','Atlantic Puffin' : 'Arctic
Exhibit','Rockhopper Penguin' : 'Arctic Exhibit'}

del zoo_animals['Unicorn']
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin'] = 'Plains Exhibit
print zoo_animals
Display. {'Atlantic Puffin': 'Arctic Exhibit', 'Rockhopper Penguin': 'Plains
Exhibit'}

Remove item from a dictionary


.remove(item)

inventory = {'gold' : 500,'pouch' : ['flint', 'twine', 'gemstone'], #


Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}

# Adding a key 'burlap bag' and assigning a list to it


inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'


inventory['pouch'].sort()

# Your code here


inventory['pocket'] = ['seashell', 'strange berry', 'lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] = inventory['gold'] + 50

String & Console Output


Creating String
'Alpha'
"Bravo"
str(3)
String Methods
len("Charlie")
"Delta".upper()
"Echo".lower()
Printing a string
print "Foxtrot"
Advanced Printing Techniques
g = "Golf"
h = "Hotel"
print "%s, %s" % (g, h)
Date and Time
from datetime import datetime
now = datetime.now()

print ('%02d/%02d/%04d ' % (now.month, now.day, now.year)) + ('%02d:%02d:


%04d' % (now.hour, now.minute, now.second))
Display. 03/28/2023 17:34:0021

import random
def private_key(p):
return random.randrange(2, p)
def public_key(p, g, private):
return pow(g, private, p) #pow(x,y) devuelve el numero x elevado a y, y
entrega un numero real si estos son enteros
def secret(p, public, private):
return pow(public, private, p)

Instructions
Your task is to determine what Bob will reply to someone when they say something to
him or ask him a question.

Bob only ever answers one of five things:

"Sure." This is his response if you ask him a question, such as "How are you?" The
convention used for questions is that it ends with a question mark.
"Whoa, chill out!" This is his answer if you YELL AT HIM. The convention used for
yelling is ALL CAPITAL LETTERS.
"Calm down, I know what I'm doing!" This is what he says if you yell a question at
him.
"Fine. Be that way!" This is how he responds to silence. The convention used for
silence is nothing, or various combinations of whitespace characters.
"Whatever." This is what he answers to anything else.

def response(hey_bob):
if bob.strip().isupper() and bob.endswith('?'):
return "Calm down, I know what I'm doing!"
if bob.strip().endswith("?"):
return "Sure."
if bob.strip().isupper():
return 'Whoa, chill out!'
if not bob.strip():
return 'Fine. Be that way!'
return 'Whatever.'

Exercise Bool
Your task is to convert a number into a string that contains raindrop sounds
corresponding to certain potential factors. A factor is a number that evenly
divides into another number, leaving no remainder. The simplest way to test if one
number is a factor of another is to use the modulo operation.

The rules of raindrops are that if a given number:

has 3 as a factor, add 'Pling' to the result.


has 5 as a factor, add 'Plang' to the result.
has 7 as a factor, add 'Plong' to the result.
does not have any of 3, 5, or 7 as a factor, the result should be the digits of the
number.

def convert(number):
result = ''
if number % 3 == 0:
result += 'Pling'
if number % 5 == 0:
result += 'Plang'
if number % 7 == 0:
result += 'Plong'
return result or str(number)

Implement a program that translates from English to Pig Latin.

Pig Latin is a made-up children's language that's intended to be confusing. It


obeys a few simple rules (below), but when it's spoken quickly it's really
difficult for non-children (and non-native speakers) to understand.

Rule 1: If a word begins with a vowel sound, add an "ay" sound to the end of the
word. Please note that "xr" and "yt" at the beginning of a word make vowel sounds
(e.g. "xray" -> "xrayay", "yttria" -> "yttriaay").
Rule 2: If a word begins with a consonant sound, move it to the end of the word and
then add an "ay" sound to the end of the word. Consonant sounds can be made up of
multiple consonants, a.k.a. a consonant cluster (e.g. "chair" -> "airchay").
Rule 3: If a word starts with a consonant sound followed by "qu", move it to the
end of the word, and then add an "ay" sound to the end of the word (e.g. "square" -
> "aresquay").
Rule 4: If a word contains a "y" after a consonant cluster or as the second letter
in a two letter word it makes a vowel sound (e.g. "rhythm" -> "ythmrhay", "my" ->
"ymay").
There are a few more rules for edge cases, and there are regional variants too.

def _rotate(word):
return word[1:] + word[0]
def _pig_latin(word):
if word[:2] == 'xr':
return 'xrayay' # for some reason
if word[0] == 'y' and word[1] in 'aeiou':
word = _rotate(word)
while word[0] not in 'aeiouy':
word = _rotate(word)
if word[-1] == 'q' and word[0] == 'u':
word = _rotate(word)
return word + 'ay'
def translate(text):
return ' '.join([_pig_latin(word) for word in text.split()])

STRING

You might also like