basic python 3 module issue - python

Okay, so I'm trying to write a module for class to load up a basic prime number checker. We have samples to look from, and I'm going to copy what I have so far... But I'm pretty lost on how to write this, and then for the program to actually call the module (should be import xxxx.py right?)
Don't be too harsh, I'm not the only one in my class struggling with this. Youtube and my search results on here haven't really helped. Thanks in advance for yet, another basic question.
#!/usr/bin/env python3
#Program Name
print("Prime Number Checker")
def factor_count(num):
factor_count = 0
print("The factors are: ")
def main():
choice = "y"
while choice.lower() == "y":
#user input
num = int(input("Please enter a number: "))
if num <= 1:
print("please choose a value greater than 1. ")
print()
else:
for i in range(1, num+1):
if num%i == 0:
print(i)
if factor_count == 2:
print(num, "is prime")
else:
print(num, "is not prime!")
if __name__ == "__main__" :
main()
print()
print("goodbye")

Couple of points, here is how I would write the program :
Don't use the same name for variables and function names factor_count. So when you write if factor_count == 2 it is always false.
You aren't updating the value of variable choice after every run
the way of finding primes is also very inefficient.
def main():
choice = "y"
while choice.lower() == "y":
factor_count = 0
# user input
num = int(input("Please enter a number: "))
if num <= 1:
print("please choose a value greater than 1. ")
print()
else:
for i in range(2, num):
if num % i == 0:
print(i)
factor_count += 1
if factor_count == 0:
print(num, "is prime")
else:
print(num, "is not prime!")
choice = input('Do you want to continue?(y/n) : ')
if __name__ == "__main__":
print("Prime Number Checker")
main()
print()
print("goodbye")

Related

How do I break out of my while loop without using the most popular functions?(sys.exit,break,etc.)

I am making a program that generates a random number and asks you to guess the number out of the range 1-100. Once you put in a number, it will generate a response based on the number. In this case, it is Too high, Too low, Correct, or Quit too soon if the input is 0, which ends the program(simplified, but basically the same thing).
It counts the number of attempts based on how many times you had to do the input function, and it uses a while loop to keep asking for the number until you get it correct. The problem that I am facing is that I have to make it break out of the while loop once the guess is either equal to the random number or 0. This normally isn't an issue, because you could use sys.exit() or some other function, but according to the instructions I can't use break, quit, exit, sys.exit, or continue. The problem is most of the solutions I've found for breaking the while loop implement break, sys.exit, or something similar and I can't use those. I used sys.exit() as a placeholder, though, so that it would run the rest of the code, but now I need to figure out a way to break the loop without using it. This is my code:
import random
import sys
def main():
global attempts
attempts = 0
guess(attempts)
keep_playing(attempts)
def guess(attempts):
number = random.randint(1,100)
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
while guess != 0:
if guess != number:
if guess < number:
print("Too low, try again")
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again")
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
else:
print()
print("Congratulations! You guessed the right number!")
print("There were", attempts,"attempts")
print()
#Ask if they want to play again
sys.exit()#<---- using sys.exit as a placeholder currently
else:
print()
print("You quit too early")
print("The number was ",number,sep='')
#Ask if they want to play again
sys.exit()#<----- using sys.exit as a placeholder currently
def keep_playing(attempts):
keep_playing = 'y'
if keep_playing == 'y' or keep_playing == 'n':
if keep_playing == 'y':
guess(attempts)
keep_playing = input("Another game (y to continue)? ")
elif keep_playing == 'n':
print()
print("You quit too early")
print("Number of attempts", attempts)
main()
If anyone has any suggestions or solutions for how to fix this, please let me know.
Try to implement this solution to your code:
is_playing = True
while is_playing:
if guess == 0:
is_playing = False
your code...
else:
if guess == number:
is_playing = False
your code...
else:
your code...
Does not use any break etc. and It does breaks out of your loop as the loop will continue only while is_playing is True. This way you will break out of the loop when the guess is 0 (your simple exit way) or when the number is guessed correctly. Hope that helps.
I am not a fan of global variables but here it's your code with my solution implemented:
import random
def main() -> None:
attempts = 0
global is_playing
is_playing = True
while is_playing:
guess(attempts)
keep_playing()
def guess(attempts: int) -> None:
number = random.randint(1,100)
print(number)
is_guessing = True
while is_guessing:
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
if guess == 0:
is_guessing = False
print("\nYou quit too early.")
print("The number was ", number,sep='')
else:
if guess == number:
is_guessing = False
print("\nCongratulations! You guessed the right number!")
print("There were", attempts, "attempts")
else:
if guess < number:
print("Too low, try again.")
elif guess > number:
print("Too high, try again.")
def keep_playing() -> None:
keep_playing = input('Do you want to play again? Y/N ')
if keep_playing.lower() == 'n':
global is_playing
is_playing = False
main()
TIP:
instead
"There were", attempts, "attempts"
do: f'There were {attempts} attempts.'

Python : If statement within a while loop

I wrote a program, which keeps rolling a "num" sided die until it reaches the maximal roll which is the number you write as "num". However, if it happens that the first roll is the number, the program does not say "You landed on your number!" as it should. Here is the code
import random
num = () #put the number here#
i = random.randint(1,num)
while i != num:
print(i)
print("Not lucky")
i = random.randint(1,num)
if i == num:
print("You landed on your number!")
Again, if the roll equals the number choice, I get "Process finished with exit code 0", not the text I want. How do I fix this?
Put the final print, outside of the while loop, as you're always land there
num = 5 # put the number here#
i = random.randint(1, num)
while i != num:
print("Not lucky,", i, "isn't the one")
i = random.randint(1, num)
print("You landed on your number!")
what if something like that?
import random
num = int(input('Put your number: '))
i = random.randint(1, num)
while True:
if i == num:
print("You landed on your number!")
print(num)
break
else:
print(i)
print("Not lucky")
i = random.randint(1, num)
You can do it like this:
import random
num = (2) #put the number here#
i = random.randint(1,num)
while i != num:
i = random.randint(1,num)
if i != num:
print(i, "Not lucky")
print(i, "You landed on your number!")
import random
num = #put the number here#
while True:
i = random.randint(1,num)
print(i)
if i == num:
print("You landed on your number!")
break
print("Not lucky")

How do i not print it twice

I'm new to python and experimenting with functions. Here's the sample code that I'm working wtih
def menu():
print(" 1. Divide")
def test1(x,y):
if y == 0:
return "The result is undefined"
else:
return x/y
num1=int(input("First: "))
num2=int(input("Second: "))
menu()
answer=int(input("Choose: "))
while answer != 0:
if answer == 1:
print()
print(" The result is", test1(num1,num2))
print()
menu()
answer=int(input("Choose: "))
When I run the program and input a y value of 0, the result prints twice. How do I make it print once only then return to menu? Thank you
This is not a bug in your code,
you can simply Change your zero condition to this:
if y == 0:
return "undefined"

There's an issue somewhere in my Python code.. I can't find where it's at

I don't know what's wrong with it.. I run it and I'm able to input a number but then it stops working. It says, "TypeError: play_game() missing 1 required positional argument: 'limit.' But I'm not sure what's missing there??
#!/usr/bin/env python3
import random
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess >= number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game()
again = input("Play again? (y/n): ")
print()
print("Bye!")
# if started as the main module, call the main function
if __name__ == "__main__":
main()
You have defined your play_game function to take limit as a parameter, but when you call this function in your main loop, you don't supply a value in the brackets of play_game().
You could either try adding that limit value that you've specified by calling it like
play_game(25)
Or, based on your code, since you're asking the user to provide a limit, call it like:
play_game(limit)
Or, if you want to be able to call play_game() without setting a limit, then change your play_game definition line to something like:
def play_game(limit=25):
Which will set a default value of 25 whenever that function is called without supplying the limit value.
Yes, play_game() needs the parameter limit. I've done a quick check on your code, and there is some additional problem
the count variable isn't initialized
you calculate the random number in every step
guess > number should be used instead of guess >= number
Here is the fixed code, it works for me. I hope it will be usefull:
import random
count = 0
number = -1
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
global number, count
if number == -1:
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess > number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(limit)
again = input("Play again? (y/n): ")
print()
print("Bye!")
In your main you are calling playgame() without providing a limit as an argument.
Your main should look something like
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(10)
again = input("Play again? (y/n): ")
print()
print("Bye!")

How do i make it so that when the user enters a number to check if it's odd or even and then the code asks the user to input 1 or 2 again

print ("[1] Identify, [2] quit")
user = int(input())
while (user) == 1:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
if (user) == 2:
quit()
The code is firstly asking the user to input 1 or 2, the code will then ask the user to input a number and then the code will say if the number is odd or even but I'm trying to make it so that after the user has input the number to check if it's odd or even, it then asks to enter 1 or 2 again.
You need to put your first two lines inside the loop. Here's one way to do it:
while True:
print("[1] Identify, [2] Quit")
user = int(input())
if user == 1:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is even".format(num))
else:
print("{0} is odd".format(num))
elif user == 2:
break
quit()
The best way to do it would be to put it all inside a while loop and exit if 2 is entered:
while True:
user = int(input("[1] Identify, [2] quit "))
if user==1:
num = int(input("Enter a number: "))
if not num%2:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
else:quit()

Categories