• How it works
  • Homework answers

Physics help

Answer to Question #95689 in Python for kylie willis-bixby

Need a fast expert's response?

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS !

Leave a comment

Ask your question, related questions.

  • 1. For this lab you will find the area of an irregularly shaped room with the shape as shown above. A
  • 2. Write the code to input a number and print the square root. Use the absolute value function to make
  • 3. Assignment 2: Room Area Room shape For this lab you will find the area of an irregularly shaped r
  • 4. Let's play Silly Sentences! Enter a name: Grace Enter an adjective: stinky Enter an adjecti
  • 5. Write a cash register program that calculates change for a restaurant of your choice. Your program s
  • 6. A vacation rental property management company must file a monthly sales tax report listing the total
  • 7. Which function would you choose to use to remove leading and trailing white spaces from a given stri
  • Programming
  • Engineering

10 years of AssignmentExpert

Who Can Help Me with My Assignment

There are three certainties in this world: Death, Taxes and Homework Assignments. No matter where you study, and no matter…

How to finish assignment

How to Finish Assignments When You Can’t

Crunch time is coming, deadlines need to be met, essays need to be submitted, and tests should be studied for.…

Math Exams Study

How to Effectively Study for a Math Test

Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…

  • Hands-on Python Tutorial »
  • 1. Beginning With Python »

1.6. Variables and Assignment ¶

Each set-off line in this section should be tried in the Shell.

Nothing is displayed by the interpreter after this entry, so it is not clear anything happened. Something has happened. This is an assignment statement , with a variable , width , on the left. A variable is a name for a value. An assignment statement associates a variable name on the left of the equal sign with the value of an expression calculated from the right of the equal sign. Enter

Once a variable is assigned a value, the variable can be used in place of that value. The response to the expression width is the same as if its value had been entered.

The interpreter does not print a value after an assignment statement because the value of the expression on the right is not lost. It can be recovered if you like, by entering the variable name and we did above.

Try each of the following lines:

The equal sign is an unfortunate choice of symbol for assignment, since Python’s usage is not the mathematical usage of the equal sign. If the symbol ↤ had appeared on keyboards in the early 1990’s, it would probably have been used for assignment instead of =, emphasizing the asymmetry of assignment. In mathematics an equation is an assertion that both sides of the equal sign are already, in fact, equal . A Python assignment statement forces the variable on the left hand side to become associated with the value of the expression on the right side. The difference from the mathematical usage can be illustrated. Try:

so this is not equivalent in Python to width = 10 . The left hand side must be a variable, to which the assignment is made. Reversed, we get a syntax error . Try

This is, of course, nonsensical as mathematics, but it makes perfectly good sense as an assignment, with the right-hand side calculated first. Can you figure out the value that is now associated with width? Check by entering

In the assignment statement, the expression on the right is evaluated first . At that point width was associated with its original value 10, so width + 5 had the value of 10 + 5 which is 15. That value was then assigned to the variable on the left ( width again) to give it a new value. We will modify the value of variables in a similar way routinely.

Assignment and variables work equally well with strings. Try:

Try entering:

Note the different form of the error message. The earlier errors in these tutorials were syntax errors: errors in translation of the instruction. In this last case the syntax was legal, so the interpreter went on to execute the instruction. Only then did it find the error described. There are no quotes around fred , so the interpreter assumed fred was an identifier, but the name fred was not defined at the time the line was executed.

It is both easy to forget quotes where you need them for a literal string and to mistakenly put them around a variable name that should not have them!

Try in the Shell :

There fred , without the quotes, makes sense.

There are more subtleties to assignment and the idea of a variable being a “name for” a value, but we will worry about them later, in Issues with Mutable Objects . They do not come up if our variables are just numbers and strings.

Autocompletion: A handy short cut. Idle remembers all the variables you have defined at any moment. This is handy when editing. Without pressing Enter, type into the Shell just

Assuming you are following on the earlier variable entries to the Shell, you should see f autocompleted to be

This is particularly useful if you have long identifiers! You can press Alt-/ several times if more than one identifier starts with the initial sequence of characters you typed. If you press Alt-/ again you should see fred . Backspace and edit so you have fi , and then and press Alt-/ again. You should not see fred this time, since it does not start with fi .

1.6.1. Literals and Identifiers ¶

Expressions like 27 or 'hello' are called literals , coming from the fact that they literally mean exactly what they say. They are distinguished from variables, whose value is not directly determined by their name.

The sequence of characters used to form a variable name (and names for other Python entities later) is called an identifier . It identifies a Python variable or other entity.

There are some restrictions on the character sequence that make up an identifier:

The characters must all be letters, digits, or underscores _ , and must start with a letter. In particular, punctuation and blanks are not allowed.

There are some words that are reserved for special use in Python. You may not use these words as your own identifiers. They are easy to recognize in Idle, because they are automatically colored orange. For the curious, you may read the full list:

There are also identifiers that are automatically defined in Python, and that you could redefine, but you probably should not unless you really know what you are doing! When you start the editor, we will see how Idle uses color to help you know what identifies are predefined.

Python is case sensitive: The identifiers last , LAST , and LaSt are all different. Be sure to be consistent. Using the Alt-/ auto-completion shortcut in Idle helps ensure you are consistent.

What is legal is distinct from what is conventional or good practice or recommended. Meaningful names for variables are important for the humans who are looking at programs, understanding them, and revising them. That sometimes means you would like to use a name that is more than one word long, like price at opening , but blanks are illegal! One poor option is just leaving out the blanks, like priceatopening . Then it may be hard to figure out where words split. Two practical options are

  • underscore separated: putting underscores (which are legal) in place of the blanks, like price_at_opening .
  • using camel-case : omitting spaces and using all lowercase, except capitalizing all words after the first, like priceAtOpening

Use the choice that fits your taste (or the taste or convention of the people you are working with).

Table Of Contents

  • 1.6.1. Literals and Identifiers

Previous topic

1.5. Strings, Part I

1.7. Print Function, Part I

  • Show Source

Quick search

Enter search terms or a module, class or function name.

  • 12. Functions »
  • Area Calculator
  • View page source

Area Calculator ¶

Write a program to calculate the area of four different geometric shapes: triangles, squares, rectangles, and circles. You must use functions. Here are the functions you should create:

Copy-paste-proof image

Name your file area_calculator.py

Your program should present a menu for the human to choose which shape to calculate, then ask them for the appropriate values (length, width, radius, etc.). Then it should pass those values to the appropriate function and display the resulting area.

Notice that you must not input the values inside the functions, and you must not display the values inside the functions. All input and output must be in the main() function, and values must be passed to the functions and returned from them.

You will need to construct your own main function and use the magical if __name__ == "__main__": statement as seen in previous assignments.

You’ll need the value of π for area_circle() ; feel free to use the math library’s pi variable.

The menu should keep looping until the human chooses to quit.

©2021 Daniel Gallo

This assignment is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License .

Creative Commons License

Adapted for Python from Graham Mitchell’s Programming By Doing

Browse Course Material

Course info, instructors.

  • Dr. Ana Bell
  • Prof. Eric Grimson
  • Prof. John Guttag

Departments

  • Electrical Engineering and Computer Science

As Taught In

  • Algorithms and Data Structures
  • Programming Languages

Learning Resource Types

Introduction to computer science and programming in python, mit6_0001f16_problem set 1.

This resource contains information regarding introduction to computer science and programming in Python: Problem set.

facebook

You are leaving MIT OpenCourseWare

  • Selection Sort
  • Python Program To
  • Iterative Merge Sort
  • Find Largest Prime Factor
  • Maximum and Minimum Elements from a tuple
  • Iterative QuickSort
  • Binary Search
  • Linear Search
  • Insertion Sort
  • Insertion sort
  • Bubble Sort
  • Counting sort
  • Topological sort
  • Binary Insertion Sort
  • Bitonic sort
  • Print Own Font
  • Print Current Time
  • Swap two numbers using third variable
  • Swap two numbers without using third variable
  • Binary Anagram
  • Find Mirror Characters
  • Python Convert Snake
  • Area of Square
  • Add Two Numbers
  • Handle Missing Keys
  • Find Factorial
  • Simple Interest
  • Compound Interest
  • Armstrong Number
  • Area of Circle
  • Prime Number
  • Find nth Fibonacci Number
  • Print ASCII
  • Find Sum of Squares
  • Find Sum of Cubes
  • Find Most Occurring Char
  • Python Regex to
  • List of Tuples
  • Display Keys associated with Values in Dictionary
  • Find Closest Pair to Kth index element in Tuple
  • Sum of Array
  • Largest in Array
  • Array Rotation
  • Rotate Array by Reversal
  • Split and Merge Array
  • Monotonic Array
  • Key-Values List To Dictionary
  • Print Anagrams in LIst
  • Interchange First and Last
  • Swap List Elements
  • Find List Length
  • Find Element in List
  • Clear a List
  • Reverse a List
  • Sum of List Elements
  • Product of List Elements
  • FInd Small in List
  • Find Largest in List
  • Find Second Largest
  • Find N Largest in List
  • Find Even in List
  • Find Odd in List
  • FInd All Even in List
  • All Positive in List
  • Negative in List
  • Remove Multiple From List
  • Clone a List
  • Find Occurrence in List
  • Remove Empty Tuple
  • Duplicate in List
  • Merge Dictionaries
  • Extract Unique From Dictionary
  • Sort Dictionary
  • Keys having multiple inputs
  • Sum of Dictionary Values
  • Remove Key from Dictionary
  • Insert at Start in Dictionary
  • Counting the frequencies
  • Add Space between Words
  • Python Program to
  • Python Program for
  • Rotate String
  • Palindrome String
  • Replace String Words
  • Duplicate String
  • Substring String
  • Binary String
  • Max Frequent Char
  • String Remove Char
  • Remove Duplicate
  • Count Words Frequency
  • Symmetrical String
  • Generating Random String
  • String Split and Join
  • Reverse String Words
  • Find Words using Chars
  • Special Chars
  • Find length of
  • Remove Char
  • String Char Order
  • Even String
  • Vowels in String
  • Count Matching Char
  • Remove Duplicates in String
  • Find Greater Words
  • Find URL in String
  • Pigeonhole Sort
  • BogoSort Algorithm
  • Stooge Sort
  • Heap Sort Program
  • Python program for Insertion sort
  • Join Tuples If Similar
  • Extract Digit from Tuples List
  • Pair Combinations of 2 tuples
  • Remove Tuples of Length K
  • Adding Tuple To List
  • Transpose Matrix
  • Matrix Multiplication
  • Matrix Add | Sub
  • Print G Pattern
  • Printed Inverted Star
  • Double-sided staircase Pattern
  • String Contains Specified Chars
  • Check if string start with same char
  • Count Uppercase Chars
  • Print Current Date
  • Find Dates of yesterday today tomorrow
  • Time 12 hours to 24 hours
  • Difference of Current Time and Given Time
  • Create Lap Timer
  • Binary search
  • Bubble Sort Program
  • create Circular Linked List of N nodes and count No. of node
  • Create Circular Link List of and display it in reverse order

Python Program to calculate area of a square

In this tutorial, we will learn how to do a simple program of calculating the area of a square in python. The area is defined as the total space a shape occupies. It is measured in square units like cm², m², km² depending on the unit of the dimensions. The formula for calculating the area of a square is given as

The formula for Area of Square

Area of a square= Side x Side

Area= Side²

For example, following as input and give the output accordingly.

Output- 6.25

Here are two simple methods for calculating and printing the area of a square where the measurement of a side is given by the user.

  • Using multiplication operator (*)
  • Using pow() function

Approach 1: Using multiplication operator (*)

Given below is a simple program for calculating area using the multiplication operator (*). The input is taken as float and the area is calculated up to 4 decimal places. We will use the "%.4f" specifier for getting 4 digits after the decimal point. In "%.4f" the number after the dot is used to indicate the decimal places and f specifies float.

Step 1 - Take input of side from user

Step 2 - Calculate area

Step 3 - Print area using "%.4f"

Python Program

Look at the program to understand the implementation of the above-mentioned approach.

Enter side of square3.2 Area of square= 10.2400

Approach 2: Using pow() function

pow() is a predefined math function in python which returns the value of x to the power y. To know more about pow() and other built-in math functions. I advise you to read the article on Python math function .

Step 1 - Define a function area_square() to calculate area Take input of side from user

Step 2 - Call pow() and set parameters as n ,2 to calculate the area

Step 3 - Take input from the user

Step 4 - Call area_square() and pass input as a parameter

Step 5- Print the area

assignment 2 room area cs python

Enter side of square2.4 Area of square= 5.7600

In this tutorial, we learned how to calculate the area of a square using 2 approaches. One, by using simple statements for multiplication and printing the output. Two, using a predefined math function called pow(). You can also define a function to calculate area by simply using the code from the first approach.

  • ← Python Convert Snake ← PREV
  • Add Two Numbers → NEXT →

C language

Lecture 4. Intro to Python

Monday April 4

Intro to Python

  • Video on canvas

📦 Code and Slides

  • 4-IntroPython.pdf
  • Lecture4-Python.zip

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons

Margin Size

  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

5.1: Floor division and modulus

  • Last updated
  • Save as PDF
  • Page ID 40878

  • Allen B. Downey
  • Olin College via Green Tea Press

\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

\( \newcommand{\Span}{\mathrm{span}}\)

\( \newcommand{\id}{\mathrm{id}}\)

\( \newcommand{\kernel}{\mathrm{null}\,}\)

\( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\)

\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\)

\( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

\( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vectorC}[1]{\textbf{#1}} \)

\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

The floor division operator, // , divides two numbers and rounds down to an integer. For example, suppose the run time of a movie is 105 minutes. You might want to know how long that is in hours. Conventional division returns a floating-point number:

But we don’t normally write hours with decimal points. Floor division returns the integer number of hours, rounding down:

To get the remainder, you could subtract off one hour in minutes:

An alternative is to use the modulus operator , % , which divides two numbers and returns the remainder.

The modulus operator is more useful than it seems. For example, you can check whether one number is divisible by another—if x % y is zero, then x is divisible by y .

Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.

If you are using Python 2, division works differently. The division operator, / , performs floor division if both operands are integers, and floating-point division if either operand is a float .

Interested in a verified certificate or a professional certificate ?

An introduction to programming using a language called Python. Learn how to read and write code as well as how to test and “debug” it. Designed for students with or without prior programming experience who’d like to learn Python specifically. Learn about functions, arguments, and return values (oh my!); variables and types; conditionals and Boolean expressions; and loops. Learn how to handle exceptions, find and fix bugs, and write unit tests; use third-party libraries; validate and extract data with regular expressions; model real-world entities with classes, objects, methods, and properties; and read and write files. Hands-on opportunities for lots of practice. Exercises inspired by real-world programming problems. No software required except for a web browser, or you can write code on your own PC or Mac.

Whereas CS50x itself focuses on computer science more generally as well as programming with C, Python, SQL, and JavaScript, this course, aka CS50P, is entirely focused on programming with Python. You can take CS50P before CS50x, during CS50x, or after CS50x. But for an introduction to computer science itself, you should still take CS50x!

How to Take this Course

Even if you are not a student at Harvard, you are welcome to “take” this course for free via this OpenCourseWare by working your way through the course’s ten weeks of material. If you’d like to submit the course’s problem sets and final project for feedback, be sure to create an edX account , if you haven’t already. Ask questions along the way via any of the course’s communities !

  • If interested in a verified certificate from edX , enroll at cs50.edx.org/python instead.
  • If interested in a professional certificate from edX , enroll at cs50.edx.org/programs/python (for Python) or cs50.edx.org/programs/data (for Data Science) instead.

How to Teach this Course

If you are a teacher, you are welcome to adopt or adapt these materials for your own course, per the license .

Python Revision Tour II

Class 12 - computer science with python sumita arora, multiple choice questions.

The numbered position of a letter in a string is called ...............

  • integer position

Reason — The index is the numbered position of a letter in the string.

The operator ............... tells if an element is present in a sequence or not.

Reason — in is membership operator which returns True if a character or a substring exists in the given string else returns False.

The keys of a dictionary must be of ............... types.

  • any of these

Reason — Dictionaries are indexed by keys and its keys must be of any immutable type.

Following set of commands is executed in shell, what will be the output?

Reason — str[:2] here slicing operation begins from index 0 and ends at index 1. Hence the output will be 'he'.

What data type is the object below ? L = [1, 23, 'hello', 1]

Reason — A list can store a sequence of values belonging to any data type and they are depicted through square brackets.

What data type is the object below ? L = 1, 23, 'hello', 1

Reason — For creating a tuple, enclosing the elements inside parentheses is optional. Even if parentheses are omitted as shown here, still this statement will create a tuple.

To store values in terms of key and value, what core data type does Python provide ?

Reason — Dictionaries are mutable with elements in the form of a key:value pair that associate keys to values.

What is the value of the following expression ? 3 + 3.00, 3**3.0

(6.0, 27.0)

  • (6.0, 9.00)
  • [6.0, 27.0]

Reason — The value of expression is in round brackets because it is tuple. 3 + 3.00 = 6.0 3**3.0 = 3 x 3 x 3 = 27.0

List AL is defined as follows : AL = [1, 2, 3, 4, 5] Which of the following statements removes the middle element 3 from it so that the list AL equals [1, 2, 4, 5] ?

  • AL[2:3] = []
  • AL[2:2] = []
  • AL.remove(3)

del AL[2] AL[2:3] = [] AL.remove(3)

Reason — del AL[2] — The del keyword deletes the element from the list AL from index 2. AL[2:3] = [] — The slicing of the list AL[2:3] begins at index 2 and ends at index 2. Therefore, the element at index 2 will be replaced by an empty list []. AL.remove(3) — The remove() function removes an element from the list AL from index 3."

Question 10

Which two lines of code are valid strings in Python ?

  • This is a string
  • 'This is a string'
  • (This is a string)
  • "This is a string"

'This is a string' "This is a string"

Reason — Strings are enclosed within single or double quotes.

Question 11

You have the following code segment :

What is the output of this code?

Reason — The + operator creates a new string by joining the two operand strings.

Question 12

Reason — string.upper() method returns a copy of the string converted to uppercase. The + operator creates a new string by joining the two operand strings.

Question 13

Which line of code produces an error ?

  • "one" + 'two'
  • "one" + "2"

Reason — The + operator has to have both operands of the same type either of number type (for addition) or of string type (for concatenation). It cannot work with one operand as string and one as a number.

Question 14

What is the output of this code ?

Reason — The + operator concatenates two strings and int converts it to integer type.

int("3" + "4") = int("34") = 34

Question 15

Which line of code will cause an error ?

Reason — Index 5 is out of range because list has 5 elements which counts to index 4.

Question 16

Which is the correct form of declaration of dictionary ?

Day = {1:'Monday', 2:'Tuesday', 3:'wednesday'}

  • Day = {1;'Monday', 2;'Tuesday', 3;'wednesday'}
  • Day = [1:'Monday', 2:'Tuesday', 3:'wednesday']
  • Day = {1'monday', 2'tuesday', 3'wednesday'}

Reason — The syntax of dictionary declaration is:

According this syntax, Day = {1:'Monday', 2:'Tuesday', 3:'wednesday'} is the correct answer.

Question 17

Identify the valid declaration of L:

L = ['Mon', '23', 'hello', '60.5']

Reason — A list can store a sequence of values belonging to any data type and enclosed in square brackets.

Question 18

Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is incorrect ?

  • print(T[1])
  • print(max(T))
  • print(len(T))

Reason — Tuples are immutable. Hence we cannot perform item-assignment in tuples.

Fill in the Blanks

Strings in Python store their individual letters in Memory in contiguous location.

Operator + when used with two strings, gives a concatenated string.

Operator + when used with a string and an integer gives an error.

Part of a string containing some contiguous characters from the string is called string slice .

The * operator when used with a list/string and an integer, replicates the list/string.

Tuples or Strings are not mutable while lists are.

Using list() function, you can make a true copy of a list.

The pop() function is used to remove an item from a list/dictionary.

The del statement can remove an individual item or a slice from a list.

The clear() function removes all the elements of a list/dictionary.

Creating a tuple from a set of values is called packing .

Creating individual values from a tuple's elements is called unpacking .

The keys() method returns all the keys in a dictionary.

The values() function returns all values from Key : value pair of a dictionary.

The items() function returns all the Key : value pairs as (key, value) sequences.

True/False Questions

Do both the following represent the same list. ['a', 'b', 'c'] ['c', 'a', 'b']

Reason — Lists are ordered sequences. In the above two lists, even though the elements are same, they are at different indexes (i.e., different order). Hence, they are two different lists.

A list may contain any type of objects except another list.

Reason — A list can store any data types and even list can contain another list as element.

There is no conceptual limit to the size of a list.

Reason — The list can be of any size.

All elements in a list must be of the same type.

Reason — A list is a standard data type of python that can store a sequence of values belonging to any data type.

A given object may appear in a list more than once.

Reason — List can have duplicate values.

The keys of a dictionary must be of immutable types.

Reason — Dictionaries are indexed by keys. Hence its keys must be of any non-mutable type.

You can combine a numeric value and a string by using the + symbol.

Reason — The + operator has to have both operands of the same type either of number type (for addition) or both of string type (for concatenation). It cannot work with one operand as string and one as a number.

The clear( ) removes all the elements of a dictionary but does not delete the empty dictionary.

Reason — The clear() method removes all items from the dictionary and the dictionary becomes empty dictionary post this method. del statement removes the complete dictionary as an object.

The max( ) and min( ) when used with tuples, can work if elements of the tuple are all of the same type.

Reason — Tuples should contain same type of elements for max() and min() method to work.

A list of characters is similar to a string type.

Reason — In Python, a list of characters and a string type are not similar. Strings are immutable sequences of characters, while lists are mutable sequences that can contain various data types. Lists have specific methods and behaviors that differ from strings, such as append(), extend(), pop() etc.

For any index n, s[:n] + s[n:] will give you original string s.

Reason — s[:n] — The slicing of a string starts from index 0 and ends at index n-1. s[n:] — The slicing of a string starts from index n and continues until the end of the string. So when we concatenate these two substrings we get original string s.

A dictionary can contain keys of any valid Python types.

Reason — The keys of a dictionary must be of immutable types.

Assertions and Reasons

Assertion. Lists and Tuples are similar sequence types of Python, yet they are two different data types.

Reason. List sequences are mutable and Tuple sequences are immutable.

Both Assertion and Reason are true and Reason is the correct explanation of Assertion.

Explanation Lists and tuples are similar sequence types in python, but they are distinct data types. Both are used to store collections of items, but they have different properties and use cases. Lists are mutable, meaning you can add, remove, or modify elements after the list is created. Tuples, on the other hand, are immutable, meaning once a tuple is created, its contents cannot be changed.

Assertion. Modifying a string creates another string internally but modifying a list does not create a new list.

Reason. Strings store characters while lists can store any type of data.

Both Assertion and Reason are true but Reason is not the correct explanation of Assertion.

Explanation In Python, strings are immutable, meaning once they are created, their contents cannot be changed. Whenever we modify a string, python creates a new string object to hold the modified contents, leaving the original string unchanged. On the other hand, lists in python are mutable, meaning we can modify their contents after they have been created. When we modify a list, python does not create a new list object. Instead, it modifies the existing list object in place. Strings are sequences of characters, and each character in a string can be accessed by its index. Lists, on the other hand, can store any type of data, including integers, floats, strings.

Reason. Strings are immutable types while lists are mutable types of python.

Explanation In Python, strings are immutable, meaning once they are created, their contents cannot be changed. Whenever we modify a string, python creates a new string object to hold the modified contents, leaving the original string unchanged. On the other hand, lists in python are mutable, meaning we can modify their contents after they have been created. When we modify a list, python does not create a new list object. Instead, it modifies the existing list object in place.

Assertion. Dictionaries are mutable, hence its keys can be easily changed.

Reason. Mutability means a value can be changed in place without having to create new storage for the changed value.

Assertion is false but Reason is true.

Explanation Dictionaries are indexed by keys and each key must be immutable and unique. However, the dictionary itself is mutable, meaning that we can add, remove, or modify key-value pairs within the dictionary without changing the identity of the dictionary object itself. Mutability refers to the ability to change a value in place without creating a new storage location for the changed value.

Assertion. Dictionaries are mutable but their keys are immutable.

Reason. The values of a dictionary can change but keys of dictionary cannot be changed because through them data is hashed.

Explanation A dictionary is a unordered set of key : value pairs and are indexed by keys. The values of a dictionary can change but keys of dictionary cannot be changed because through them data is hashed. Hence dictionaries are mutable but keys are immutable and unique.

Assertion. In Insertion Sort, a part of the array is always sorted.

Reason. In Insertion sort, each successive element is picked and inserted at an appropriate position in the sorted part of the array.

Explanation Insertion sort is a sorting algorithm that builds a sorted list, one element at a time from the unsorted list by inserting the element at its correct position in sorted list. In Insertion sort, each successive element is picked and inserted at an appropriate position in the previously sorted array.

Type A: Short Answer Questions/Conceptual Questions

What is the internal structure of python strings ?

Strings in python are stored as individual characters in contiguous memory locations, with two-way index for each location. The index (also called subscript) is the numbered position of a letter in the string. Indices begin 0 onwards in the forward direction up to length-1 and -1,-2, .... up to -length in the backward direction. This is called two-way indexing.

Write a python script that traverses through an input string and prints its characters in different lines - two characters per line.

Discuss the utility and significance of Lists, briefly.

A list is a standard data type of python that can store a sequence of values belonging to any type. Lists are mutable i.e., we can change elements of a list in place. Their dynamic nature allows for flexible manipulation, including appending, inserting, removing, and slicing elements. Lists offer significant utility in data storage, iteration, and manipulation tasks.

What do you understand by mutability ? What does "in place" task mean ?

Mutability means that the value of an object can be updated by directly changing the contents of the memory location where the object is stored. There is no need to create another copy of the object in a new memory location with the updated values. Examples of mutable objects in python include lists, dictionaries. In python, "in place" tasks refer to operations that modify an object directly without creating a new object or allocating additional memory. For example, list methods like append(), extend(), and pop() perform operations in place, modifying the original list, while string methods like replace() do not modify the original string in place but instead create a new string with the desired changes.

Start with the list [8, 9, 10]. Do the following using list functions:

  • Set the second entry (index 1) to 17
  • Add 4, 5 and 6 to the end of the list
  • Remove the first entry from the list
  • Sort the list
  • Double the list
  • Insert 25 at index 3

listA = [8, 9, 10]

  • listA[1] = 17
  • listA.extend([4, 5, 6])
  • listA.pop(0)
  • listA.sort()
  • listA = listA * 2
  • listA.insert(3, 25)

What's a[1 : 1] if a is a string of at least two characters ? And what if string is shorter ?

a[x:y] returns a slice of the sequence from index x to y - 1. So, a[1 : 1] will return an empty list irrespective of whether the list has two elements or less as a slice from index 1 to index 0 is an invalid range.

What are the two ways to add something to a list ? How are they different ?

The two methods to add something to a list are:

append method — The syntax of append method is list.append(item) .

extend method — The syntax of extend method is list.extend(<list>) .

The difference between the append() and extend() methods in python is that append() adds one element at the end of a list, while extend() can add multiple elements, given in the form of a list, to a list.

append method:

Output — [10, 12, 14, 16]

extend method:

Output — ['a', 'b', 'c', 'd', 'e']

What are the two ways to remove something from a list? How are they different ?

The two ways to remove something from a list are:

pop method — The syntax of pop method is List.pop(<index>) .

del statement — The syntax of del statement is

The difference between the pop() and del is that pop() method is used to remove single item from the list, not list slices whereas del statement is used to remove an individual item, or to remove all items identified by a slice.

pop() method:

Output — 'k'

del statement:

Output — [1, 2, 5]

What is the difference between a list and a tuple ?

In the Python shell, do the following :

  • Define a variable named states that is an empty list.
  • Add 'Delhi' to the list.
  • Now add 'Punjab' to the end of the list.
  • Define a variable states2 that is initialized with 'Rajasthan', 'Gujarat', and 'Kerala'.
  • Add 'Odisha' to the beginning of the list states2.
  • Add 'Tripura' so that it is the third state in the list states2.
  • Add 'Haryana' to the list states2 so that it appears before 'Gujarat'. Do this as if you DO NOT KNOW where 'Gujarat' is in the list. Hint. See what states2.index("Rajasthan") does. What can you conclude about what listname.index(item) does ?
  • Remove the 5th state from the list states2 and print that state's name.
  • states = []
  • states.append('Delhi')
  • states.append('Punjab')
  • states2 = ['Rajasthan', 'Gujarat', 'Kerala']
  • states2.insert(0,'Odisha')
  • states2.insert(2,'Tripura')
  • a = states2.index('Gujarat') states2.insert(a - 1,'Haryana')
  • b = states2.pop(4) print(b)

Discuss the utility and significance of Tuples, briefly.

Tuples are used to store multiple items in a single variable. It is a collection which is ordered and immutable i.e., the elements of the tuple can't be changed in place. Tuples are useful when values to be stored are constant and need to be accessed quickly.

If a is (1, 2, 3)

  • what is the difference (if any) between a * 3 and (a, a, a) ?
  • Is a * 3 equivalent to a + a + a ?
  • what is the meaning of a[1:1] ?
  • what is the difference between a[1:2] and a[1:1] ?
  • a * 3 ⇒ (1, 2, 3, 1, 2, 3, 1, 2, 3) (a, a, a) ⇒ ((1, 2, 3), (1, 2, 3), (1, 2, 3)) So, a * 3 repeats the elements of the tuple whereas (a, a, a) creates nested tuple.
  • Yes, both a * 3 and a + a + a will result in (1, 2, 3, 1, 2, 3, 1, 2, 3).
  • This colon indicates (:) simple slicing operator. Tuple slicing is basically used to obtain a range of items. tuple[Start : Stop] ⇒ returns the portion of the tuple from index Start to index Stop (excluding element at stop). a[1:1] ⇒ This will return empty list as a slice from index 1 to index 0 is an invalid range.
  • Both are creating tuple slice with elements falling between indexes start and stop. a[1:2] ⇒ (2,) It will return elements from index 1 to index 2 (excluding element at 2). a[1:1] ⇒ () a[1:1] specifies an invalid range as start and stop indexes are the same. Hence, it will return an empty list.

What is the difference between (30) and (30,) ?

a = (30) ⇒ It will be treated as an integer expression, hence a stores an integer 30, not a tuple. a = (30,) ⇒ It is considered as single element tuple since a comma is added after the element to convert it into a tuple.

Write a Python statement to declare a Dictionary named ClassRoll with Keys as 1, 2, 3 and corresponding values as 'Reena', 'Rakesh', 'Zareen' respectively.

Why is a dictionary termed as an unordered collection of objects ?

A dictionary is termed as an unordered collection of objects because the elements in a dictionary are not stored in any particular order. Unlike string, list and tuple, a dictionary is not a sequence. For a dictionary, the printed order of elements is not the same as the order in which the elements are stored.

What type of objects can be used as keys in dictionaries ?

Keys of a dictionary must be of immutable types such as

  • a Python string
  • a tuple (containing only immutable entries)

Though tuples are immutable type, yet they cannot always be used as keys in a dictionary. What is the condition to use tuples as a key in a dictionary ?

For a tuple to be used as a key in a dictionary, all its elements must be immutable as well. If a tuple contains mutable elements, such as lists, sets, or other dictionaries, it cannot be used as a key in a dictionary.

Dictionary is a mutable type, which means you can modify its contents ? What all is modifiable in a dictionary ? Can you modify the keys of a dictionary ?

Yes, we can modify the contents of a dictionary. Values of key-value pairs are modifiable in dictionary. New key-value pairs can also be added to an existing dictionary and existing key-value pairs can be removed. However, the keys of the dictionary cannot be changed. Instead we can add a new key : value pair with the desired key and delete the previous one. For example:

Explanation

d is a dictionary which contains one key-value pair. d[2] = 2 adds new key-value pair to d. d[1] = 3 modifies value of key 1 from 1 to 3. d[3] = 2 adds new key-value pair to d. del d[2] deletes the key 2 and its corresponding value.

Question 19

How is del D and del D[<key>] different from one another if D is a dictionary ?

del D deletes the entire dictionary D. After executing del D , the variable D is no longer defined, and any attempt to access D will result in a NameError . del D[<key>] deletes the key-value pair associated with the specified key from the dictionary D . After executing del D[<key>] , the dictionary D still exists, but the specified key and its corresponding value are removed from the dictionary.

For example:

Question 20

Create a dictionary named D with three entries, for keys 'a', 'b' and 'c'. What happens if you try to index a nonexistent key (D['d']) ? What does python do if you try to assign to a nonexistent key d. (e.g., D['d'] = 'spam') ?

  • In this example, the dictionary D does not contain the key 'd'. Therefore, attempting to access this key by D['d'] results in a KeyError because the key does not exist in the dictionary.
  • If we try to assign a value to a nonexistent key in a dictionary, python will create that key-value pair in the dictionary. In this example, the key 'd' did not previously exist in the dictionary D. When we attempted to assign the value 'spam' to the key 'd', python created a new key-value pair 'd': 'spam' in the dictionary D.

Question 21

What is sorting ? Name some popular sorting techniques.

Sorting refers to arranging elements of a sequence in a specific order — ascending or descending.

Sorting Techniques are as follows :

  • Bubble Sort
  • Insertion Sort
  • Selection Sort

Question 22

Discuss Bubble sort and Insertion sort techniques.

Bubble Sort : In Bubble sort, the adjoining values are compared and exchanged if they are not in proper order. This process is repeated until the entire array is sorted.

Insertion Sort : Insertion sort is a sorting algorithm that builds a sorted list one element at a time from the unsorted list by inserting the element at its correct position in sorted list.

Type B: Application Based Questions

Question 1(a).

What will be the output produced by following code fragments ?

str(123) converts the number 123 to string and stores in y so y becomes "123". "hello" * 3 repeats "hello" 3 times and stores it in x so x becomes "hellohellohello".

"hello" + "world" concatenates both the strings so x becomes "helloworld". As "helloworld" contains 10 characters so len(x) returns 10.

Question 1(b)

The code concatenates three strings "hello", "to Python", and "world" into the variable x . Then, it iterates over each character in x using a for loop. For each character, it assigns it to the variable y and prints y followed by a colon and space, all on the same line due to the end=" " parameter.

Question 1(c)

print(x[:2], x[:-2], x[-2:]) — x[:2] extracts the substring from the beginning of x up to index 1, resulting in "he". x[:-2] extracts the substring from the beginning of x up to the third last character, resulting in "hello wor". x[-2:] extracts the substring from the last two characters of x until the end, resulting in "ld". Hence, output of this line becomes he hello wor ld

print(x[6], x[2:4]) — x[6] retrieves the character at index 6, which is 'w'. x[2:4] extracts the substring from index 2 up to index 3, resulting in "ll". Hence, output of this line becomes w ll

print(x[2:-3], x[-4:-2]) — x[2:-3] extracts the substring from index 2 up to the fourth last character, resulting in "llo wo". x[-4:-2] extracts the substring from the fourth last character to the third last character, resulting in "or". Hence, output of this line becomes llo wo or

Write a short Python code segment that adds up the lengths of all the words in a list and then prints the average (mean) length.

  • The code prompts the user to enter a list of words and assigns it to the variable word_list .
  • We iterate over word_list using for loop. Inside the loop, length of each word gets added to total_length variable.
  • Average length is calculated by dividing total_length by the number of words in word_list .

Predict the output of the following code snippet ?

The slicing notation a[start:stop:step] extracts a portion of the list from index start to stop-1 with a specified step. In the slicing part a[3:0:-1] :

  • start is 3, which corresponds to the element with value 4.
  • stop is 0, but as element at stop index is excluded so slicing goes up to index 1.
  • step is -1, indicating that we want to step backward through the list.

Putting it together:

This extracts elements from index 3 to (0+1) in reverse order with a step of -1.

The output of the code will be:

Question 4(a)

Predict the output of the following code snippet?

  • arr is initialised as a list with elements [1, 2, 3, 4, 5, 6].
  • for loop iterates over the indices from 1 to 5. For each index i , it assigns the value of arr[i] to arr[i - 1] , effectively shifting each element one position to the left. After this loop, the list arr becomes [2, 3, 4, 5, 6, 6] .
  • Second for loop iterates over the indices from 0 to 5 and prints each element of the list arr without newline characters because of end="" parameter. Then it prints the elements of the modified list arr , resulting in 234566 .

Question 4(b)

  • Numbers is a list containing the numbers 9, 18, 27, and 36.
  • The outer for loop iterates over each element in the list Numbers .
  • The inner loop iterates over the range from 1 to the remainder of Num divided by 8. For example, if Num is 9, the range will be from 1 to 1 (9 % 8 = 1). If Num is 18, the range will be from 1 to 2 (18 % 8 = 2), and so on. Then it prints the value of N, followed by a "#", and ensures that the output is printed on the same line by setting end=" ".
  • After both loops, it prints an empty line, effectively adding a newline character to the output.

Question 5(a)

Find the errors. State reasons.

t[0] = 6 will raise a TypeError as tuples are immutable (i.e., their elements cannot be changed after creation).

Question 5(b)

There are no errors in this python code. Lists in python can contain elements of any type. As lists are mutable so t[0] = 6 is also valid.

Question 5(c)

t[4] = 6 will raise an error as we are trying to change the value at index 4 but it is outside the current range of the list t . As t has 3 elements so its indexes are 0, 1, 2 only.

Question 5(d)

t[0] = "H" will raise an error because strings in python are immutable, meaning we cannot change individual characters in a string after it has been created. Therefore, attempting to assign a new value to t[0] will result in an error.

Question 5(e)

The errors in this code are:

  • In the list [Amar, Shveta, Parag] , each element should be enclosed in quotes because they are strings.
  • The equality comparison operator is '==' instead of = for checking equality.
  • if statement should be lowercase.

Assuming words is a valid list of words, the program below tries to print the list in reverse. Does it have an error ? If so, why ? (Hint. There are two problems with the code.)

There are two issue in range(len(words), 0, -1) :

  • The start index len(words) is invalid for the list words as it will have indexes from 0 to len(words) - 1 .
  • The end index being 0 means that the last element of the list is missed as the list will be iterated till index 1 only.

The corrected python code is :

What would be the output of following code if ntpl = ("Hello", "Nita", "How's", "life ?") ?

ntpl is a tuple containing 4 elements. The statement (a, b, c, d) = ntpl unpacks the tuple ntpl into the variables a, b, c, d. After that, the values of the variables are printed.

The statement ntpl = (a, b, c, d) forms a tuple with values of variables a, b, c, d and assigns it to ntpl. As these variables were not modified, so effectively ntpl still contains the same values as in the first statement.

ntpl[0] ⇒ "Hello" ∴ ntpl[0][0] ⇒ "H"

ntpl[1] ⇒ "Nita" ∴ ntpl[1][1] ⇒"i"

ntpl[0][0] and ntpl[1][1] concatenates to form "Hi". Thus ntpl[0][0]+ntpl[1][1], ntpl[1] will return "Hi Nita ".

What will be the output of the following code ?

Tuples can be declared with or without parentheses (parentheses are optional). Here, tuple_a is declared without parentheses where as tuple_b is declared with parentheses but both are identical. As both the tuples contain same values so the equality operator ( == ) returns true.

What will be the output of the following code snippet ?

In the given python code snippet, id1 and id2 will point to two different objects in memory as del rec deleted the original dictionary whose id is stored in id1 and created a new dictionary with the same contents storing its id in id2 . However, id1 == id2 will compare the contents of the two dictionaries pointed to by id1 and id2 . As contents of both the dictionaries are same hence it returns True . If in this code we add another line print(id1 is id2) then this line will print False as id1 and id2 point to two different dictionary objects in memory.

Write the output of the code given below :

A dictionary my_dict with two key-value pairs, 'name': 'Aman' and 'age': 26 is initialized. Then updates the value associated with the key 'age' to 27. Then adds a new key-value pair 'address': 'Delhi' to the dictionary my_dict . The items() method returns all of the items in the dictionary as a sequence of (key, value) tuples. In this case, it will print [('name', 'Aman'), ('age', 27), ('address', 'Delhi')].

Write a method in python to display the elements of list thrice if it is a number and display the element terminated with '#' if it is not number.

For example, if the content of list is as follows :

The output should be 414141 DROND# GIRIRAJ# 131313 ZAR#

  • The code prompts the user to enter the elements of the list separated by spaces and stores the input as a single string in the variable my_list .
  • Then splits the input string my_list into individual elements and stores them in a new list called new_list .
  • Then for loop iterates over each element in the new_list.
  • The isdigit() method is used to check if all characters in the string are digits. If it's true (i.e., if the element consists only of digits), then it prints the element concatenated with itself three times. Otherwise, if the element contains non-digit characters, it prints the element concatenated with the character '#'.

Name the function/method required to

(i) check if a string contains only uppercase letters.

(ii) gives the total length of the list.

(i) isupper() method is used to check if a string contains only uppercase letters.

(ii) len() gives the total length of the list.

  • An empty dictionary named my_dict is initialized.
  • my_dict[(1,2,4)] = 8, my_dict[(4,2,1)] = 10, my_dict[(1,2)] = 12 these lines assign values to the dictionary my_dict with keys as tuples. Since tuples are immutable, so they can be used as keys in the dictionary.
  • The for loop iterates over the keys of the dictionary my_dict . Inside the loop, the value associated with each key k is added to the variable sum .
  • sum and my_dict are printed.

Type C: Programming Practice/Knowledge based Questions

Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after the area code and the next three numbers. For example, 017-555-1212 is a legal input. Display if the phone number entered is valid format or not and display if the phone number is valid or not (i.e., contains just the digits and dash at specific places).

Write a program that should prompt the user to type some sentence(s) followed by "enter". It should then print the original sentence(s) and the following statistics relating to the sentence(s):

  • Number of words
  • Number of characters (including white-space and punctuation)
  • Percentage of characters that are alpha numeric
  • Assume any consecutive sequence of non-blank characters in a word.

Write a program that takes any two lists L and M of the same size and adds their elements together to form a new list N whose elements are sums of the corresponding elements in L and M. For instance, if L = [3, 1, 4] and M = [1, 5, 9], then N should equal [4, 6, 13].

Write a program that rotates the elements of a list so that the element at the first index moves to the second index, the element in the second index moves to the third index, etc., and the element in the last index moves to the first index.

Write a short python code segment that prints the longest word in a list of words.

Write a program that creates a list of all the integers less than 100 that are multiples of 3 or 5.

Define two variables first and second so that first = "Jimmy" and second = "Johny". Write a short python code segment that swaps the values assigned to these two variables and prints the results.

Write a python program that creates a tuple storing first 9 terms of Fibonacci series.

Create a dictionary whose keys are month names and whose values are the number of days in the corresponding months.

(a) Ask the user to enter a month name and use the dictionary to tell them how many days are in the month.

(b) Print out all of the keys in alphabetical order.

(c) Print out all of the months with 31 days.

(d) Print out the (key-value) pairs sorted by the number of days in each month.

Write a function called addDict(dict1, dict2) which computes the union of two dictionaries. It should return a new dictionary, with all the items in both its arguments (assumed to be dictionaries). If the same key appears in both arguments, feel free to pick a value from either.

Write a program to sort a dictionary's keys using Bubble sort and produce the sorted keys as a list.

Write a program to sort a dictionary's values using Bubble sort and produce the sorted values as a list.

IMAGES

  1. Learn Python by Exercises #2: Area of a Room

    assignment 2 room area cs python

  2. Assignment 2: Room Area : r/projectstemanswer

    assignment 2 room area cs python

  3. Assignment 2: Room Area : r/projectstemanswer

    assignment 2 room area cs python

  4. Assignment 2 Room Area.docx

    assignment 2 room area cs python

  5. Assignment operators in python

    assignment 2 room area cs python

  6. How to find area of a triangle in Python

    assignment 2 room area cs python

VIDEO

  1. Final Day

  2. Assignment

  3. Meeting Rooms III

  4. Image Processing in Python with Scikits-image

  5. python program for area of rectangle

  6. Day 14

COMMENTS

  1. Answer in Python for Assignment 2: Room Area #96157

    Answer to Question #96157 in Python for Assignment 2: Room Area 2019-10-08T09:57:57-04:00. Answers > Programming & Computer Science > Python. Question #96157. For this lab you will find the area of an irregularly shaped room with the shape as shown above.

  2. Learn Python by Exercises #2: Area of a Room

    Learn Python by Exercises #2: Area of a RoomSubscribe to Our Channel: https://www.youtube.com/Life2Coding?s...-----Pl...

  3. assignment 2: room area programming python in Project Stem

    Click here 👆 to get an answer to your question ️ assignment 2: room area programming python in Project Stem ... assignment 2: room area CS python fundamentals project stem ...

  4. CS Python Fundamentals Unit 2 Test

    About Press Copyright Contact us Creators Advertise Developers Terms Privacy Policy & Safety How YouTube works Test new features NFL Sunday Ticket Press Copyright ...

  5. Answer in Python for Timothy #87539

    Assignment 2: Room Area Room shape For this lab you will find the area of an irregularly shaped room with the shape as shown above. ... Answer to Question #87539 in Python for Timothy 2019-04-04T06:28:50-04:00. Answers > Programming & Computer Science > Python. Question #87539.

  6. Beginner Python Area of a room

    My first recommendation is to check out the Python style guide, called pep8). Most Python developers stick to this, and it will make your life easier when trying to communicate with us. Next, you want to adjust your expectations. Trying to parse out a bunch of values from something like: Wall 1 3x4 Wall 2 5x9 Wall 3 9x9 Door 1 2x6.5 Door 2 2x6.5

  7. Answer in Python for kylie willis-bixby #95689

    For this lab you will find the area of an irregularly shaped room with the shape as shown above. A; 2. Write the code to input a number and print the square root. Use the absolute value function to make ; 3. Assignment 2: Room Area Room shape For this lab you will find the area of an irregularly shaped r; 4. Let's play Silly Sentences!

  8. Flashcards Assignment 2: Room Area

    Assignment 2: Room Area Quizlet has study tools to help you learn anything. Improve your grades and reach your goals with flashcards, practice tests and expert-written solutions today.

  9. Python Assignment 2

    1) Take an image.2) Mark the points with number ending your Roll ID (ex 2005).3) Save the coordinates in the excel file (Take 500 points).4) Find the distanc...

  10. 1.6. Variables and Assignment

    A variable is a name for a value. An assignment statement associates a variable name on the left of the equal sign with the value of an expression calculated from the right of the equal sign. Enter. width. Once a variable is assigned a value, the variable can be used in place of that value. The response to the expression width is the same as if ...

  11. Area Calculator

    Area Calculator. Write a program to calculate the area of four different geometric shapes: triangles, squares, rectangles, and circles. You must use functions. Here are the functions you should create: Name your file area_calculator.py. Your program should present a menu for the human to choose which shape to calculate, then ask them for the ...

  12. Assignment 2 Room Area.pdf

    View Assignment 2 Room Area.pdf from COMPUTER SCIENCE 593000 at Heritage High School. ! Intro to CS Term 1 (f9cf0d) Assignment 2: Room Area Assignment 2: Room Area SY

  13. MIT6_0001F16_Problem Set 1

    This resource contains information regarding introduction to computer science and programming in Python: Problem set. Resource Type: Assignments. pdf. 673 kB MIT6_0001F16_Problem Set 1 Download File DOWNLOAD. Course Info Instructors ... assignment_turned_in Programming Assignments with Examples. Download Course.

  14. Lecture 5

    You might write a function to calculate the area of a circle as. a ( r) = π r 2. In Python, typing into a file (in the upper pane of the Spyder IDE), we write. def area_circle(radius): pi = 3.14159 area = pi * radius**2 return area. Note that the def is not indented and the other lines are indented four spaces.

  15. Python Program to calculate area of a square

    Algorithm. Step 1 - Define a function area_square () to calculate area Take input of side from user. Step 2 - Call pow () and set parameters as n ,2 to calculate the area. Step 3 - Take input from the user. Step 4 - Call area_square () and pass input as a parameter. Step 5- Print the area.

  16. PDF Lecture 2: Variables & Assignments

    In More Detail: Variables (Section 2.1) • A variable § is a named memory location (box) § contains a value(in the box) • Examples: 21 x 5 Variable x, with value 5 (of type int) area 20.1 Variable area, w/ value 20.1 (of type float) Variable names must start with a letter (or _). The type belongs to the value, not to the variable.

  17. Assignment 2: room area CS python fundamentals project stem

    Find an answer to your question assignment 2: room area CS python fundamentals project stem

  18. PDF Lecture 2: Variables & Assignments

    Lecture 2: Variables & Assignments. (Sections 2.1-2.3,2.5, 2.6) and paper (or stylus and tablet) ready. We'll. Have pencil. do visualization exercises that involve drawing diagrams today. Recommendations for note taking: Print out posted lecture slides and write on them. Have the slides pdf ready and annotate electronically.

  19. CS106A Intro to Python

    2. 3/30 Control Flow 3. 4/1 Decomposition 4. 4/4 Intro to Python 5. 4/6 Arithmetic Expressions 6. 4/8 Control Flow Revisited 7. 4/11 Functions Revisited 8. 4/13 Parameters 9. 4/15 Lists 10. 4/18 Images 11. 4/20 Lists of Lists 12. 4/22 Wrapping Up Lists 13. 4/25 Canvas 14. 4/27 Strings 15. 4/29 Files 16. 5/2 Dictionaries 17. 5/4 Nested ...

  20. 5.1: Floor division and modulus

    This page titled 5.1: Floor division and modulus is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.

  21. Assignment 2: Room Area edhesive

    Assignment 2: Room Area edhesive - 12877899

  22. CS50's Introduction to Programming with Python

    An introduction to programming using a language called Python. Learn how to read and write code as well as how to test and "debug" it. Designed for students with or without prior programming experience who'd like to learn Python specifically. Learn about functions, arguments, and return values (oh my!); variables and types; conditionals ...

  23. Chapter 2: Python Revision Tour II

    Get answers to all exercises of Chapter 2: Python Revision Tour II Sumita Arora Computer Science with Python CBSE Class 12 book. Clear your computer doubts instantly & get more marks in computers exam easily. ... Hence we cannot perform item-assignment in tuples. Fill in the Blanks. ... with dashes after the area code and the next three numbers ...