Writing a program to divide user_num by x 3 times - python

I am trying to write a program for my class that divides the user_num by x three times. Thus far, I have:
user_num = input()
x = input()
So what is the missing link to do this? By three times, it should be like if the user inputs:
2000
2
Then the output should be:
1000 500 250
Am I on the right track and if so, what is the next step to make this work?

The first step is simply what you have, except the numbers are also converted into a numeric type to allow for mathematical operations.
user_num = int(input("enter a number: "))
x = int(input("enter x: "))
After that, you want to divide user_num by x, and then print the result, three times over. This is done using a loop. // will perform the division and ignore the decimal. print will work as expected, and the end argument will format the output as you described.
for _ in range(3):
user_num = user_num // x
print(user_num, end=" ")

Related

how to print sum of numbers between any given numbers using loop python

how can i print the sum of all the numbers between any two given numbers in python.
i am not allowed to use functions like sum(). i can only use while or for loop.
i have a code which does the job but the problem is it also prints result every time after adding two numbers but i only want it to print final sum of all the numbers.
Here's the code:
...
a = int(input("Please enter a number"))
b = int(input("Please enter a number"))
n = 0
for x in range(a+1,b):
n+=x
print(n)
...
thanks
There is an Indentation Error just check the line below the for loop and give the proper indentation. You can refer to my code
a = int(input("Please enter a number: "))
b = int(input("Please enter a number: "))
n = 0
for x in range(a+1,b):
n+=x
print(n)

Write a Python program to print the following sequence of numbers (N to be entered by user): X + X^3/3! + X^5/5!... Upto the Nth Term

The problem i am having with this question is that the code i have written is showing a logical error. Here is the code i have written:
x = int(input("Please enter the base number: "))
n = int(input("Please enter the number of terms: "))
s = 0
factorial = 1
for i in range(1,n+1,2):
factorial = factorial*i
s = (x**i) / factorial
#using f string to format the numbers to a fixed number of decimal places
print(f"{s:.6f}", end='+')
I used the for loop to only show odd values of index, because that is the requirement in the question. My output is coming as follows:
Please enter the base number: 2
Please enter the number of terms: 4
2.000000+2.666667+
We don't have to actually find the sum, only display all the individual addends separated by a plus sign. What changes should i make within the code to get the required results?
My required output would look something like this:
Please enter the base number: 2
Please enter the number of terms: 4
2.000000+1.333333+0.266666+0.025396
Just change to
for i in range(1,2*(n)+1,2):
from
for i in range(1,n+1,2):
Now, the output is:
Please enter the base number: 2
Please enter the number of terms: 4
2.000000+2.666667+2.133333+1.219048+
Also, the method of calculating factorial is wrong as it skips half of the terms, when you jump i from 1 to 3 to 5, so that 2, 4, 6.. are getting missed.
So, you can do:
if i > 1:
factorial = factorial*i*(i-1)
elif i == 1:
factorial*i
So, the final code would be:
x = int(input("Please enter the base number: "))
n = int(input("Please enter the number of terms: "))
s = 0
factorial = 1
for i in range(1,2*n+1,2):
if i > 1:
factorial = factorial*i*(i-1)
elif i == 1:
factorial*i
s = (x**i) / factorial
#using f string to format the numbers to a fixed number of decimal places
print(f"{s:.6f}", end='+')
Factorial is in the loop but the loop does i=1,3,5 and not i=1,2,3,4,5, that's might be a problem. If the "number of terms" : "2.000000+2.666667" is two so in the loop your range avec to be until n*2 and not n but careful because the factory will be changed.

calculate the sum of the digits of any three digit no(in my code loop is running every time help in correction)

my problem is i have to calculate the the sum of digits of given number and that no is between 100 to 999 where 100 and 999 can also be include
output is coming in this pattern
if i take a=123 then out put is coming total=3,total=5 and total=6 i only want output total=6
this is the problem
there is logical error in program .Help in resolving it`
this is the complete detail of my program
i have tried it in this way
**********python**********
while(1):
a=int(input("Enter any three digit no"))
if(a<100 or a>999):
print("enter no again")
else:
s = 0
while(a>0):
k = a%10
a = a // 10
s = s + k
print("total",s)
there is no error message in the program because it has logical error in the program like i need output on giving the value of a=123
total=6 but i m getting total=3 then total=5 and in last total=6 one line of output is coming in three lines
If you need to ensure the verification of a 3 digit value and perform that validation, it may be useful to employ Regular Expressions.
import re
while True:
num = input("Enter number: ")
match = re.match(r"^\d{3}$, num)
if match:
numList = list(num)
sum = 0
for each_number in numList:
sum += int(each_number)
print("Total:", sum)
else:
print("Invalid input!")
Additionally, you can verify via exception handling, and implementing that math you had instead.
while True:
try:
num = int(input("Enter number: "))
if num in range(100, 1000):
firstDigit = num // 10
secondDigit = (num // 10) % 10
thirdDigit = num % 10
sum = firstDigit + secondDigit + thirdDigit
print("Total:", sum)
else:
print("Invalid number!")
except ValueError:
print("Invalid input!")
Method two utilizes a range() function to check, rather than the RegEx.
Indentation problem dude, remove a tab from last line.
Also, a bit of python hint/tip. Try it. :)
a=123
print(sum([int(x) for x in str(a)]))

Python - Run for loop 3 times [duplicate]

This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 3 months ago.
So I have this assignment and I have a question about a part I don't know how to do, can you guys help me?
def main():
# Please see the comments
largest = 0
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
number1 = int(input("Please enter the first number: "))
number2 = int(input("Please enter the second number: "))
number3 = int(input("Please enter the third number: "))
# insert call to function find_largest after this comment.
# find_largest will take in three parameters and will return the largest of the 3 numbers
result = find_largest(number1, number2, number3)
# insert the statement to print the three numbers entered and the largest number after this comment.
print("The numbers you entered were, \n", [number1, number2, number3])
print ("The largest of the numbers you entered is", result)
def find_largest(a, b, c):
# insert parameters in the parenthesis
# Write the code for this function here.
# find_largest will take in three parameters and will return the largest of the 3 numbers
# These three numbers are passed in as parameters from the main function
# Hint: if and elif - no loop needed here
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
return largest
main() # this is the call to main() that will make the program run
So, my question is the part:
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
I don't know what to add so the loop run 2 more times after it has found the largest number
The loop you have makes the first two iterations of the loop pointless, as each time you loop, you are reassigning new numbers to the three number variables. As a result, only the numbers entered in the last iteration of the loop are ever used for anything. I think this would make more sense:
numbers = []
for i in range(3):
input = int(input("Enter number: "))
numbers.append(input)
This will give you a list called numbers with 3 numbers in it entered by the user. Then you can do what you want with them. Having said that, you really don't need a for loop to do this. As Craig Burgler mentioned.
Alternatively(though this doesn't use range...):
number1 = 0
number2 = 0
number3 = 0
for i in (number1, number2, number3):
i = int(input("Enter number: "))
The code as written will ask for three numbers three times, overwriting the first and second set of numbers that the user enters. If the assignment is to get three numbers from the user and tell the user which is largest, then you do not need the for loop. The three input statements will do the trick.

Python: Display and count divisors of two integers

Write a program that will prompt the user for two integers, each of which is greater
than 0. The program will display and count the number of divisors that the two integers have in
common.
Additional requirements:
if the integer is less than 1 tell the user there is a problem and then prompt them for the
integer again.
This is what I have written so far, but I am stuck here I dont know how to incorporate both numbers. Essentially I do not know where to go from here or if 'here' is even correct???
Please help...[This is my first time with python]
integer1 = input("Enter an integer: ")
integer2 = input("Enter an integer: ")
print integer1, ": " ,
i = 1
while i <= integer1 and integer2 :
if integer1 or integer2 < 1 :
print input("Enter an integer: ")
if integer1%i == 0 and integer2%i == 0 :
print i ,
i = i + 1
Try to do one step after the other. And try to break down your task into simple steps. In your example it could be something like:
Get first number
Get second number
Calculate
This you can break down futher
Get first number:
Get Number from User
Loop while Number is not ok
...
This way you can see that the validation should not be inside the while loop.
Another tip: test each step separately. This way you will find that if integer1 or integer2 < 1 or while i <= integer1 and integer2 will not work the way you think they do.
This is not how logical operators work in Python or programming in general.
while i <= integer1 and integer2 :
In Python integer2 is a separate logical statement that is always true.
Try instead:
while i <= integer1 and i <= integer2
You'll want to move the code that
validates your input outside of the
loop.
Your print i doesn't need a
comma.
The syntax in your flow
control needs a bit of work, for
example if integer1 or integer2 <
1: should be if ((integer1 < 1) or
(integer2 < 1)):.
First we should do a simple way to get both integers; noting there could be multiple errors. (Even better would be raw_input and checking the number resolves to an int).
integer1 = -1
integer2 = -1
while(integer1 < 1):
integer1 = input("Enter integer 1: ")
while(integer2 < 1):
integer2 = input("Enter integer 2: ")
factor_list1 = [] # store factor list of first number
double_factor_count = 0
# generate the factor list of the first number
for i in range(1, integer1+1): # range(1,5+1) is the list [1,2,3,4,5]
if integer1 % i == 0:
factor_list1.append(i)
for j in range(1, integer2+1):
if integer2 % j == 0 and j in factor_list1:
print j,
double_factor_count += 1
print "\n double count:", double_factor_count
Possibly you want to change it to range(2, integer1) if you want to skip 1 and the integer typed in as numbers.
Note your original code wasn't indented (so didn't appear as code in the forums, and that and and or combine expressions (e.g., things that are True or False). So you meant if integer1 < 1 or integer2 < 1:.
Your code is actually very close, but you have a few problems:
You're not validating integer1 and integer2 correctly (though I suspect you know that, since you're just printing the replacement value).
Your loop test is broken. What you've written means "i is less than integer1, and also integer2 isn't zero".
You can also improve your code in a couple of ways:
Ensuring that your input is not only >= 1, but also an integer.
Using a for loop instead of a while loop, using Python's excellent iterables support.
Here's how to make sure that what the user typed was an integer:
integer1 = 0
while not integer1:
try:
# raw_input() ensures the user can't type arbitrary code
# int() throws a ValueError if what they typed wasn't an integer
integer1 = int(raw_input("Enter the first integer: "))
if integer1 < 1:
print "You must enter an integer greater than 0!"
integer1 = 0 # so that our while statement loops again
except ValueError:
# the user typed something other than an integer
print "You must enter an integer!"
The while, try, and if statements here ensure that the user will be forced to enter a valid integer before your code continues. Here's an example of what the user sees:
Enter the first integer: 6.6
You must enter an integer!
Enter the first integer: -5
You must enter an integer greater than 0!
Enter the first integer: sys.exit(0)
You must enter an integer!
Enter the first integer: 12
Enter the second integer:
And this is how I'd recommend setting up your loop:
# min() returns the smallest of its arguments
# xrange() iterates over a sequence of integers (here, starting with 1 and
# stopping at min(integer1, integer2))
for i in xrange(1, min(integer1, integer2) + 1):
# magic goes here!
Documentation links:
int()
min()
raw_input() and input()
xrange()
Your problem is with your if statements.
Rather than saying: while i <= integer1 and integer2, you need to say while i <= integer1 and i <= integer2
The same applies for your other if statement. if integer1 or integer2 < 1 : should be if integer1 < 1 or integer2 < 1 :

Categories

Resources