Python Loop until condition is met - python-3.x

I'm trying to write a program for an assignment and for one section, I need to create division questions. I need it so that when the random numbers are picked, the first number will always be larger than the second number. the function that I have created does most of the work but I cant seem to figure out how to get it to loop until the condition is met. In the code, I have tried using a while loop but when I run it, I still get the first number as being a lower number.
Does anyone have any recommendations as to how I could do this?
import random
import time
score = 0
Addition = range(1, 20)
Multiplication = ['1', '2', '3', '4', '5']
Division = ['1', '2', '4', '6', '8', '10']
def additionfunc():
for x in range (0, 4):
a = random.choice(Addition)
b = random.choice(Addition)
c = float(a) + float(b)
print("What is", a," plus", b)
answer = int(input("Please enter your answer: "))
if answer == c:
print("Correct")
print("Plus 10 points")
global score
score = score + 10
print()
time.sleep(1)
else:
print("Incorrect")
print("No points added")
print()
time.sleep(1)
print("Well done, your score was", score)
print()
mainmenu()
def multiplicationfunc():
for x in range (0, 4):
a = random.choice(Multiplication)
b = random.choice(Multiplication)
c = float(a) * float(b)
print("What is", a," multiplied by", b)
answer = int(input("Please enter your answer: "))
if answer == c:
print("Correct")
print("Plus 10 points")
global score
score = score + 10
print()
time.sleep(1)
else:
print("Incorrect")
print("No points added")
print()
time.sleep(1)
print("Well done, your score was", score)
print()
mainmenu()
def divisionfunc():
for x in range (0,4):
a = random.choice(Division)
b = random.choice(Division)
c = float(a) / float(b)
print("What is", a, "divided by", b)
answer = float(input("Please enter your answer: "))
if answer == c:
print("Correct")
print("Plus 10 points")
global score
score = score +10
print()
time.sleep(1)
else:
print("Incorrect")
print("No points added")
print()
time.sleep(1)
print("Well done, your score was", score)
print()
mainmenu()
def mainmenu():
print("Welcome to the Numeracy Game")
print("1. Addition")
print("2. Multiplication")
print("3. Division")
print("Score =", score)
time.sleep(2)
Genre = int(input("Enter the value for the mode:"))
print()
if Genre == 1:
additionfunc()
elif Genre == 2:
multiplicationfunc()
elif Genre == 3:
divisionfunc()
mainmenu();

I hope this is what you need:
division= ['1', '2', '4', '6', '8', '10'] #[1,2,4,6,8,10]
# you could also use random.randint(start, stop)
#if you only want even ints you can use random.randint(0,10,2)
a = random.choice(division) # random.ranint(0,10)
b = random.choice(division) # random.randint(0,10)
if b == 10:
#prevents b from being the biggest number which would result in an endless loop
b = random.choice(division)
while a < b or a==b: # if a is smaller or same as b change a
a = random.choice(division)
else:
# it would be easier to use ints instead string and only convert
# them to string in your print statemnt
c = float(a)/float(b)

Related

highscore and keeping score

#This is a for loop to get the score of a player playing a riddle game
#It runs and loops but it's not calculating the score properly. #There're 6 riddles and 3 rounds. #Say I get 4/6 correct my score is 20 but it's displaying 3.0 instead. how do I get a precise answer while importing the math function?
for i in range(6):
print(riddles[i])
#
userchoice = input("Enter A, B, C, or D: ")
if userchoice.upper() == answers[i]:
print("That's Correct")
score += 5
print(f" {score}")
else:
print("That's Incorrect")
score -= 1
print(f"{score}")
total = total + int(score)
highScoreEasy = print(f"Here is your score: {int(total/score)} !!!!!")
print()
Shouldn't it just be a simple sum?
riddles = []
answers = []
riddle_score = 5
total = len(riddles) * riddle_score
score = 0
for i, riddle in enumerate(riddles):
print(riddle)
userchoice = input("Enter A, B, C, or D: ")
if userchoice.upper() == answers[i]:
print("That's Correct")
score += riddle_score
else:
print("That's Incorrect")
print(f"Here is your score: {score}/{total}!")

Number Guessing game Computer Playing

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

Code Not Compiling- Unable to figure out Issue

I have been stumped on this for days now and I can seem to figure out what the problem is. I am able to run all of it fine except when I select option 1 on the console menu. I will be able to make through the first inputs and then I get an error every time. Also for some reason when another option is selected, it does not jump to that option, it just starts going the password generator code instead. Any help would be appreciated. Still fairly new to all this.
import math
import sys
import random
import datetime
import string
import secrets
from datetime import date
while 1:
print("\nWelcome to the application that will solve your everday problems!")
print("\nPlease Select an Option from the List Below:")
print("1: To Generate a New Secure Password ")
print("2: To Calculate and Format a Percentage ")
print("3: To Receive the amount of days until Jul 4th, 2025 ")
print("4: To Calculate the Leg of Triangle by using the Law of Cosines ")
print("5: To Calculate the Volume of a Right Circular Cylinder ")
print("6: To Exit the Program ")
choice = int(input("Please enter your Selected Option: "))
if choice == 6:
print("\nThank you for coming, Have a Great Day!")
break
elif choice == 1:
def input_length(message):
while True:
try: #check if input is integer
length = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
if length < 5: #check if password's length is greater then 5
print("Too short password!")
continue
else:
return length
def input_yes_no(message):
while True:
option = input(message).lower()
if option not in ('y', 'n'): #check if user entered y/n (or Y/N)
print("Enter y or n !")
else:
return option
def get_options():
while True:
use_upper_case = input_yes_no("Use upper case? [y/n]: ")
use_lower_case = input_yes_no("Use lower case? [y/n]: ")
use_numbers = input_yes_no("Use numbers? [y/n]: ")
use_special_characters = input_yes_no("Use special characters? [y/n]: ")
options = (use_upper_case, use_lower_case, use_numbers, use_special_characters)
if all(option == 'n' for option in options): #check if all options are 'n'
print("Choose some options!")
elif all(option == 'n' for option in options[:-1]) and options[-1] == 'y':
print("Password can not contain only special characters")
return options
def generate_alphabet(use_upper_case, use_lower_case, use_numbers, use_special_characters):
alphabet = ''
if use_upper_case == 'y' and use_lower_case == 'y':
alphabet = string.ascii_letters
elif use_upper_case == 'y' and use_lower_case == 'n':
alphabet = string.ascii_uppercase
elif use_upper_case == 'n' and use_lower_case == 'y':
alphabet = string.ascii_lowercase
if use_numbers == 'y':
alphabet += string.digits
if use_special_characters == 'y':
alphabet += string.punctuation
def generate_password(alphabet, password_length, options):
use_upper_case = options[0]
use_lower_case = options[1]
use_numbers = options[2]
use_special_characters = options[3]
while True:
password = ''.join(secrets.choice(alphabet) for i in range(password_length))
if use_upper_case == 'y':
if not any(c.isupper() for c in password):
continue
if use_lower_case == 'y':
if not any(c.islower() for c in password):
continue
if use_numbers == 'y':
if not sum(c.isdigit() for c in password) >= 2:
continue
if use_special_characters == 'y':
if not any(c in string.punctuation for c in password):
continue
break
def main():
password_length = input_length("Enter the length of the password: ")
options = get_options()
alphabet = generate_alphabet(*options)
password = generate_password(alphabet, password_length, options)
print("Your password is: ", password)
if __name__ == "__main__":
main()
elif choice == 2:
Num = float(input("Please Enter the Numerator: "))
Denom = float(input("Please Enter the Denomenator: "))
Deci = int(input("Please Enter the Number of Decimal Places You Would Like: "))
Val = Num/Denom*100
Val = round(Val, Deci)
print("\nThe Percentage of the numbers you entered is", Val, "%")
elif choice == 3:
Today = datetime.date.today()
Future = date(2025, 7, 25)
Diff = Future - Today
print("\nTotal numbers of days till July 4th, 2025 is:", Diff.days)
elif choice == 4:
A = int(input("Please Enter angle A: "))
B = int(input("Please enter angle B: "))
Angle = int(input("Please Enter the Angle of the Triangle: "))
c = A*A + B*B - 2*A*B*math.cos(math.pi/180*Angle)
print("\nThe Leg of the Triangle is:", round(c))
elif choice == 5:
Radius = int(input("Please Enter the Radius of the Cylinder: "))
Height = int(input("Please Enter the Height of the Cylinder: "))
Volume = (math.pi*Radius*Radius)*Height
print("\nThe Volume of the Cylinder is:", Volume)

I'm trying to make this program repetitive while using all the functions but cannot seem to get it working

So all I want to create is a loop for this program so that it will be able to be used more than once without re-running through the shell, I would like to also learn how to do this with any program involving functions
Everything
print('Welcome to the prime checker!')
num = int(input("Enter any number between 1 - 5000: "))
def is_prime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(num, "is not prime")
break
else:
print(num, "is prime")
else:
print(num, "is not a prime number")
is_prime(num)
def print_factors(num):
print("The factors of",num,"are:")
for i in range(1, num + 1):
if num % i == 0:
print(i)
print_factors(num)
def main():
choice = "y"
while choice.lower() == "y":
# get input
#num = int(input("Enter any number between 1 - 5000: "))
# see if the user wants to continue
choice = input("Repeat? (y/n): ")
print()
print("Bye!")
if __name__ == "__main__":
main()
print('Finished!')
I just want it to work when you press y and re-run the entire program like its first time
Structure your code. Create functions. Call functions. Respect indentations.
def check_primes():
print('Welcome to the prime checker!')
num = int(input("Enter any number between 1 - 5000: "))
def is_prime(num):
# do checking -your current code makes not much sense
# and does not do what the methodnames imply
# see f.e. https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime
print("Did prime checking")
def main():
choice = "y"
while choice.lower() == "y":
check_primes()
# see if the user wants to continue
choice = input("Repeat? (y/n): ")
if __name__ == "__main__":
main()

TypeError: list indices must be integers, not _io.TextIOWrapper

I am trying to search for a certain number within a Text Document. It reads the file fine, and using the same code later can print fine, but when I tell it to find a certain number in the Text Document it tells me TypeError: list indices must be integers, not _io.TextIOWrapper. I have looked all around but all questions say 'not str' whereas mine says 'not _io.TextIOWrapper'
This is my code (I am going down route 'A' under 'menuOptions'
import time
import linecache
print("Welcome to the League Fixture Manager!")
time.sleep(3)
print("What would you like to do?")
time.sleep(1)
print("Press A to search for a fixture.")
time.sleep(0.1)
print("Press B to view Outstanding fixtures.")
time.sleep(0.1)
print("Press C to display the leader board")
time.sleep(0.1)
print("Or press Q to quit, this will exit the application.")
time.sleep(0.1)
menuOptions = input("What would you like to do? A, B, C, or Q.")
if menuOptions == 'A':
print("Please enter the fixture number you are looking for... ")
fixtureQuestion = input(int())
fixtureQuestion = int(fixtureQuestion)
fixtureQuestion = fixtureQuestion - (1)
time.sleep(3)
if fixtureQuestion < 1:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
elif fixtureQuestion > 190:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
else:
searchData = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\\firesideFixtures.txt")
lines = searchData.readlines()
print(lines[searchData])
time.sleep(1)
print("Return to menu?")
menuReturn = input("Y or N")
if menuReturn == 'Y':
print("Press B to view outstanding fixtures.")
time.sleep(0.1)
print("Press C to display the leaderboard")
time.sleep(0.1)
print("Or press Q to exit the application.")
time.sleep(0.1)
print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
time.sleep(0.1)
menuOptions2 = input("What would you like to do? B, C, or Q?")
if menuOptions2 == 'B':
print("~~incomplete~~")
elif menuOptions2 == 'C':
print("~~incomplete~~")
elif menuOptions2 == 'Q':
print("Exiting Application...")
time.sleep(1)
exit()
elif menuReturn == 'N':
print("Exiting Application...")
time.sleep(2)
exit()
elif menuOptions == 'B':
print("Searching for fixtures...")
time.sleep(3)
data = [line.strip() for line in open(r"Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideFixtures.txt").readlines()]
for line in data:
print(line)
time.sleep(1)
print("Return to menu?")
menuReturn = input("Y or N")
if menuReturn == 'Y':
print("Press A to search for a fixture")
time.sleep(0.1)
print("Press C to display the leaderboard")
time.sleep(0.1)
print("Or press Q to exit the application.")
time.sleep(0.1)
print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
time.sleep(0.1)
menuOptions2 = input("What would you like to do? B, C, or Q?")
if menuOptions2 == 'A':
fixtureQuestion = input(int("Please enter the fixture number you are looking for... "))
fixtureQuestion = fixtureQuestion - 1
time.sleep(3)
if fixtureQuestion < 1:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
elif fixtureQuestion > 190:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
else:
searchData = open(r"Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideFixtures.txt").readlines()
lines = searchData.readlines()
print(lines[fixtureQuestion])
time.sleep(1)
print("Return to menu?")
menuReturn = input("Y or N")
if menuReturn == 'Y':
print("Press C to display the leaderboard")
time.sleep(0.1)
print("Or press Q to exit the application.")
time.sleep(0.1)
print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
time.sleep(0.1)
menuOptions2 = input("What would you like to do? B, C, or Q?")
if menuOptions2 == 'C':
print("~~incomplete~~")
elif menuOptions2 == 'Q':
print("Exiting Application...")
time.sleep(1)
exit()
elif menuReturn == 'N':
print("Exiting Application...")
time.sleep(2)
exit()
elif menuOptions2 == 'Q':
print("Exiting Application...")
time.sleep(1)
exit()
elif menuOptions == 'C':
while RetryForC == "Yes":
RetryForC == "No"
fireRead = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideResults.txt")
for line in fireRead:
fireRead = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideResults.txt")
InfoOne = line.split(',')[0]
InfoTwo = line.split(',')[1]
InfoThree = line.split(',')[2]
InfoFour = line.split(',')[3]
PointCounter = int(line.split(',')[2])
PointCounter = PointCounter * 3
fireRead.close()
print("Player:",InfoOne,"Has played:",InfoTwo,", has won:",InfoThree,", has lost:",InfoFour,", and therefore has",PointCounter,"many points.")
print("Retry?")
RestForC = str(input("Yes/No "))
print("The program will now close...")
time.sleep(5)
exit()
elif menuOptions == 'Q':
print("Exiting Applicaion...")
time.sleep(2)
exit()
And this is my result:
Welcome to the League Fixture Manager!
What would you like to do?
Press A to search for a fixture.
Press B to view Outstanding fixtures.
Press C to display the leader board
Or press Q to quit, this will exit the application.
What would you like to do? A, B, C, or Q.A
Please enter the fixture number you are looking for...
016
Traceback (most recent call last):
File "E:\Python\Python Work\League\League3.py", line 33, in <module>
print(lines[searchData])
TypeError: list indices must be integers, not _io.TextIOWrapper
What can I do to fix this?
This line:
print(lines[searchData])
Doesn't make any sense. Indices of a list must be integers, so you can do:
>>> my_list = [1, 2, 3]
>>> my_list[0]
1
lines is a list which contains the lines of the file and search_data is a file object. It looks like you're missing some basic python concepts. Please do read the documentation I pasted in your other question you asked 10 minutes ago!

Resources