0% found this document useful (0 votes)
83 views6 pages

Nuevo Documento de Texto

The document contains examples of Python code demonstrating various concepts including: - Looping with while and for loops - Defining and calling functions - String operations and methods - List operations and methods - Formatting strings - Counting letters in strings The code shows how to iterate over sequences, access elements, define and call functions, manipulate strings and lists, and format output.

Uploaded by

Gloria Peralta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views6 pages

Nuevo Documento de Texto

The document contains examples of Python code demonstrating various concepts including: - Looping with while and for loops - Defining and calling functions - String operations and methods - List operations and methods - Formatting strings - Counting letters in strings The code shows how to iterate over sequences, access elements, define and call functions, manipulate strings and lists, and format output.

Uploaded by

Gloria Peralta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

while loop

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

while contador < n:


if n % contador ==0 :
# print(contador +" ")
sum+=contador
contador+=1
return sum

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"])

for variable in sequence


body

range(n): 0, 1, 2, ... n-1


range(x,y): x, x+1, x+2, ... y-1

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

def student_grade(name, grade):


return "{},{}".format(name,grade)

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

for character in string Iterates over each character in the string


if substring in string Checks whether the substring is part of the string

string[i] Accesses the character at index i of the string, starting at zero

string[i:j] Accesses the substring starting at index i, ending at index j-1. If i


is omitted, it's 0 by default. If j is omitted, it's len(string) by default.

String methods
string.lower() / string.upper() Returns a copy of the string with all lower / upper
case characters

string.lstrip() / string.rstrip() / string.strip() Returns a copy of the string


without left / right / left or right whitespace

string.count(substring) Returns the number of times substring is present in the


string

string.isnumeric() Returns True if there are only numeric characters in the string.
If not, returns False.

string.isalpha() Returns True if there are only alphabetic characters in the


string. If not, returns False.

string.split() / string.split(delimiter) Returns a list of substrings that were


separated by whitespace / delimiter

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}

floating point with that many decimals

'{:.2f}'.format(0.5) ? '0.50'

{:.2s}

string with that many characters

'{:.2s}'.format('Python') ? 'Py'

{:<6s}

string aligned to the left that many spaces

'{:<6s}'.format('Py') ? 'Py '

{:>6s}
string aligned to the right that many spaces

'{:>6s}'.format('Py') ? ' Py'

{:^6s}

string centered in that many spaces

'{:^6s}'.format('Py') ? ' Py '

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

print(car_listing({"Kia Soul":19000, "Lamborghini Diablo":55000, "Ford


Fiesta":13000, "Toyota Prius":24000}))

def squares(start, end):


new_list=[]
for n in range(start,end+1):
new_list.append(n*n)

return new_list

print(squares(2, 3)) # Should be [4, 9]


print(squares(1, 5)) # Should be [1, 4, 9, 16, 25]
print(squares(0, 10)) # Should be [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

def combine_lists(list1, list2):


# Generate a new list containing the elements of list2
# Followed by the elements of list1 in reverse order
# list1=list1.reverse()
new_list=list2
#print(len(list1))
n1=len(list1)-1
while n1>=0:
#print(n1)
#print(list1[n1])
new_list.append(list1[n1])
n1=n1-1

return new_list

Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]#inverso segundo


Drews_list = ["Mike", "Carol", "Greg", "Marcia"] #primero

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+ " "

# Does anything else need to be done


# before returning the result?

# Return the formatted string


return "house number {} on street named {}".format(number,street.rstrip())

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("Math is fun! 2+2=4"))


# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n':
1}

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}

You might also like