3 Mart 2019 Pazar

Python Starting

Udemy Problems Solve


Exercise-1



Quiz: Average Electricity Bill

It's time to try a calculation in Python!
My electricity bills for the last three months have been $23, $32 and $64. What is the average monthly electricity bill over the three month period? Write an expression to calculate the mean, and use print() to view the result.

# Write an expression that calculates the average of 23, 32 and 64
# Place the expression in this print statement

print((23+32+64)/3)





Quiz: Calculate

In this quiz you're going to do some calculations for a tiler. Two parts of a floor need tiling. One part is 9 tiles wide by 7 tiles long, the other is 5 tiles wide by 7 tiles long. Tiles come in packages of 6.
  1. How many tiles are needed?
  2. You buy 17 packages of tiles containing 6 tiles each. How many tiles will be left over?


# Fill this in with an expression that calculates how many tiles are needed.

print(9*7+5*7)



# Fill this in with an expression that calculates how many tiles will be left over.

print(17*6-(9*7+5*7))





Quiz: Assign and Modify Variables

Now it's your turn to work with variables. The comments in this quiz (the lines that begin with #) have instructions for creating and modifying variables. After each comment write a line of code that implements the instruction.
Note that this code uses scientific notation to define large numbers. 4.445e8 is equal to 4.445 * 10 ** 8 which is equal to 444500000.0

# The current volume of a water reservoir (in cubic metres)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic metres)
rainfall = 5e6

# decrease the rainfall variable by 10% to account for runoff

rainfall -= rainfall*0.1

# add the rainfall variable to the reservoir_volume variable
reservoir_volume  += rainfall
# increase reservoir_volume by 5% to account for stormwater that flows
reservoir_volume += reservoir_volume*0.05
# into the reservoir in the days following the storm
# decrease reservoir_volume by 5% to account for evaporation
reservoir_volume -= reservoir_volume*0.05
# subtract 2.5e5 cubic metres from reservoir_volume to account for water
# that's piped to arid regions.
reservoir_volume -= 2.5e5
# print the new value of the reservoir_volume variable
print(reservoir_volume)

Quiz: Which is denser, Rio or San Francisco?

Try comparison operators in this quiz! This code calculates the population densities of Rio de Janeiro and San Francisco.
Write code to compare these densities. Is the population of San Francisco more dense than that of Rio de Janeiro? Print True if it is and False if not.



sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5

san_francisco_pop_density = sf_population/sf_area
rio_de_janeiro_pop_density = rio_population/rio_area

result = san_francisco_pop_density > rio_de_janeiro_pop_density

print(result)

# Write code that prints True if San Francisco is denser than Rio, and False otherwise






Quiz: Fix the Quote


The line of code in the following quiz will cause a SyntaxError, thanks to the misuse of quotation marks. First run it with Test Run to view the error message. Then resolve the problem so that the quote (from Henry Ford) is correctly assigned to the variable ford_quote.



# TODO: Fix this string!
ford_quote = 'Whether you think you can, or you think you can\'t--you\'re right.'

print(ford_quote)




You fixed the string, nice work! There are two ways to do this:

with backslash escaping: ford_quote = 'Whether you think you can, or you think you can\'t--you\'re right.'

with double quotes: ford_quote = "Whether you think you can, or you think you can't--you're right."






We’ve already seen that the type of objects will affect how operators work on them. What will be the output of this code?

coconut_count = "34"
mango_count = "15"
tropical_fruit_count = coconut_count + mango_count
print(tropical_fruit_count)






Quiz: Write a Server Log Message

In this programming quiz, you’re going to use what you’ve learned about strings to write a logging message for a server.
You’ll be provided with example data for a user, the time of their visit and the site they accessed. You should use the variables provided and the techniques you’ve learned to print a log message like this one (with the username, url, and timestamp replaced with values from the appropriate variables):
Yogesh accessed the site http://petshop.com/pets/reptiles/pythons at 16:20.

Use the Test Run button to see your results as you work on coding this piece by piece.


username = "Kinari"
timestamp = "04:50"
url = "http://petshop.com/pets/mammals/cats"

# TODO: print a log message using the variables above.
# The message should have the same format as this one:
# "Yogesh accessed the site http://petshop.com/pets/reptiles/pythons at 16:20."
message = username + " accessed the site " + url + " at " + timestamp + "."

print(message)




Quiz: Write a Server Log Message

In this programming quiz, you’re going to use what you’ve learned about strings to write a logging message for a server.
You’ll be provided with example data for a user, the time of their visit and the site they accessed. You should use the variables provided and the techniques you’ve learned to print a log message like this one (with the username, url, and timestamp replaced with values from the appropriate variables):
Yogesh accessed the site http://petshop.com/pets/reptiles/pythons at 16:20.
Use the Test Run button to see your results as you work on coding this piece by piece.


username = "Kinari"
timestamp = "04:50"
url = "http://petshop.com/pets/mammals/cats"

# TODO: print a log message using the variables above.
# The message should have the same format as this one:
# "Yogesh accessed the site http://petshop.com/pets/reptiles/pythons at 16:20."
print(username+ " accessed the site "+ url +" at " + timestamp+".")



Type Playground

Use this programming space with Test Run to experiment with types of objects. Don't forget to use print to see the output of your code.

print("caner")
a = "caner"
print(a)
print(len(a))
print(type(a))
print(type(len(a)/2))

caner caner 5 <class 'str'> <class 'float'>

Quiz: Total Sales

In this quiz, you’ll need to change the types of the input and output data in order to get the result you want.
Calculate and print the total sales for the week from the data provided. Print out a string of the form "This week's total sales: xxx", where xxx will be the actual total of all the numbers. You’ll need to change the type of the input data in order to calculate that total.


mon_sales = "121"
tues_sales = "105"
wed_sales = "110"
thurs_sales = "98"
fri_sales = "95"

#TODO: Print a string with this format: This week's total sales: xxx
# You will probably need to write some lines of code before the print statement.

sum = int(mon_sales) + int(tues_sales) + int(wed_sales) + int(thurs_sales) + int(fri_sales)
sum = str (sum)
print("This week's total sales: "+ sum)

This week's total sales: 529


String Method Playground



# Browse the complete list of string methods at:
# https://docs.python.org/3/library/stdtypes.html#string-methods
# and try them out here

print("caner ezeroglu".title())


full_name = "caner ezeroglu"

print(full_name.islower())

print(full_name.count("e"))

print("caner EzeroGLu".capitalize())

print("Caner EzeroGLu".casefold())


Caner Ezeroglu True 3 Caner ezeroglu caner ezeroglu



format() Practice

Use the coding space below to practice using the format() string method. There are no right or wrong answers here, just practice!



# Write two lines of code below, each assigning a value to a variable


# Now write a print statement using .format() to print out a sentence and the 
#   values of both of the variables


print("Caner Ezeroglu {} in {}".format("born", "Turkey"))

a = "Caner Ezeroglu born in Turkey"

a.split(' ', 2)





Caner Ezeroglu born in Turkey




Quiz: String Methods Coding Practice

Below, we have a string variable that contains the first verse of the poem, If by Rudyard Kipling. Remember, \n is a special sequence of characters that causes a line break (a new line).
verse = "If you can keep your head when all about you\n  Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n  But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n  Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n  And yet don’t look too good, nor talk too wise:"
Use the code editor below to answer the following questions about verse and use Test Run to check your output in the quiz at the bottom of this page.
  1. What is the length of the string variable verse?
  2. What is the index of the first occurrence of the word 'and' in verse?
  3. What is the index of the last occurrence of the word 'you' in verse?
  4. What is the count of occurrences of the word 'you' in the verse?
You will need to refer to Python's string methods documentation.


verse = "If you can keep your head when all about you\n  Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n  But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n  Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n  And yet don’t look too good, nor talk too wise:"
print(verse)

# Use the appropriate functions and methods to answer the questions above
# Bonus: practice using .format() to output your answers in descriptive messages!

textlength = len(verse)

print ("\nThe length of the string variable is {} ".format(textlength))
print("The index of the first occurrence of the word 'and' is in {}".format(verse.find('and')))
print("The index of the last occurrence of the word 'you' is in {}".format(verse.rfind('you')))
print("The count of occurrences of the word 'you' is in {}".format(verse.count('you')))



If you can keep your head when all about you Are losing theirs and blaming it on you, If you can trust yourself when all men doubt you, But make allowance for their doubting too; If you can wait and not be tired by waiting, Or being lied about, don’t deal in lies, Or being hated, don’t give way to hating, And yet don’t look too good, nor talk too wise: The length of the string variable is 362 The index of the first occurrence of the word 'and' is in 65 The index of the last occurrence of the word 'you' is in 186 The count of occurrences of the word 'you' is in 8




Exercise-2








Quiz: List Indexing


Use list indexing to determine how many days are in a particular month based on the integer variable month, and store that value in the integer variable num_days. For example, if month is 8, num_days should be set to 31, since the eighth month, August, has 31 days.

Remember to account for zero-based indexing!







month = 8

days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]


# use list indexing to determine the number of days in the month

num_days = days_in_month[month - 1]

print(num_days)


31



Quiz: List Indexing

Use list indexing to determine how many days are in a particular month based on the integer variable month, and store that value in the integer variable num_days. For example, if month is 8, num_days should be set to 31, since the eighth month, August, has 31 days.
Remember to account for zero-based indexing!



month = 8
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]

# use list indexing to determine the number of days in month

num_days = days_in_month[month - 1]

print(num_days)


Quiz: Slicing Lists

Select the three most recent dates from this list using list slicing notation. Hint: negative indexes work in slices!




eclipse_dates = ['June 21, 2001', 'December 4, 2002', 'November 23, 2003',
                 'March 29, 2006', 'August 1, 2008', 'July 22, 2009',
                 'July 11, 2010', 'November 13, 2012', 'March 20, 2015',
                 'March 9, 2016']
                 
                 
# TODO: Modify this line so it prints the last three elements of the list
print(eclipse_dates[-3:])




QUESTİON 3 OF 3

Suppose we have the following two expressions, sentence1 and sentence2:
sentence1 = "I wish to register a complaint."
sentence2 = ["I", "wish", "to", "register", "a", "complaint", "."]
Match the Python code below with the value of the modified sentence1 or sentence2. If the code results in an error, match it with “Error”.




PYTHON CODE

VALUE OF SENTENCE1 OR SENTENCE2

sentence2[6]="!"
["I", "wish", "to", "register", "a", "complaint", "!"]
sentence2[0]= "Our Majesty"
["Our Majesty", "wish", "to", "register", "a", "complaint", "."]
sentence1[30]="!"
Error






Practice: Which Prize

Write an if statement that lets a competitor know which of these prizes they won based on the number of points they scored, which is stored in the integer variable points.
PointsPrize
1 - 50wooden rabbit
51 - 150no prize
151 - 180wafer-thin mint
181 - 200penguin
All of the lower and upper bounds here are inclusive, and points can only take on positive integer values up to 200.
In your if statement, assign the result variable to a string holding the appropriate message based on the value of points. If they've won a prize, the message should state "Congratulations! You won a [prize name]!" with the prize name. If there's no prize, the message should state "Oh dear, no prize this time."
Note: Feel free to test run your code with other inputs, but when you submit your answer, only use the original input of points = 174. You can hide your other inputs by commenting them out.



points = 174  # use this input to make your submission

# write your if statement here

if points >= 1 and points <= 50:
    a = "wooden rabbit"
elif points > 50 and points <= 150:
    a = "no prize"
elif points > 150 and points <= 180:
    a = "wafer-thin mint"
elif points > 180 and points <= 200:
    a = "penguin"
else :
    a = "... Oh dear, no prize this time!"

result = "Congratulations! You won a {}".format(a)


print(result)





Quiz: Guess My Number

You decide you want to play a game where you are hiding a number from someone. Store this number in a variable called 'answer'. Another user provides a number called 'guess'. By comparing guess to answer, you inform the user if their guess is too high or too low.
Fill in the conditionals below to inform the user about how their guess compares to the answer.

# '''
# You decide you want to play a game where you are hiding 
# a number from someone.  Store this number in a variable 
# called 'answer'.  Another user provides a number called
# 'guess'.  By comparing guess to answer, you inform the user
# if their guess is too high or too low.

# Fill in the conditionals below to inform the user about how
# their guess compares to the answer.
# '''
answer = 5
guess = 5

if guess < answer:
    result = "Oops!  Your guess was too low."
elif guess > answer:
    result = "Oops!  Your guess was too high."
elif guess == answer:
    result = "Nice!  Your guess matched the answer!"

print(result)



Quiz: Tax Purchase

Depending on where an individual is from we need to tax them appropriately. The states of CA, MN, and NY have taxes of 7.5%, 9.5%, and 8.9% respectively. Use this information to take the amount of a purchase and the corresponding state to assure that they are taxed by the right amount.

# '''
# Depending on where an individual is from we need to tax them 
# appropriately.  The states of CA, MN, and 
# NY have taxes of 7.5%, 9.5%, and 8.9% respectively.
# Use this information to take the amount of a purchase and 
# the corresponding state to assure that they are taxed by the right
# amount.
# '''
state = "CA"
purchase_amount = 20

if state == "CA":
    tax_amount = .075
    total_cost = purchase_amount*(1+tax_amount)
    result = "Since you're from {}, your total cost is {}.".format(state, total_cost)

elif state == "MN":
    tax_amount = .095
    total_cost = purchase_amount*(1+tax_amount)
    result = "Since you're from {}, your total cost is {}.".format(state, total_cost)

elif state == "NY":
    tax_amount = .089
    total_cost = purchase_amount*(1+tax_amount)
    result = "Since you're from {}, your total cost is {}.".format(state, total_cost)

print(result)




Quiz: Using Truth Values of Objects

The code below is the solution to the Which Prize quiz you've seen previously. You're going to rewrite this based on what you've learned about truth values.
points = 174

if points <= 50:
    result = "Congratulations! You won a wooden rabbit!"
elif points <= 150:
    result = "Oh dear, no prize this time."
elif points <= 180:
    result = "Congratulations! You won a wafer-thin mint!"
else:
    result = "Congratulations! You won a penguin!"

print(result)
You will use a new variable prize to store a prize name if one was won, and then use the truth value of this variable to compose the result message. This will involve two if statements.
1st conditional statement: update prize to the correct prize name based on points.
2nd conditional statement: set result to the correct phrase based on whether prize is evaluated as True or False.
  • If prize is None, result should be set to "Oh dear, no prize this time."
  • If prize contains a prize name, result should be set to "Congratulations! You won a {}!".format(prize). This will avoid having the multiple result assignments for different prizes.
At the beginning of your code, set prize to None, as the default value.




points = 174  # use this input when submitting your answer

# set prize to default value of None
prize = None

# use the value of points to assign prize to the correct prize name
if points <= 50:
    prize = "wooden rabbit"
elif 151 <= points <= 180:
    prize = "wafer-thin mint"
elif points >= 181:
    prize = "penguin"

# use the truth value of prize to assign result to the correct message
if prize:
    result = "Congratulations! You won a {}!".format(prize)
else:
    result = "Oh dear, no prize this time."

print(result)




Practice: Quick Brown Fox

Use a for loop to take a list and print each element of the list in its own line.
Example:
sentence = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
Output:
the
quick
brown
fox
jumped
over
the
lazy
dog


sentence = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]

# Write a for loop to print out each word in the sentence list, one word per line

for loop in sentence:
    print (loop)



Practice: Multiples of 5

Write a for loop below that will print out every whole number that is a multiple of 5 and less than or equal to 30.
This should output:
5
10
15
20
25
30


# Write a for loop using range() to print out multiples of 5 up to 30 inclusive

for number in range(5,35,5):
    print(number)



Quiz: Create Usernames

Write a for loop that iterates over the names list to create a usernames list. To create a username for each name, make everything lowercase and replace spaces with underscores. Running your forloop over the list:
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
should create the list:
usernames = ["joey_tribbiani", "monica_geller", "chandler_bing", "phoebe_buffay"]
HINT: Use the .replace() method to replace the spaces with underscores. Check out how to use this method in this Stack Overflow answer.



names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []

# write your for loop here

for name in names:
    usernames.append(name.lower().replace(" ", "_"))

print(usernames)






Quiz: Modify Usernames with Range

Write a for loop that uses range() to iterate over the positions in usernames to modify the list. Like you did in the previous quiz, change each name to be lowercase and replace spaces with underscores. After running your loop, this list
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
should change to this:
usernames = ["joey_tribbiani", "monica_geller", "chandler_bing", "phoebe_buffay"]




usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]

# write your for loop here

for index in range(len(usernames)):
    usernames[index] = usernames[index].lower().replace(" ", "_")
    
print(usernames)








Quiz: Tag Counter

Write a for loop that iterates over a list of strings, tokens, and counts how many of them are XML tags. XML is a data language similar to HTML. You can tell if a string is an XML tag if it begins with a left angle bracket "<" and ends with a right angle bracket ">". Keep track of the number of tags using the variable count.
You can assume that the list of strings will not contain empty strings.


tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0

# write your for loop here
for token in tokens:
    if token[0] == '<' and token[-1] == '>':
        count += 1

print(count)



Quiz: Create an HTML List

Write some code, including a for loop, that iterates over a list of strings and creates a single string, html_str, which is an HTML list. For example, if the list is items = ['first string', 'second string'], printing html_str should output:
<ul>
<li>first string</li>
<li>second string</li>
</ul>
That is, the string's first line should be the opening tag <ul>. Following that is one line per element in the source list, surrounded by <li> and </li> tags. The final line of the string should be the closing tag </ul>.





items = ['first string', 'second string']
html_str = "<ul>\n"  # "\ n" is the character that marks the end of the line, it does
                     # the characters that are after it in html_str are on the next line

# write your code here
for item in items:
    html_str += "<li>{}</li>\n".format(item)
html_str += "</ul>"

print(html_str)



Quiz: Fruit Basket - Task 1

You would like to count the number of fruits in your basket. In order to do this, you have the following dictionary and list of fruits. Use the dictionary and list to count the total number of fruits, but you do not want to count the other items in your basket.





# You would like to count the number of fruits in your basket. 
# In order to do this, you have the following dictionary and list of
# fruits.  Use the dictionary and list to count the total number
# of fruits, but you do not want to count the other items in your basket.

result = 0
basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']

#Iterate through the dictionary

for object, count in basket_items.items():
    if object in fruits:
        result +=count

#if the key is in the list of fruits, add the value (number of fruits) to result

print("There are {} fruits in the basket.".format(result))



Quiz: Fruit Basket - Task 2

If your solution is robust, you should be able to use it with any dictionary of items to count the number of fruits in the basket. Try the loop for each of the dictionaries below to make sure it always works.



#Example 1

result = 0
basket_items = {'pears': 5, 'grapes': 19, 'kites': 3, 'sandwiches': 8, 'bananas': 4}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']

# Your previous solution here

for object, count in basket_items.items():
    if object in fruits:
        result +=count

#if the key is in the list of fruits, add the value (number of fruits) to result

print("There are {} fruits in the basket.".format(result))

#Example 2

result = 0
basket_items = {'peaches': 5, 'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']

# Your previous solution here
for object, count in basket_items.items():
    if object in fruits:
        result +=count

#if the key is in the list of fruits, add the value (number of fruits) to result

print("There are {} fruits in the basket.".format(result))
#Example 3

result = 0
basket_items = {'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4, 'bears': 10}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']

for object, count in basket_items.items():
    if object in fruits:
        result +=count

#if the key is in the list of fruits, add the value (number of fruits) to result

print("There are {} fruits in the basket.".format(result))





Quiz: Fruit Basket - Task 3

So, a couple of things about the above examples:
  1. It is a bit annoying having to copy and paste all the code to each spot - wouldn't it be nice to have a way to repeat the process without copying all the code? Don't worry! You will learn how to do this in the next lesson!
  2. It would be nice to keep track of both the number of fruits and other items in the basket.
Use the environment below to try out this second part.





# You would like to count the number of fruits in your basket. 
# In order to do this, you have the following dictionary and list of
# fruits.  Use the dictionary and list to count the total number
# of fruits and not_fruits.

fruit_count, not_fruit_count = 0, 0
basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']

result = 0
other_result = 0
#Iterate through the dictionary

for object, count in basket_items.items():
    if object in fruits:
        fruit_count += count

#if the key is in the list of fruits, add to fruit_count.
    else:
        not_fruit_count += count
#if the key is not in the list, then add to the not_fruit_count


print(fruit_count, not_fruit_count)






Practice: Factorials with While Loops

Find the factorial of a number using a while loop.
factorial of a whole number is that number multiplied by every whole number between itself and 1. For example, 6 factorial (written "6!") equals 6 x 5 x 4 x 3 x 2 x 1 = 720. So 6! = 720.
We can write a while loop to take any given number and figure out what its factorial is.
Example: If number is 6, your code should compute and print the product, 720.




# number to find the factorial of
number = 6   

# start with our product equal to one
product = 1

# track the current number being multiplied
current = 1

# write your while loop here
while current <= number:
    product *= current
    current += 1
    # multiply the product so far by the current number
    
    
    # increment current with each iteration until it reaches number



# print the factorial of number
print(product)





Practice: Factorials with For Loops

Now use a for loop to find the factorial!
It will now be great practice for you to try to revise the code you wrote above to find the factorial of a number, but this time, using a for loop. Try it in the code editor below!



# number to find the factorial of
number = 6   

# start with our product equal to one
product = 1

# write your for loop here

for num in range(2, number+1):
    product *= num

# print the factorial of number
print(product)






Quiz: Count By

Suppose you want to count from some number start_num by another number count_by until you hit a final number end_num. Use break_num as the variable that you'll change each time through the loop. For simplicity, assume that end_num is always larger than start_num and count_by is always positive.
Before the loop, what do you want to set break_num equal to? How do you want to changebreak_num each time through the loop? What condition will you use to see when it's time to stop looping?
After the loop is done, print out break_num, showing the value that indicated it was time to stop looping. It is the case that break_num should be a number that is the first number larger than end_num.


start_num = 1
end_num = 100
count_by = 2

# write a while loop that uses break_num as the ongoing number to 
#   check against end_num
break_num =start_num

while break_num < end_num:
    break_num += count_by

print(break_num)







Quiz: Count By Check

Suppose you want to count from some number start_num by another number count_by until you hit a final number end_num, and calculate break_num the way you did in the last quiz.
Now in addition, address what would happen if someone gives a start_num that is greater than end_num. If this is the case, set result to "Oops! Looks like your start value is greater than the end value. Please try again."Otherwise, set result to the value of break_num.


start_num = 5
end_num = 100
count_by = 2

# write a condition to check that end_num is larger than start_num before looping
# write a while loop that uses break_num as the ongoing number to 
#   check against end_num
if start_num > end_num:
    result = "Oops! Looks like your start value is greater than the end value. Please try again."
    
else:
    break_num = start_num
    while break_num < end_num:
        break_num += count_by
    result = break_num

print(result)



Quiz: Nearest Square

Write a while loop that finds the largest square number less than an integerlimit and stores it in a variable nearest_square. A square number is the product of an integer multiplied by itself, for example 36 is a square number because it equals 6*6.
For example, if limit is 40, your code should set the nearest_square to 36.



limit = 40

# write your while loop here

num = 0
while (num+1)**2 < limit:
    num += 1
nearest_square = num**2


print(nearest_square)





Question: What type of loop should we use?

You need to write a loop that takes the numbers in a given list named num_list:
num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
Your code should add up the odd numbers in the list, but only up to the first 5 odd numbers together. If there are more than 5 odd numbers, you should stop at the fifth. If there are fewer than 5 odd numbers, add all of the odd numbers.
Would you use a while or a for loop to write this code?
We have provided our solution on the next page. Feel free to use the coding playground below to test your code.



num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]

count_odd = 0
list_sum = 0
i = 0
len_num_list = len(num_list)

while (count_odd < 5) and (i < len_num_list):
    if num_list[i] % 2 != 0:
        list_sum += num_list[i]
        count_odd += 1
    i += 1

print ("The numbers of odd numbers added are: {}".format(count_odd))
print ("The sum of the odd numbers added is: {}".format(list_sum))


BREAK AND CONTINUE




manifest = [("bananas", 15), ("mattresses", 24), ("dog kennels", 42), ("machine", 120), ("cheeses", 5)]

# the code breaks the loop when weight exceeds or reaches the limit
print("METHOD 1")
weight = 0
items = []
for cargo_name, cargo_weight in manifest:
    print("current weight: {}".format(weight))
    if weight >= 100:
        print("  breaking loop now!")
        break
    else:
        print("  adding {} ({})".format(cargo_name, cargo_weight))
        items.append(cargo_name)
        weight += cargo_weight

print("\nFinal Weight: {}".format(weight))
print("Final Items: {}".format(items))

# skips an iteration when adding an item would exceed the limit
# breaks the loop if weight is exactly the value of the limit
print("\nMETHOD 2")
weight = 0
items = []
for cargo_name, cargo_weight in manifest:
    print("current weight: {}".format(weight))
    if weight >= 100:
        print("  breaking from the loop now!")
        break
    elif weight + cargo_weight > 100:
        print("  skipping {} ({})".format(cargo_name, cargo_weight))
        continue
    else:
        print("  adding {} ({})".format(cargo_name, cargo_weight))
        items.append(cargo_name)
        weight += cargo_weight

print("\nFinal Weight: {}".format(weight))
print("Final Items: {}".format(items))






METHOD 1 current weight: 0 adding bananas (15) current weight: 15 adding mattresses (24) current weight: 39 adding dog kennels (42) current weight: 81 adding machine (120) current weight: 201 breaking loop now! Final Weight: 201 Final Items: ['bananas', 'mattresses', 'dog kennels', 'machine'] METHOD 2 current weight: 0 adding bananas (15) current weight: 15 adding mattresses (24) current weight: 39 adding dog kennels (42) current weight: 81 skipping machine (120) current weight: 81 adding cheeses (5) Final Weight: 86 Final Items: ['bananas', 'mattresses', 'dog kennels', 'cheeses']


DEFINING FUNCTIONS

Quiz: Population Density Function

Write a function named population_density that takes two arguments, population and land_area, and returns a population density calculated from those values. I've included two test cases that you can use to verify that your function works correctly. Once you've written your function, use the Test Run button to test your code.



# write your function here
def population_density(population, land_area):
    return population/land_area


# test cases for your function
test1 = population_density(10, 1)
expected_result1 = 10
print("expected result: {}, actual result: {}".format(expected_result1, test1))

test2 = population_density(864816, 121.4)
expected_result2 = 7123.6902801
print("expected result: {}, actual result: {}".format(expected_result2, test2))



Quiz: readable_timedelta

Write a function named readable_timedelta. The function should take one argument, an integer days, and return a string that says how many weeks and days that is. For example, calling the function and printing the result like this:
print(readable_timedelta(10))
should output the following:
1 week(s) and 3 day(s).



# write your function here
def readable_timedelta(days):
    weeks = days // 7
    remainder = days % 7
    return "{} week(s) and {} day(s).".format(weeks, remainder)
    
# test your function
print(readable_timedelta(10))




REFERENCE => UDACITY PYTHON COURSE






Ros2 çalışmaları

 1) Her saniye yazı yazdırma. Eklediğim kod öncelikle Hello Cpp Node yazdıracak ardınca Hello ekleyecek. benim .cpp dosyamın adı my_first_no...