Nuevo Documento de Texto
Nuevo Documento de Texto
x=0
while x<5 :
print ("Not there yet x="+str(x))
x=x+1
print("x="+str(x))
def attempts(n):
x=1
while x<=n:
print(""+str(x))
x+=1
print("done")
attempts(5)
def sum_divisors(n):
sum = 0
contador = 1
print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
for x in range(5):
print(x)
def is_valid(user):
if len(user)>3:
return True
return False
def validate_users(users):
for user in users:
if is_valid(user):
print(user + " is valid")
else:
print(user + " is invalid")
validate_users(["purplecat"])
range(p,q,r): p, p+r, p+2r, p+3r, ... q-1 (if it's a valid increment)
meesage[-1]
slice
fruit="pineapple"
print(fruit[:4])
Pine
pets="Cat & Dog"
pets.index("&")
5
str in str
"this is a string".upper()
You can use the strip method to remove surrounding whitespace from a string.
Whitespace includes spaces, tabs, and newline characters. You can also use the
methods lstrip and rstrip to remove whitespace only from the left or the right
side of the string, respectively.
The method count can be used to return the number of times a substring appears in a
string. This can be handy for finding out how many characters appear in a string,
or counting the number of times a certain word appears in a sentence or paragraph.
If you wanted to check if a string ends with a given substring, you can use the
method endswith. This will return True if the substring is found at the end of the
string, and False if not.
The isnumeric method can check if a string is composed of only numbers. If the
string contains only numbers, this method will return True. We can use this to
check if a string contains numbers before passing the string to the int() function
to convert it to an integer, avoiding an error. Useful!
We took a look at string concatenation using the plus sign, earlier. We can also
use the join method to concatenate strings. This method is called on a string that
will be used to join a list of strings. The method takes a list of strings to be
joined as a parameter, and returns a new string composed of each of the strings
from our list joined using the initial string. For example, "
".join(["This","is","a","sentence"]) would return the string "This is a sentence".
The inverse of the join method is the split method. This allows us to split a
string into a list of strings. By default, it splits by any whitespace characters.
You can also split by any other characters by passing a paramet
print(student_grade("Reed", 80))
print(student_grade("Paige", 92))
print(student_grade("Jesse", 85))
{:.2f}
{:>3.2f}
String operations
len(string) Returns the length of the string
String methods
string.lower() / string.upper() Returns a copy of the string with all lower / upper
case characters
string.isnumeric() Returns True if there are only numeric characters in the string.
If not, returns False.
string.replace(old, new) Returns a new string where all occurrences of old have
been replaced by new.
delimiter.join(list of strings) Returns a new string with all the strings joined by
the delimiter
{:d}
integer value
'{:d}'.format(10.5) ? '10'
{:.2f}
'{:.2f}'.format(0.5) ? '0.50'
{:.2s}
'{:.2s}'.format('Python') ? 'Py'
{:<6s}
{:>6s}
string aligned to the right that many spaces
{:^6s}
Lists Defined
Lists in Python are defined using square brackets, with the elements stored in the
list separated by commas: list = ["This", "is", "a", "list"]. You can use the len()
function to return the number of elements in a list: len(list) would return 4. You
can also use the in keyword to check if a list contains a certain element. If the
element is present, it will return a True boolean. If the element is not found in
the list, it will return False. For example, "This" in list would return True in
our example. Similar to strings, lists can also use indexing to access specific
elements in a list based on their position. You can access the first element in a
list by doing list[0], which would allow you to access the string "This".
In Python, lists and strings are quite similar. They�re both examples of sequences
of data. Sequences have similar properties, like (1) being able to iterate over
them using for loops; (2) support indexing; (3) using the len function to find the
length of the sequence; (4) using the plus operator + in order to concatenate; and
(5) using the in keyword to check if the sequence contains a value. Understanding
these concepts allows you to apply them to other sequence types as well.
fruits.append()
fruits.insert(0,"orandge")
fruits.remove("Melon")
fruits.pop(3)
def car_listing(car_prices):
result = ""
for ext,key in car_prices.items():
result += "{} costs {} dollars".format(ext,key) + "\n"
return result
return new_list
return new_list
print(combine_lists(Jamies_list, Drews_list))
def format_address(address_string):
# Declare variables
number=""
street=""
# Separate the address string into parts
words = address_string.split()
# Traverse through the address parts
for word in words:
# Determine if the address part is the
# house number or part of the street name
if word.isnumeric():
number=word
else:
street += word+ " "
ef count_letters(text):
result = {}
# Go through each letter in the text
text=text.lower().strip()
for letter in text:
# Check if the letter needs to be counted or not
if(letter.isalpha()):
if letter not in result :
# Add or increment the value in the dictionary
result[letter]=0
result[letter]+=1
return result
print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}
print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}