Having some problems with Task 2 - python

#Loop starts here
# This one provides the option to select one of the three tasks.
task = input (' Hello! Welcome to Patricia G. Myrons program select task 1, 2 or 3. \n')
#If the user selects task 1, the program will perform the Simple Divisibility Test
if task == 1 :
print "Task 1 is here! \n"
print "I can tell you if n is evenly divisible by m \n"
print "Enter the following"
n = input("Integer:")
m = input("Integer:")
evaluation = n % m
if evaluation == 0:
print n, "/", m, " evenly divides"
else:
print n, "/", m, " Sorry, does not evenly divide. Try again!"
#If the user selects task 2, the program will perform the Prime Test
if task == 2 :
print "Task 2 is here! \n"
print "I can tell you if the number you enter is prime or not \n"
number=int(raw_input("Enter a number "))
elif number <= 1:
print "Sorry! It is not prime"
else:
n=2
check = True
while n != m:
if m%n == 0:
print "Yeas! The number you entered is prime"
check = False
break
n+=1
if check == True:
print "Yeas! The number you entered is prime"
#If the user selects task 3, the program will display a list of factor numbers
if task == 3:
print "Task 3 is here! \n"
print "I can tell you all of the factors of the number you enter \n"
def print_factors(n):
print("The factors of",n,"are:")
for i in range(1, n + 1):
if n % i == 0:
print(i)
num = int(input("Enter any number: "))
I just finished my program in Python, but I am having some problems with Task 2.

Your code has indentation problem.
Also the variable used in code is not defined with default value.
I defined all variables default value on top of code.
Please see below code.
evaluation = 0
n = 0
m = 0
number = 0
check = False
task = input (' Hello! Welcome to Patricia G. Myrons program select task 1, 2 or 3. \n')
#If the user selects task 1, the program will perform the Simple Divisibility Test
if task == 1 :
print "Task 1 is here! \n"
print "I can tell you if n is evenly divisible by m \n"
print "Enter the following"
n = input("Integer:")
m = input("Integer:")
evaluation = n % m
if evaluation == 0:
print n, "/", m, " evenly divides"
else:
print n, "/", m, " Sorry, does not evenly divide. Try again!"
#If the user selects task 2, the program will perform the Prime Test
if task == 2 :
print "Task 2 is here! \n"
print "I can tell you if the number you enter is prime or not \n"
number=int(raw_input("Enter a number "))
if number <= 1:
print "Sorry! It is not prime"
else:
n=2
check = True
while n != m:
if m%n == 0:
print "Yeas! The number you entered is prime"
check = False
break
n+=1
if check == True:
print "Yeas! The number you entered is prime"
#If the user selects task 3, the program will display a list of factor numbers
if task == 3:
print "Task 3 is here! \n"
print "I can tell you all of the factors of the number you enter \n"
def print_factors(n):
print("The factors of",n,"are:")
for i in range(1, n + 1):
if n % i == 0:
print(i)
num = print_factors(int(input("Enter any number: ")))

Related

hailstone program in python

i have to write a hailstone program in python
you pick a number, if it's even then half it, and if it's odd then multiply it by 3 and add 1 to it. it says to continue this pattern until the number becomes 1.
the program will need methods for the following:
accepting user input
when printing the sequence, the program should loop until the number 1.
print a count for the number of times the loop had to run to make the sequence.
here's a sample run:
prompt (input)
Enter a positive integer (1-1000). To quit, enter -1: 20
20 10 5 16 8 4 2 1
The loop executed 8 times.
Enter a positive integer (1-1000). To quit, enter -1: 30
30 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
The loop executed 19 times.
Enter a positive integer (1-1000). To quit, enter -1: -1
Thank you for playing Hailstone.
right now i have this:
count = 0
def hailstone(n):
if n > 0
print(n)
if n > 1:
if n % 2 == 0:
hailstone(n / 2)
else:
hailstone((n * 3) + 1)
count = count + 1
i don't know what to do after this
Try to think in a modular way, make two functions: check_number() and user_call(). Check_number will verify if the current number in the loop is odd or even and the user_call() just wraps it to count how many times the loop did iterate.
I found the exercise in a great book called Automate Boring Stuff with Python, you have to check it out, if you don't know it already.
Here's my code. Try to use what serves you the best.
from sys import exit
def check_number(number):
if number % 2 ==0:
print(number // 2)
return(number // 2)
else:
print(number*3+1)
return number*3+1
def user_call(number):
count = 0
while number != 1:
count += 1
number = check_number(number)
return count
if __name__ == "__main__":
try:
number = int(input('Give a number \n'))
count = user_call(number)
print('count ',count)
except Exception as e:
exit()
you can use global
visit https://www.programiz.com/python-programming/global-keyword to learn more
import sys
res = []
def hailstone(number):
global res
if number > 1:
if number % 2 == 0:
res.append( number // 2 )
hailstone(res[len(res)-1])
else:
res.append(number * 3 + 1)
hailstone(res[len(res)-1])
return res
number = int(input('Enter a positive integer. To quit, enter -1: '))
if number <= 0 or number == 0:
print('Thank you for playing Hailstone.')
sys.exit()
else:
answers = hailstone(number)
for answer in answers:
print(answer)
print('The loop executed {} times.'.format(len(answers) + 1))
I used recursion to solve the problem.
Heres my code:
Edit: All criteria met
count = 0
list_num = []
def input_check():
number = int(input("Enter a positive integer (1-1000). To quit, enter -1: "))
if number >= 1 and number <= 1000:
hailstone_game(number)
elif number == -1:
return
else:
print("Please type in a number between 1-1000")
input_check()
def hailstone_game(number):
global count
while number != 1:
count += 1
list_num.append(number)
if number % 2 == 0:
return hailstone_game(int(number/2))
else:
return hailstone_game(int(number*3+1))
list_num.append(1) # cheap uncreative way to add the one
print(*list_num, sep=" ")
print(f"The loop executed {count} times.")
return
input_check()
Additional stuff that could be done:
- Catching non-integer inputs using try / except
Keep in mind when programming it is a good habit to keep different functions of your code separate, by defining functions for each set of 'commands'. This leads to more readable and easier to maintain code. Of course in this situation it doesn't matter as the code is short.
Your recursive function is missing a base/terminating condition so it goes into an infinite loop.
resultArray = [] #list
def hailstone(n):
if n <= 0: # Base Condition
return
if n > 0:
resultArray.append(n)
if n > 1:
if n % 2 == 0:
hailstone(int(n/2))
else:
hailstone((n * 3) + 1)
# function call
hailstone(20)
print(len(resultArray), resultArray)
Output
8 [20, 10, 5, 16, 8, 4, 2, 1]
Here's a recursive approach for the problem.
count=0
def hailstone(n):
global count
count+=1
if n==1:
print(n)
else:
if n%2==0:
print(n)
hailstone(int(n/2))
else:
print(n)
hailstone(3*n+1)
hailstone(21)
print(f"Loop executed {count} times")

Finding whether a number is prime or not python3

I have written a code to find out if a number is prime or composite.
The code works fine when I input a prime number but when I input a composite number the output is:
enter number: 100
The number is not prime.
The number is prime.
I don't want The number is prime output for composite number input.
Here is my code:
print ('This program tells whether the number is prime or not')
print ('')
def prime(x):
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
print('The number is prime.')
i = input('enter number: ')
prime(int(i))
Please tell me what can I do to correct it.
The problem is the indentation, you've to move the indentation of the last line and add a break after that, so try using:
print ('This program tells whether the number is prime or not')
print ('')
def prime(x):
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
print('The number is prime.')
break
i = input('enter number: ')
prime(int(i))
I can see why. you are missing else after if. try this:
print ('This program tells whether the number is prime or not')
print ('')
def prime(x):
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
else:
print('The number is prime.')
i = input('enter number: ')
prime(int(i))
if num > 1:
for n in range(2, x-1):
if x % n == 0:
print('The number is not prime.')
break
else:
print('The number is prime.')
else:
print('The number is not prime.')
Simply fix that indentation in the for loop. Also, this looks a lot cleaner.
This is the recommended way to solve this problem.
do not use hard coded print statement.
try to return True or False instead.
def is_prime(x:str):
if x < 2:
return False
else:
for n in range(2, int(x/2)): # Use this for more speed
if x % n == 0:
return False
return True
Now you can check the number is prime or not by calling this is_prime function
print('Number is prime' if is_prime(6) else 'Number is not prime')
The problem is that when you break the loop the last print statement is called. If you end the function using return statement you will not reach the last print statement.
def prime(x):
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
return
print('The number is prime.')

Primality Test algorithm fails

I created a simple primality test algorithm, but it fails for numbers like 15. Why?
number = int(input("Test if Prime: "))
print ("Is " + str(number) + " Prime?: ")
for i in range (2, number):
if number % i == 0:
print ("No")
break
else:
print ("Yes")
I tried an elif statement with other variations, but it still doesn't work:
number = int(input("Test if Prime: "))
print ("Is " + str(number) + " Prime?: ")
for i in range (2, number):
if number % i == 0:
break
elif number % i != 0:
print ("Yes")
Any help is appreciated.
You have your else condition inside the loop. At any point in time, it'll only check for one value...
Modifying your for loop to print out the number it is checking for:
for i in range (2, number):
print (i)
if number % i == 0:
print ("No")
break
else:
print ("Yes")
prints out (for number = 15):
2
Yes
3
No
Which you know works if it prints out 'No' number - 1 times
To slightly modify what you did, we can just change it to:
flag = False
for i in range (2, number):
if number % i == 0:
print ("No")
flag = True
break
if (!flag)
print("Yes")
All this does is push the print statement outside the loop (for a number to be prime it needs to be non-divisible by all numbers less than it). The flag ensures that you only print out True or False (you don't want to print out both)
Here's a quick refactor I did based on your example:
def is_prime_simple(number):
is_prime = True
for i in range(2, number):
if number % i == 0:
is_prime = False
break
return is_prime
number = int(input("Test if Prime: "))
print ("Is " + str(number) + " Prime?: ")
print('Yes' if is_prime_simple(number) else 'No')
due to wrong indentation, else will be will executed for all non-divisors of odd numbers
for i in range (2, number):
if number % i == 0:
print ("No")
break
else:
print ("Yes")

Automate the boring tasks - exercise - collatz function

Beginner question here.
I have just attempted an exercise from Automate the boring stuff. I've completed the question in the format suggested by first defining a function as below:
"Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1."
and then using that same function, meeting those minimal constraints, to write a programme that meets the following requirements:
Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.
I've managed to generate a sequence of numbers ending with one, following the above rules, but my program prints each number in the sequence three times. Is anyone able to explain why this might be?
Thanks so much for your help
def collatz(number):
if int(number) % 2 == 0:
print(int(number)//2)
return int(number)//2
else:
print(3 * int(number) + 1)
return 3 * int(number) + 1
collatz(5)
print('Enter a number')
entry = input()
while collatz(entry) != 1:
collatz(entry)
entry = collatz(entry)
Your loop should look like this:
entry = input()
while entry != 1:
entry = collatz(entry)
You are calling the function 3 times and you have a print call in the function.
Only call the function once and I would remove the print statements from the collatz method and just print in the calling loop, e.g.:
In []:
def collatz(number):
if number % 2 == 0:
return number//2
return 3*number + 1
entry = int(input("Enter a number: "))
print(entry)
while entry != 1:
entry = collatz(entry)
print(entry)
Out[]:
Enter a number: 10
10
5
16
8
4
2
1
You can try:
def collatz(number):
if number == 0:
return 'Try again with an integer other than 0'
elif number == 1:
return 1
elif number % 2 == 0:
n = number // 2
print(n)
elif number % 2 == 1:
n = 3 * number + 1
print(n)
while n != 1:
n = collatz(n)
return n
return n
The last statement return n in line 15 is optional.

How can I log the highest and lowest number entered in Python?

I don't realize what is my mistake, this is how far I got now:
x = 1
e = 0
while x <= 50:
print "Please enter a number (from 1 to 9):"
b = float(raw_input())
asd = 0
if asd == 0:
h = b
l = b
asd = 1
if b < l:
l = b
elif b > h:
h = b
if 1 <= b or b <= 9:
x = x * b
print x
else:
print "Number is too large or too small."
e = e + 1
print "You have reached a value over 50."
print "Highest number entered:", h
print "Lowest number entered:", l
print "Entered numbers:", e
This is the program's output:
Please enter a number (from 1 to 9):
5
5.0
Please enter a number (from 1 to 9):
4
20.0
Please enter a number (from 1 to 9):
5
100.0
You have reached a value over 50.
Highest number entered: 5.0
Lowest number entered: 5.0
Entered numbers: 3
Why is the program giving me 5 instead of 4 as lowest number entered and how can I correct that?
You keep resetting asd each iteration, you need to set the variables outside the loop, I would use a list and that will enable you to get the min/max and number of valid inputs :
nums = [] # hold all nums outside the loop
limit = 1
while 50 >= limit:
num = float(raw_input("Please enter a number (from 1 to 9)")
if 1 <= num <= 9:
limit *= num
nums.append(num) # add all to list
else:
print "Number is too large or too small."
print "You have reached a value over 50."
print "Highest number entered:", max(nums)
print "Lowest number entered:", min(nums)
print "Entered numbers:", len(nums)
Everytime you go through the loop, you are setting asd to 0, causing the if statement below it to execute every single time, so you are always blindly updating l with the value the user just entered, which you have named as b
just for fun :)
def get_float_input(msg="Enter a Number:"):
while True:
try:
return float(raw_input(msg))
except ValueError:
print "Invalid Input Please Enter A Float!"
from itertools import takewhile
my_list = sorted(takewhile(lambda val:val < 50,iter(get_float_input,"Y")))
print "You Have Entered A # Greater than 50"
print "Min:",my_list[0]
print "Max:",my_list[-1]
print "Entered %d Numbers"%len(my_list)

Categories