• Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectivesā„¢ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How do you check whether a number is divisible by another number?

I need to test whether each number from 1 to 1000 is a multiple of 3 or a multiple of 5.

I tried this code in Python 2.x:

The idea is to try dividing the number and see if the result is an integer. However, I'm not getting the expected result.

How do I test whether the number is an integer?

In 2.x, division like this will produce an integer, discarding the remainder; see How can I force division to be floating point? Division keeps rounding down to 0? for details.

In 3.x, the division will produce a floating-point value; the result is not "an integer" even if it is a whole number , so the isinstance check will fail. See Why does integer division yield a float instead of another integer? for details.

If you need the remainder from integer division rather than just testing for divisibility, see Find the division remainder of a number .

Karl Knechtel's user avatar

  • 2 In Python 2.x, integer division always yields an integer. –  Russell Borogove Commented Nov 3, 2011 at 22:19
  • 27 You should be printing "Fizz" and "Buzz" –  wim Commented Nov 3, 2011 at 23:21
  • 13 Project Euler Problem 1 ? –  Ashutosh Dave Commented Jan 30, 2013 at 13:56
  • This is a special case of finding the remainder when doing integer division . –  Karl Knechtel Commented Oct 27, 2022 at 19:20

7 Answers 7

You do this using the modulus operator, %

evaluates true if and only if n is an exact multiple of k . In elementary maths this is known as the remainder from a division.

In your current approach you perform a division and the result will be either

  • always an integer if you use integer division, or
  • always a float if you use floating point division.

It's just the wrong way to go about testing divisibility.

David Heffernan's user avatar

  • 0 % 5 == 0 would be True as well, but zero is not exact multiple of zero. –  Fusion Commented Aug 9, 2017 at 12:41
  • 11 @Fusion 0 == 0*5 –  David Heffernan Commented Feb 20, 2018 at 23:37
  • @Chris_Rands Put that into an answer, people who do code-golf (like me) would be very happy. In fact, I came here looking for a golfed answer like that. –  MilkyWay90 Commented Nov 11, 2018 at 22:29

You can simply use % Modulus operator to check divisibility. For example: n % 2 == 0 means n is exactly divisible by 2 and n % 2 != 0 means n is not exactly divisible by 2.

Toby Allen's user avatar

You can use % operator to check divisiblity of a given number

The code to check whether given no. is divisible by 3 or 5 when no. less than 1000 is given below:

Cleb's user avatar

I had the same approach. Because I didn't understand how to use the module (%) operator.

  • This means if you divide 6 by 3 you will not have a remainder, 3 is a factor of 6.

Now you have to relate it to your given problem.

  • This is saying, if my number ( n ) is divisible by 3 leaving a 0 remainder.

Add your then (print, return) statement and continue your

wjandrea's user avatar

This code appears to do what you are asking for.

Or something like

Or any number of things.

Bennett Jester's user avatar

  • 1 Its better to explain the fix you have given and what made it worked –  chans Commented Oct 18, 2019 at 6:16
  • 1 That is NOT a good way to test divisibility: doing a float division, converting to a string and then doing string manipulations to find if the fractional part is (literally) ".0" is at the very least inefficient, and possibly wrong depending on the floating point implementation and the code that does the conversions. –  NickD Commented Oct 18, 2019 at 14:22
  • E.g. try x=10000000000000000; b = str(x/(x-1)); b in the python interpreter. –  NickD Commented Oct 18, 2019 at 15:08

For small numbers n%3 == 0 will be fine. For very large numbers I propose to calculate the cross sum first and then check if the cross sum is a multiple of 3:

honk's user avatar

  • 3 Is calculating the cross sum and using the modulus operation really faster than directly using the modulus operation? If so, shouldn't you call your function recursively until the number is "small" enough? –  honk Commented Aug 9, 2014 at 6:43
  • This is in fact extremely inefficient - so inefficient that by default, recent Python versions will outright refuse to perform the operation for large inputs, as large string/int conversion is considered a vector for denial of service attacks. By default, the str call will raise a ValueError for inputs where the result would be longer than 4300 decimal digits. –  user2357112 Commented Feb 27 at 22:01

Not the answer you're looking for? Browse other questions tagged python integer modulo or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Tag hover experiment wrap-up and next steps
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • A post-apocalyptic short story where very sick people from our future save people in our timeline that would be killed in plane crashes
  • Repeats: Simpler at the cost of more redundant?
  • Does the First Amendment protect deliberately publicizing the incorrect date for an election?
  • Car LED circuit
  • With 42 supernovae in 37 galaxies, how do we know SH0ES results is robust?
  • Which direction is the rolling shutter on a Canon 5D?
  • Base change in Chriss-Ginzburg
  • collcell and \IfBlankTF comparison not working
  • Output of a Diffractometer
  • "Heads cut off" or "souls cut off" in Rev 20:4?
  • How come I was allowed to bring 1.5 liters of liquid through security at Frankfurt Airport?
  • How predictable are the voting records of members of the US legislative branch?
  • Fisher claims Σ(x - λ)²/λ is chi-squared when x is Poisson – how is that?
  • Why would Space Colonies even want to secede?
  • Relation between specific heats for a magnetic system
  • Questions about best way to raise the handlebar on my bike
  • Erase the loops
  • Did the Space Shuttle weigh itself before deorbit?
  • Would donations count as revenue from a free software?
  • Finding the maximum squared distance between a pair of coordinates from a set of coordinates
  • Dual UK/CAN national travelling from UK to Canada and back - which passport should I use to book tickets?
  • Three 7-letter words, 21 unique letters, excludes either HM or QS
  • How to handle stealth before combat starts?
  • Why would luck magic become obsolete in the modern era?

cs python fundamentals assignment 4 divisible by three

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Check if number is divisible by three and two

Looks next nested if a little structure redundancy? Any better way for next nested if?

Peilonrayz's user avatar

  • 1 \$\begingroup\$ Do you need to check one specific number, or are you checking some consecutive numbers in sequence? \$\endgroup\$ –  Reinderien Commented Jul 17, 2020 at 22:16

Instead of checking for division by 2 and 3 separately twice, you can make use of the fact that:

$$ 2 * 3 = 6$$

python pep8 suggests to use 4-whitespace nesting as indentation levels.

Use 4 spaces per indentation level.

If you have more numbers to check divisibility against, keep a set of the numbers for which num % x == 0 , and print the factors at the end.

hjpotter92's user avatar

  • \$\begingroup\$ Is it intentional that some of the print statements are indented 6 spaces in instead of 4 spaces? \$\endgroup\$ –  Simply Beautiful Art Commented Jul 17, 2020 at 21:27
  • 1 \$\begingroup\$ @SimplyBeautifulArt my mistake. fixed \$\endgroup\$ –  hjpotter92 Commented Jul 17, 2020 at 21:52
  • \$\begingroup\$ The disadvantage of this approach is its worst-case performance, if we consider modulation to be costly. If there are many "divisible by neither 2 nor 3" cases, then there will be many triple-modulations, whereas the approach of putting mod-2 and mod-3 results in boolean variables will only ever have worst-case two modulations. \$\endgroup\$ –  Reinderien Commented Jul 17, 2020 at 22:00
  • \$\begingroup\$ @Reinderien I don't think modulo operations are that costly. \$\endgroup\$ –  hjpotter92 Commented Jul 17, 2020 at 22:06
  • \$\begingroup\$ Depends on whether you're running on a microcontroller :) Also, this is a classic interview question. It's entirely possible for the interviewers to add that stipulation. \$\endgroup\$ –  Reinderien Commented Jul 17, 2020 at 22:08

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking ā€œPost Your Answerā€, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python python-3.x or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Why did evolution fail to protect humans against sun?
  • What's wrong with my app authentication scheme?
  • Why does editing '/etc/shells' file using 'sudo open' shows an error saying I don't own the file?
  • What was Bertrand Russell's take on the resolution of Russell's paradox?
  • What role does the lower bound play in the statement of Savitch's Theorem?
  • Three 7-letter words, 21 unique letters, excludes either HM or QS
  • Making wobbly 6x4’ table stable
  • Is the Ted-Ed Leprechaun's Magic Bag Unique?
  • Base change in Chriss-Ginzburg
  • "Heads cut off" or "souls cut off" in Rev 20:4?
  • What is a word/phrase that best describes a "blatant disregard or neglect" for something, but with the connotation of that they should have known?
  • Would donations count as revenue from a free software?
  • Fisher claims Σ(x - λ)²/λ is chi-squared when x is Poisson – how is that?
  • If there is no free will, doesn't that provide a framework for an ethical model?
  • How can I cross an overpass in "Street View" without being dropped to the roadway below?
  • I submitted a paper and later realised one reference was missing, although I had written the authors in the body text. What could happen?
  • What does it mean to have a truth value of a 'nothing' type instance?
  • Why would Space Colonies even want to secede?
  • Can a Statute of Limitations claim be rejected by the court?
  • Car LED circuit
  • Will the US Customs be suspicious of my luggage if i bought a lot of the same item?
  • How to create a extruded 4-star shape that is rotated inwards?
  • Guitar amplifier placement for live band
  • Cover letter format in Germany

cs python fundamentals assignment 4 divisible by three

Divisible by 3

Define a function named div_3 that returns True if its single integer parameter is divisible by 3 and False otherwise.

For example, div_3(6) is True because 6/3 does not leave any remainder. However div_3(5) is False because 5/3 leaves 2 as a remainder.

Lesson completed

Congratulations! You have finished the lesson "Divisible by 3".

Leave Feedback

This helps tailor the lessons to you.

Lesson difficulty:
Lesson pace:

Keep learning

Wrong submission.

Your submission was not accepted. Here is an explanation:

If you are stuck you can get help or get a hint .

Try reading our post on getting unstuck . It lists techniques that typically help our learners.

This slide has a hint. View hint .

Get personal help

Discord is an online chat application. We hang out there and are happy to help you. Here is an invite:

Join Python Principles Discord

Force solve

If you remain stuck, you can click the button below to "force solve" the current slide. Avoid this if possible, because it stunts your learning.

Congratulations!

Your solution was correct! You have now completed this challenge. More challenges Show example solutions

Example solution

You solved the exercise. Sometimes we can learn a lot from seeing other people's code and different ways to solve an exercise.

Here is an example of how the exercise can be solved:

Decode School

Divisible by 3 or not in python

Python Program to get a number num and check whether num is divisible by 3.

Sample Input 1:

Sample Output 1:

Divisible by 3

Sample Input 2:

Sample Output 2:

Not divisible by 3

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

Program or Solution

Program explanation.

Get input num from user using input() method check whether the remainder of num divided by 3 is equal to 0 using if statement.

if it is 0, then print num is divisible by 3 using print() method.

Else print num is not divisible by 3 using print() method.

Related Programs

  • Python if example
  • Greatest of two numbers in Python
  • Smallest of two numbers in python
  • ODD or Even in Python
  • 3 digit number or not in python
  • Greatest of three numbers in Python
  • Smallest of three numbers in Python
  • Leap year in python
  • Last digit divisible by 3 or not in python
  • Calculator in python
  • grade calculation in python
  • else if in python
  • check whether bit is set in python
  • odd or even using bitwise operator in python

Email ID for Digital Training

Decode school.

Dexar Code School or shortly Decode School is a platform to learn Programs and foundations of Comptuter Science. It enables a 360 ° and depth learning through examples and excercises.

Beginner Links

  • Guessing Game Programs
  • Pattern Programs
  • Number Pattern Programs
  • Logic Building in C
  • Logic Building in Python
  • Python Programming Examples
  • C Programming Examples
  • Java Programming Examples

© Copyright 2017-DEXAR CODE SCHOOL. Design by: uiCookies

DECODE SCHOOL

  • C Programming
  • Python Programming
  • Java Programming
  • Python Logic Building
  • Problem Solving using Java
  • Text Mining
  • Python Tutorial
  • OOPS in Java
  • Database Management
  • Operating Systems

Session Detail

Cookie CSRF:
Cookie Leetcode Session:
  • How to Think Like a Computer Scientist: Learning with Python 2nd Edition documentation »
  • 4. Conditionals

4. Conditionals Ā¶

4.1. the modulus operator Ā¶.

The modulus operator works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second. In Python, the modulus operator is a percent sign ( % ). The syntax is the same as for other operators:

So 7 divided by 3 is 2 with 1 left over.

The modulus operator turns out to be surprisingly useful. 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.

4.2. Boolean values and expressions Ā¶

The Python type for storing true and false values is called bool , named after the British mathematician, George Boole. George Boole created Boolean algebra , which is the basis of all modern computer arithmetic.

There are only two boolean values : True and False . Capitalization is important, since true and false are not boolean values.

A boolean expression is an expression that evaluates to a boolean value. The operator == compares two values and produces a boolean value:

In the first statement, the two operands are equal, so the expression evaluates to True ; in the second statement, 5 is not equal to 6, so we get False .

The == operator is one of the comparison operators ; the others are:

Although these operations are probably familiar to you, the Python symbols are different from the mathematical symbols. A common error is to use a single equal sign ( = ) instead of a double equal sign ( == ). Remember that = is an assignment operator and == is a comparison operator. Also, there is no such thing as =< or => .

4.3. Logical operators Ā¶

There are three logical operators : and , or , and not . The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10.

n % 2 == 0 or n % 3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3.

Finally, the not operator negates a boolean expression, so not(x > y) is true if (x > y) is false, that is, if x is less than or equal to y .

4.4. Conditional execution Ā¶

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the ** if statement**:

(See the String formatting section in the Strings chapter for more information.)

The boolean expression after the if statement is called the condition . If it is true, then the indented statement gets executed. If not, nothing happens.

The syntax for an if statement looks like this:

As with the function definition we have already seen, the if statement consists of a header and a body. The header begins with the keyword if followed by a boolean expression and ends with a colon (:).

The indented statements that follow are called a block . The first unindented statement marks the end of the block. A statement block inside a compound statement is called the body of the statement.

Each of the statements inside the body are executed in order if the boolean expression evaluates to True . The entire block is skipped if the boolean expression evaluates to False .

There is no limit on the number of statements that can appear in the body of an if statement, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you havenā€™t written yet). In that case, you can use the pass statement, which does nothing.

4.5. Alternative execution Ā¶

A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this:

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will be executed. The alternatives are called branches , because they are branches in the flow of execution.

As an aside, if you need to check the parity (evenness or oddness) of numbers often, you might wrap this code in a function :

For any value of x , print_parity displays an appropriate message. When you call it, you can provide any integer expression as an argument.

4.6. Chained conditionals Ā¶

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional :

elif is an abbreviation of else if . Again, exactly one branch will be executed. There is no limit of the number of elif statements but only a single (and optional) else statement is allowed and it must be the last branch in the statement:

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

4.7. Nested conditionals Ā¶

One conditional can also be nested within another. We could have written the trichotomy example as follows:

The outer conditional contains two branches. The first branch contains a simple output statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both output statements, although they could have been conditional statements as well.

Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. In general, it is a good idea to avoid them when you can.

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:

The print statement is executed only if we make it past both the conditionals, so we can use the and operator:

These kinds of conditions are common, so Python provides an alternative syntax that is similar to mathematical notation:

This condition is semantically the same as the compound boolean expression and the nested conditional.

4.8. The return statement Ā¶

The return statement allows you to terminate the execution of a function before you reach the end. One reason to use it is if you detect an error condition:

The function print_square_root has a parameter named x . The first thing it does is check whether x is less than or equal to 0, in which case it displays an error message and then uses return to exit the function. The flow of execution immediately returns to the caller, and the remaining lines of the function are not executed.

4.9. Keyboard input Ā¶

In Input we were introduced to Pythonā€™s built-in function that gets input from the keyboard: input() . Letā€™s look at this again in greater depth.

When input() is called, the program stops and waits for the user to type something. When the user presses Return or the Enter key, the program resumes and input() returns what the user typed as a string :

It is always a good idea to tell the user what to input. We can supply a prompt as a single argument to input() :

Notice that the prompt is a string, so it must be enclosed in quotation marks.

If we expect the user response to be an integer or a float, we can still call input() , and then use conversion functions to convert what input() returns to other types.

4.10. Type conversion Ā¶

Each Python type comes with a built-in command that attempts to convert values of another type into that type. The int(ARGUMENT) command, for example, takes any value and converts it to an integer, if possible, or complains otherwise:

int can also convert floating-point values to integers, but remember that it truncates the fractional part:

The float(ARGUMENT) command converts integers and strings to floating-point numbers:

It may seem odd that Python distinguishes the integer value 1 from the floating-point value 1.0 . They may represent the same number, but they belong to different types. The reason is that they are represented differently inside the computer.

The str(ARGUMENT) command converts any argument given to it to type string :

str(ARGUMENT) will work with any value and convert it into a string. As mentioned earlier, True is boolean value; true is not.

For boolean values, the situation is especially interesting:

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.

NOTE: calling one of these conversion functions on data stored in a variable does not change whatā€™s stored in the variable! It takes what is stored in the variable and converts it, but does not automatically reassign the result back to the variable:

If you want x to contain the float 3.14159, you can convert it and reassign it like this:

4.11. Graphics Ā¶

We will be using a modified version of a graphics package provided by John Zelle ( http://mcsp.wartburg.edu/zelle/python/ ) as part of his Python Programming textbook. Although we are not using his textbook, we can still use the graphics package. The graphics package installed on all of the CS Department lab machines. To run it on your own computer, you will need to copy it from the lab machines onto your computer. Ask a CS professor for help with this if you need it.

Try the following python python:

The second to the last command pauses and waits until you click the mouse in the graphics window. Without it, the screen would flash by so quickly you wouldnā€™t see it.

Running this python, you should see a graphics window that looks like this:

graphics illustration 1

We will be using the graphics library from here on to illustrate (pun intended) computer programming concepts and to add to our fun while learning. You can find out more about the graphics module by reading Appendix B .

4.12. Glossary Ā¶

A group of consecutive statements with the same indentation.

The block of statements in a compound statement that follows the header.

An expression that is either true or false.

There are exactly two boolean values: True and False . Boolean values result when a boolean expression is evaluated by the Python interepreter. They have type bool .

One of the possible paths of the flow of execution determined by conditional execution.

A conditional branch with more than two possible flows of execution. In Python chained conditionals are written with if ... elif ... else statements.

One of the operators that compares two values: == , != , > , < , >= , and <= .

The boolean expression in a conditional statement that determines which branch is executed.

A statement that controls the flow of execution depending on some condition. In Python the keywords if , elif , and else are used for conditional statements.

One of the operators that combines boolean expressions: and , or , and not .

An operator, denoted with a percent sign ( % ), that works on integers and yields the remainder when one number is divided by another.

One program structure within another, such as a conditional statement inside a branch of another conditional statement.

A visual cue that tells the user to input data.

An explicit statement that takes a value of one type and computes a corresponding value of another type.

The process of adding a function header and parameters to a sequence of program statements is often refered to as ā€œwrapping the code in a functionā€. This process is very useful whenever the program statements in question are going to be used multiple times.

4.13. Exercises Ā¶

Try to evaluate the following numerical expressions in your head, then use the Python interpreter to check your results:

>>> 5 % 2 >>> 9 % 5 >>> 15 % 12 >>> 12 % 15 >>> 6 % 6 >>> 0 % 7 >>> 7 % 0

What happened with the last example? Why? If you were able to correctly anticipate the computerā€™s response in all but the last one, it is time to move on. If not, take time now to make up examples of your own. Explore the modulus operator until you are confident you understand how it works.

Wrap this code in a function called compare(x, y) . Call compare three times: one each where the first argument is less than, greater than, and equal to the second argument.

To better understand boolean expressions, it is helpful to construct truth tables. Two boolean expressions are logically equivalent if and only if they have the same truth table.

The following Python program prints out the truth table for any boolean expression in two variables: p and q:

You will learn how this program works in later chapters. For now, you will use it to learn about boolean expressions. Copy this program to a file named p_and_q.py , then run it from the command line and give it: p or q , when prompted for a boolean expression. You should get the following output:

Now that we see how it works, letā€™s wrap it in a function to make it easier to use:

We can import it into a Python shell and call truth_table with a string containing our boolean expression in p and q as an argument:

Use the truth_table functions with the following boolean expressions, recording the truth table produced each time:

not(p or q) p and q not(p and q) not(p) or not(q) not(p) and not(q)

Which of these are logically equivalent?

Enter the following expressions into the Python shell:

Analyze these results. What observations can you make about values of different types and logical operators? Can you write these observations in the form of simple rules about and and or expressions?

Wrap this code in a function called dispatch(choice) . Then define function_a , function_b , and function_c so that they print out a message saying they were called. For example:

Put the four functions ( dispatch , function_a , function_b , and function_c into a program named ch04e05.py . At the bottom of this program add a call to dispatch('b') . Your output should be:

Finally, modify the program so that user can enter ā€˜aā€™, ā€˜bā€™, or ā€˜cā€™. Test it by importing your program into the Python shell.

Write a function named is_divisible_by_3 that takes a single integer as an argument and prints ā€œThis number is divisible by three.ā€ if the argument is evenly divisible by 3 and ā€œThis number is not divisible by three.ā€ otherwise.

Now write a similar function named is_divisible_by_5 .

Generalize the functions you wrote in the previous exercise into a function named is_divisible_by_n(x, n) that takes two integer arguments and prints out whether the first is divisible by the second. Save this in a file named ch04e07.py . Import it into a shell and try it out. A sample session might look like this:

What will be the output of the following?

Explain what happened and why it happened.

Save the following in a file named house.py . This draws a simple house on a graphics window.

Run this program and confirm that you get a window that looks like this:

GASP illustration 2

Wrap the house code in a function named draw_house() .

Run the program now. Do you see a house? Why not?

Add a call to draw_house() at the botton of the program so that the house returns to the screen.

Parameterize the function with x and y parameters ā€“ the header should then become def draw_house(x, y): , so that you can pass in the location of the house on the canvas.

Use draw_house to place five houses on the canvas in different locations.

Exploration: Read over Appendix B and write a program named houses.py that produces the following when run:

GASP illustration 3

hint : You will need to use a Polygon for the roof instead of two Line s in order to fill the roof with a color.

  • How to Think Like a Computer Scientist: Learning with Python 2nd Edition documentation »

4. Conditionals Ā¶

4.1. the modulus operator Ā¶.

The modulus operator works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second. In Python, the modulus operator is a percent sign ( % ). The syntax is the same as for other operators:

So 7 divided by 3 is 2 with 1 left over.

The modulus operator turns out to be surprisingly useful. 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.

4.2. Boolean values and expressions Ā¶

The Python type for storing true and false values is called bool , named after the British mathematician, George Boole. George Boole created Boolean algebra , which is the basis of all modern computer arithmetic.

There are only two boolean values : True and False . Capitalization is important, since true and false are not boolean values.

A boolean expression is an expression that evaluates to a boolean value. The operator == compares two values and produces a boolean value:

In the first statement, the two operands are equal, so the expression evaluates to True ; in the second statement, 5 is not equal to 6, so we get False .

The == operator is one of the comparison operators ; the others are:

Although these operations are probably familiar to you, the Python symbols are different from the mathematical symbols. A common error is to use a single equal sign ( = ) instead of a double equal sign ( == ). Remember that = is an assignment operator and == is a comparison operator. Also, there is no such thing as =< or => .

4.3. Logical operators Ā¶

There are three logical operators : and , or , and not . The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10.

n % 2 == 0 or n % 3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3.

Finally, the not operator negates a boolean expression, so not(x > y) is true if (x > y) is false, that is, if x is less than or equal to y .

4.4. Conditional execution Ā¶

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the ** if statement**:

The boolean expression after the if statement is called the condition . If it is true, then the indented statement gets executed. If not, nothing happens.

The syntax for an if statement looks like this:

As with the function definition from last chapter and other compound statements, the if statement consists of a header and a body. The header begins with the keyword if followed by a boolean expression and ends with a colon (:).

The indented statements that follow are called a block . The first unindented statement marks the end of the block. A statement block inside a compound statement is called the body of the statement.

Each of the statements inside the body are executed in order if the boolean expression evaluates to True . The entire block is skipped if the boolean expression evaluates to False .

There is no limit on the number of statements that can appear in the body of an if statement, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.

4.5. Alternative execution Ā¶

A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this:

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will be executed. The alternatives are called branches , because they are branches in the flow of execution.

As an aside, if you need to check the parity (evenness or oddness) of numbers often, you might wrap this code in a function :

For any value of x , print_parity displays an appropriate message. When you call it, you can provide any integer expression as an argument.

4.6. Chained conditionals Ā¶

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional :

elif is an abbreviation of else if . Again, exactly one branch will be executed. There is no limit of the number of elif statements but only a single (and optional) else statement is allowed and it must be the last branch in the statement:

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

4.7. Nested conditionals Ā¶

One conditional can also be nested within another. We could have written the trichotomy example as follows:

The outer conditional contains two branches. The first branch contains a simple output statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both output statements, although they could have been conditional statements as well.

Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. In general, it is a good idea to avoid them when you can.

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:

The print statement is executed only if we make it past both the conditionals, so we can use the and operator:

These kinds of conditions are common, so Python provides an alternative syntax that is similar to mathematical notation:

This condition is semantically the same as the compound boolean expression and the nested conditional.

4.8. The return statement Ā¶

The return statement allows you to terminate the execution of a function before you reach the end. One reason to use it is if you detect an error condition:

The function print_square_root has a parameter named x . The first thing it does is check whether x is less than or equal to 0, in which case it displays an error message and then uses return to exit the function. The flow of execution immediately returns to the caller, and the remaining lines of the function are not executed.

4.9. Keyboard input Ā¶

In Input we were introduced to Python’s built-in functions that get input from the keyboard: raw_input and input . Now let’s look at these again in greater depth.

When either of these functions are called, the program stops and waits for the user to type something. When the user presses Return or the Enter key, the program resumes and raw_input returns what the user typed as a string :

Before calling raw_input , it is a good idea to print a message telling the user what to input. This message is called a prompt . We can supply a prompt as an argument to raw_input :

Notice that the prompt is a string, so it must be enclosed in quotation marks.

If we expect the response to be an integer, we can use the input function which evaluates the response as a Python expression:

If the user types a string of digits, it is converted to an integer and assigned to speed . Unfortunately, if the user types characters that do not make up a valid Python expression, the program crashes:

In the last example, if the user had made the response a valid Python expression by putting quotes around it, it would not have given an error:

To avoid this kind of error, it is a good idea to use raw_input to get a string and then use conversion commands to convert it to other types.

4.10. Type conversion Ā¶

Each Python type comes with a built-in command that attempts to convert values of another type into that type. The int(ARGUMENT) command, for example, takes any value and converts it to an integer, if possible, or complains otherwise:

int can also convert floating-point values to integers, but remember that it truncates the fractional part:

The float(ARGUMENT) command converts integers and strings to floating-point numbers:

It may seem odd that Python distinguishes the integer value 1 from the floating-point value 1.0 . They may represent the same number, but they belong to different types. The reason is that they are represented differently inside the computer.

The str(ARGUMENT) command converts any argument given to it to type string :

str(ARGUMENT) will work with any value and convert it into a string. As mentioned earlier, True is boolean value; true is not.

For boolean values, the situation is especially interesting:

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.

4.11. GASP Ā¶

GASP ( G raphics A PI for S tudents of P ython) will enable us to write programs involving graphics. Before you can use GASP, it needs to be installed on your machine. If you are running Ubuntu GNU/Linux, see GASP in Appendix A . Current instructions for installing GASP on other platforms can be found at http://dev.laptop.org/pub/gasp/downloads .

After installing gasp, try the following python script:

The second to the last command pauses and waits until a key is pressed. Without it, the screen would flash by so quickly you wouldn’t see it.

Running this script, you should see a graphics window that looks like this:

GASP illustration 1

We will be using gasp from here on to illustrate (pun intended) computer programming concepts and to add to our fun while learning. You can find out more about the GASP module by reading Appendix B .

4.12. Glossary Ā¶

4.13. exercises Ā¶.

Try to evaluate the following numerical expressions in your head, then use the Python interpreter to check your results:

>>> 5 % 2 >>> 9 % 5 >>> 15 % 12 >>> 12 % 15 >>> 6 % 6 >>> 0 % 7 >>> 7 % 0

What happened with the last example? Why? If you were able to correctly anticipate the computer’s response in all but the last one, it is time to move on. If not, take time now to make up examples of your own. Explore the modulus operator until you are confident you understand how it works.

Wrap this code in a function called compare(x, y) . Call compare three times: one each where the first argument is less than, greater than, and equal to the second argument.

To better understand boolean expressions, it is helpful to construct truth tables. Two boolean expressions are logically equivalent if and only if they have the same truth table.

The following Python script prints out the truth table for any boolean expression in two variables: p and q:

You will learn how this script works in later chapters. For now, you will use it to learn about boolean expressions. Copy this program to a file named p_and_q.py , then run it from the command line and give it: p or q , when prompted for a boolean expression. You should get the following output:

Now that we see how it works, let’s wrap it in a function to make it easier to use:

We can import it into a Python shell and call truth_table with a string containing our boolean expression in p and q as an argument:

Use the truth_table functions with the following boolean expressions, recording the truth table produced each time:

not(p or q) p and q not(p and q) not(p) or not(q) not(p) and not(q)

Which of these are logically equivalent?

Enter the following expressions into the Python shell:

Analyze these results. What observations can you make about values of different types and logical operators? Can you write these observations in the form of simple rules about and and or expressions?

Wrap this code in a function called dispatch(choice) . Then define function_a , function_b , and function_c so that they print out a message saying they were called. For example:

Put the four functions ( dispatch , function_a , function_b , and function_c into a script named ch04e05.py . At the bottom of this script add a call to dispatch('b') . Your output should be:

Finally, modify the script so that user can enter ‘a’, ‘b’, or ‘c’. Test it by importing your script into the Python shell.

Write a function named is_divisible_by_3 that takes a single integer as an argument and prints “This number is divisible by three.” if the argument is evenly divisible by 3 and “This number is not divisible by three.” otherwise.

Now write a similar function named is_divisible_by_5 .

Generalize the functions you wrote in the previous exercise into a function named is_divisible_by_n(x, n) that takes two integer arguments and prints out whether the first is divisible by the second. Save this in a file named ch04e07.py . Import it into a shell and try it out. A sample session might look like this:

What will be the output of the following?

Explain what happened and why it happened.

The following gasp script, in a file named house.py , draws a simple house on a gasp canvas:

Run this script and confirm that you get a window that looks like this:

GASP illustration 2

  • Wrap the house code in a function named draw_house() .
  • Run the script now. Do you see a house? Why not?
  • Add a call to draw_house() at the botton of the script so that the house returns to the screen.
  • Parameterize the function with x and y parameters – the header should then become def draw_house(x, y): , so that you can pass in the location of the house on the canvas.
  • Use draw_house to place five houses on the canvas in different locations.

Exploration: Read over Appendix B and write a script named houses.py that produces the following when run:

GASP illustration 3

hint : You will need to use a Polygon for the roof instead of two Line s to get filled=True to work with it.

  • DSA Tutorial
  • Data Structures
  • Linked List
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Divide & Conquer
  • Mathematical
  • Backtracking
  • Branch and Bound
  • Pattern Searching

Count of different numbers divisible by 3 that can be obtained by changing at most one digit

Given a string str representing a number having N digits, the task is to calculate the number of ways to make the given number divisible by 3 by changing at most one digit of the number.

Input: str[] = “23” Output: 7 Explanation: Below are the numbers that can be made from the string which are divisible by 3 – 03, 21, 24, 27, 33, 63, 93 1.Change 2 to 0 (0+3)=3 divisible by 3 2.Change 3 to 1 (2+1)=3 divisible by 3 3 change 3 to 4 (2+4)=6 divisible by 3 4 change 2 to 3 sum is 6 divisible by 3 Similarly there are total 7 number of ways to make the given number divisible by 3 Input: str[] = “235” Output: 9

Approach: The idea is very simple to solve this problem. Calculate the sum of digits of a given number and then for each index, remove that digit and try all possible digits from 0 to 9 and see if the sum is divisible by 3 or not. Follow the steps below to solve the problem:

  • Initialize the variable sum as 0 to store the sum of digits of the number.
  • Add the value of digit at i-th index in the variable sum.
  • Initialize the variable count as 0 to store the answer.
  • If the number itself is divisible by 3 then increment count by one.
  • Initialize the variable remaining_sum as sum-(number.charAt(i)-48).
  • Add the value of j to the variable remaining_sum and if remaining_sum is divisible by 3 and j is not equal to the digit at i-th index, then add the value of count by 1.
  • After performing the above steps, print the value of count as the answer.

Below is the implementation of the above approach..

                     
                     
                           
                       
               

Time Complexity: O(N) Auxiliary Space: O(1)

author

Please Login to comment...

Similar reads.

  • divisibility
  • number-digits

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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. For each week, follow this workflow:

And then submit the courseā€™s final project .

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 .

IMAGES

  1. Product of Numbers divisible by 3 from M to N

    cs python fundamentals assignment 4 divisible by three

  2. list count divisible by 3 in python šŸ˜€

    cs python fundamentals assignment 4 divisible by three

  3. python program to generate divisible by 3 but are not a multiple of 2

    cs python fundamentals assignment 4 divisible by three

  4. ciclo for

    cs python fundamentals assignment 4 divisible by three

  5. Python Programming

    cs python fundamentals assignment 4 divisible by three

  6. Write a program to check whether a number is divisible by 3 or not

    cs python fundamentals assignment 4 divisible by three

COMMENTS

  1. Assignment 4: Divisible by Three ProjectSTEM hello! I have no clue at

    To write a program using a loop in Python, you can leverage the language's high-level and readable design.Python's emphasis on code readability is evident through its use of indentation.. How to explain. It supports multiple programming paradigms, including functional, object-oriented, and structured programming.. One common type of loop in Python is the while loop, which allows you to execute ...

  2. CS Python Fundamental Unit 3 and Unit 4 Review Flashcards

    Which of the following is true? a = 15 b = 10 1. b >= a or a > b 2. a < b and a == b 3. a < b or a == b 4. a < b and a != b 1. b >= a or a > b See an expert-written answer!

  3. Project stem CS python fundamentals UNIT 1 SV Flashcards

    1.4 lesson practice question 1. 1. Which of the following is true about software and hardware? Software refers to programs that run on the physical hardware of a computer. 1.4 lesson practice question 2. 2. Main memory is ___________. lost when the computer is powered off. 1.4 lesson practice question 3.

  4. 8.1

    8.1 - 8.5 Project Stem CS Python Fundamentals. A list is: A data structure that stores a list of users. A data structure that holds external data. A data structure that holds a sequence of data. A function that organizes data. Click the card to flip šŸ‘†. A data structure that holds a sequence of data. Click the card to flip šŸ‘†.

  5. python

    Nice answer, given the peculiar requirements. It may be worth noting that even divThree is much more inefficient for really large numbers (e.g., 10**10**6) than the % 3 check, since the int -> str conversion takes time quadratic in the number of digits. (For 10**10**6, I get a timing of 13.7 seconds for divThree versus 0.00143 seconds for a simple %3-based function.

  6. Welcome to 101 Exercises for Python Fundamentals

    Welcome to 101 Exercises for Python Fundamentals. Solving these exercises will help make you a better programmer. ... function definition named is_multiple_of _three that takes in a number and returns True or False if the number is evenly divisible by 3. assert is_multiple_of_three(3 ... assert is_multiple_of_both_three_and_five(4) == False ...

  7. python

    2. You can use % operator to check divisiblity of a given number. The code to check whether given no. is divisible by 3 or 5 when no. less than 1000 is given below: n=0. while n<1000: if n%3==0 or n%5==0: print n,'is multiple of 3 or 5'. n=n+1. edited Jan 12, 2016 at 19:19.

  8. Python Program to check whether it is possible to make a divisible by 3

    Given an integer N, the task is to check whether the sum of digits of the given number is divisible by all of its digits or not. If divisible then print Yes else print No. Examples: Input: N = 12 Output: No Sum of digits = 1 + 2 = 3 3 is divisible by 1 but not 2. Input: N = 123 Output: Yes Approach: First find the sum of the digits of the number th

  9. python

    python pep8 suggests to use 4-whitespace nesting as indentation levels. Use 4 spaces per indentation level. If you have more numbers to check divisibility against, keep a set of the numbers for which num % x == 0 , and print the factors at the end.

  10. Python Challenge: Divisible by 3

    You have now completed this challenge. You solved the exercise. Sometimes we can learn a lot from seeing other people's code and different ways to solve an exercise. Here is an example of how the exercise can be solved: Interactive Python challenge: Divisible by 3. Define a function named div_3 that returns True if its single integer parameter ...

  11. Divisible by 3 or not in python

    Python Program to get a number num and check whether num is divisible by 3. Sample Input 1: 27 Sample Output 1: Divisible by 3 Sample Input 2: 43 Sample Output 2: Not divisible by 3. Try your Solution. Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

  12. Assignment 4 divisible by 3 in project stem

    The program starts by asking the user for the total number of checks. It then enters a for loop where it prompts the user to input a number and checks if it's divisible by 3 using the modulus operator. The program keeps count of how many numbers are divisible and how many are not. After the loop, it prints the counts. profile. Nice explanation ...

  13. 4. Conditionals

    Test it by importing your program into the Python shell. Write a function named is_divisible_by_3 that takes a single integer as an argument and prints "This number is divisible by three." if the argument is evenly divisible by 3 and "This number is not divisible by three." otherwise. Now write a similar function named is_divisible_by_5.

  14. 4. Conditionals

    Test it by importing your script into the Python shell. Write a function named is_divisible_by_3 that takes a single integer as an argument and prints "This number is divisible by three." if the argument is evenly divisible by 3 and "This number is not divisible by three." otherwise. Now write a similar function named is_divisible_by_5.

  15. CS Python fundamentals 1.5 question 4 : r/projectstem

    CS Python fundamentals 1.5 question 4. If anyone has the answers to 1.5-1.9 in project stem that would be a big helpšŸ™. 2.

  16. Unit 4

    CS1101 Python Programming script:def is_divisible(x, if return true else: return false implementing is_power function that takes two arguments def is_power(x, ... Programming Assignment Unit 4; Programming Assignment Unit 5; ... Programming Fundamentals CS 1101. University of the People. 999+ Documents. Go to course. 4. CS 1101 Discussion Forum ...

  17. Written Assignment Unit-4 Solution for Programming Fundamentals 1101

    View WRITTEN ASSIGNMENT UNIT-4 SOLUTION FOR PROGRAMMING FUNDAMENTALS 1101.PDF from COMP CS 1101 at University of the People. Sample Answer Python Program # def ReturnTrue if is_divisible(x, AI Chat with PDF

  18. Count of different numbers divisible by 3 that can be obtained by

    Given a string str representing a number having N digits, the task is to calculate the number of ways to make the given number divisible by 3 by changing at most one digit of the number.. Examples: Input: str[] = "23" Output: 7 Explanation: Below are the numbers that can be made from the string which are divisible by 3 - 03, 21, 24, 27, 33, 63, 93 1.Change 2 to 0 (0+3)=3 divisible by 3

  19. Assignment 4 divisible by three HELP PLEASE : r/EdhesiveHelp

    need help with assignment 4 divisible by three. Advertisement Coins. 0 coins. Premium Powerups Explore Gaming. Valheim Genshin Impact Minecraft Pokimane Halo Infinite Call of Duty: Warzone Path of Exile Hollow Knight: Silksong Escape from Tarkov Watch Dogs: Legion. Sports ...

  20. Assignment 4 divisible by three I need a little help. I do not

    The issue is with the line num % 3 == 0 in the else statement. This is a comparison expression that evaluates to either True or False and does not change the value of notdivisible.. What is programming? Computer programming is the process of carrying out a specific computation, typically by designing and constructing an executable computer programme.. Here's the corrected code:

  21. Computer Science assignment journal unit 4 1101is divisible

    Computer Science assignment journal unit 4 1101is divisible. Cover learning journal on first week of first term on python language. ... Programming Fundamentals (CS 1101) Practice materials. 95% (55) 98. ... Difference between a list and Tutle in Python [ WEEK 3 ] Written Assignment; A Python Function With 3 Parameters Using Math Module;

  22. Assignment 4: divisible by three : r/projectstemanswer

    Assignment 4: divisible by three unit 4 Sorry for the delayed posting, I like just got dumped last night soooo yeah Share Add a Comment. Be the first to comment Nobody's responded to this post yet. Add your thoughts and get the conversation going. Top 69% ...

  23. 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 ...