How to extract numbers from csv file into variable - python

I want to make a highscore in a game on python - todo this i've realised I have to use an external file. I want it to extract the numbers located in the file and save them as a variable. It will then compare it to the users score and if it's bigger it will write the new high score to the file
I've been googling for days with no luck.
while theo >= 0 and theo <=9:
theo = theo + 1
x = (random.randint(0, 12))
y = (random.randint(0, 12))
print("Your sum is: " ,y,"x ",x)
answer = input("What is the answer?: ")
while len(answer) == 0:
answer = input("What is the answer?: ")
an = (x*y)
if int(answer) == (an):
print("Well done - you were correct ")
score = score + 1
elif int(answer) != (an):
print("Sorry, you were wrong. The correct answer was " ,an)
if theo == (10):
print("The quiz has finished. your score is ",score)
again = input("Do you want to play again? (Y/N)")
gamesplayed = gamesplayed + 1
if again == ("Y") or again == ("y"):
theo = 0
timesplayed = timesplayed + 1
elif again!=("y") or again!=("Y"):
print("well done your final score was ",score," you played ",timesplayed," times")
I want it to do above

I personally prefer to use dataclass CSV whenever I work with CSV files. You just need to type the column as integer (you do that by typing dataclass attribute as int)
It is a nice clean way to convert CSV rows to python objects. The only restriction is that you need to use python3.7 or higher.

Related

Using Python to make a quiz from a text file

I'm learning Python, and I need to make a mini quiz. The questions and answers are in a text file (called textfile.txt), each on its own line. At the end of the quiz, it will tell the user their score out of three.
I can get my quiz to print out the first question, and when I try inputting an answer no matter what I put (correct answer or incorrect answer), it'll tell me it's incorrect.
In the text file I have the following:
whats 1+1
2
whats 2+2
4
whats 3+3
6
And here is what I have in my .py file:
questions = open("textfile.txt", "r")
content = questions.readlines()
userScore = 0
for i in range(1):
print(content[0])
answer = input("What's the answer: ")
if answer == content[1]:
print("Correct")
userScore + 1
else:
print("Incorrect")
print(content[2])
answer = input("What's the answer: ")
if answer == content[3]:
print("Correct")
userScore + 1
else:
print("Incorrect")
print(content[4])
answer = input("What's the answer: ")
if answer == content[5]:
print("Correct")
userScore + 1
else:
print("Incorrect")
questions.close()
print("You're done the quiz, your score is: ")
print(userScore)
How do I make it read the correct answer and keep track of the users score?
First of all, use .strip() to remove the newline characters. The answers comparison might not always work because of them.
To ask every even row you can use the modulo (%) operator to get the remainder of the current line index after dividing it by two.
If the answer is correct we add 1 to the corrent_answer_count variable that we print in the end.
questions = open(r"textfile.txt", "r")
content = [line.strip() for line in questions.readlines()]
questions.close()
corrent_answer_count = 0
for i in range((len(content))):
if i % 2 == 0:
print(content[i])
answer = input("What's the answer: ")
if answer == content[i + 1]:
print("Correct")
corrent_answer_count += 1
else:
print("Incorrect")
print("Correct answer count: " + str(corrent_answer_count))

How to make if statement check each for loop statement for valid input

import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for (computer_choice) in range(1,6):
user_choice = input("What number between 1 and " + max_value + " do you choose? ")
if user_choice == computer_choice:
print("Thank you for playing. ")
Needs to give the user 5 chances to give the computer_choice before failing. For loop is required.
You can add a counter which will keep the track of the number of attemps that user has made so far.
Also need to convert user input from string to int type.
import random
max_value = int(input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? "))
computer_choice = random.randint(1, int(max_value))
count = 0
for (computer_choice) in range(1,6):
user_choice = int(input("What number between 1 and " + max_value + " do you choose? "))
count += 1
if user_choice == computer_choice:
print("Thank you for playing. ")
if count==5:
print("you have reached maximum attempt limit")
exit(0)
Run the for loop with separate variable then computer_choice. Also add eval to input statement as it gives string to conert the user_choice to integer and add a break statement in if user_choice == computer_choice to end the program, rest should work fine.
import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for (i) in range(1,6):
#input takes string convert choice to int using eval
user_choice = eval(input("What number between 1 and " + max_value + " do you choose? "))
if user_choice == computer_choice:
print("Thank you for playing. ")
break
if(i==5):
print("Sorry, maximum number of tries reached.")
One of the approach:
import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for i in range(1,6):
user_choice = input("What number between 1 and " + max_value + " do you choose? ")
if int(user_choice) == int(computer_choice):
print("Right choice. Thank you for playing. ")
break
elif(i == 5):
print ("Sorry, maximum attempts reached...")
break
else:
print ("Oops, wrong choice, pls choose again...")
Output:
I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? 5
What number between 1 and 5 do you choose? 1
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 3
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 4
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 5
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 6
Sorry, maximum attempts reached...

I need help on a python guessing game

I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")

I'm trying to create a number guessing game but when I run this it keeps running the while loop and doesnt break out [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I'm trying to create a number guessing game but when I run this it keeps running the while loop and doesnt break out. (very new to python by the way) thanks!
from random import randint
name1 = input("What is Player One's first name? ")
name2 = input("What is Player Two's first name? ")
cnumber = randint(1,25)
guess1 = ""
guess2 = ""
times_guessed1 = 0
times_guessed2 = 0
while guess1 != cnumber and guess2 != cnumber:
guess1 = input(name1 + " guess a number between 1 and 25: ")
times_guessed1 += 1
guess2 = input(name2 + " guess a number between 1 and 25: ")
times_guessed2 += 1
if guess1 == cnumber:
print (name1, "wins!")
print ("You guessed,", times_guessed1, "times.")
elif guess2 == cnumber:
print (name2, "wins!")
print ("You guessed,", times_guessed2, "times.")
input() returns a str.
randint(1,25) returns an int.
When it compares, '2' with 2, it will be false in python.
Solution: convert the input to int like below.
guess1 = int(input(name1 + " guess a number between 1 and 25: "))
guess2 = int(input(name2 + " guess a number between 1 and 25: "))
input will return a string use int(input()) to covert to int to be able to match with randint
cnumber is an int, but guess1 and guess2 are strings, so they are never equal, because their types are different. The easiest would be to convert cnumber to a string: cnumber = str(randint(1,25)).

Guessing algorithm does not seem to work, guessing number by Python

I am struggling with some simple algorithm which should make python guess the given number in as few guesses as possible. It seems to be running but it is extremely slow. What am I doing wrong. I have read several topics already concerning this problem, but can't find a solution. I am a beginner programmer, so any tips are welcome.
min = 1
max = 50
number = int(input(("please choose a number between 1 and 50: ")))
total = 0
guessed = 0
while guessed != 1:
guess = int((min+max)/2)
total += 1
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
min = guess + 1
elif guess < number:
max = guess - 1
Thanks
ps. I am aware the program does not check for wrong input ;)
Your logic is backwards. You want to lower the max when you guess too high and raise the min when you guess too low. Try this:
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
max = guess - 1
elif guess < number:
min = guess + 1
Apart from having the logic backwards, you should not be using min and max as variable names. They are python functions. You can also use while True and break as soon as the number is guessed.
while True:
guess = (mn + mx) // 2
total += 1
if guess == number:
print("The number has been found in {} guesses!".format(total))
break
elif guess < number:
mn = guess
elif guess > number:
mx = guess
You will also see by not adding or subtracting 1 from guess this will find the number in less steps.
from random import randint
print('choose a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla python wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break

Categories