Can't get value from input - python

I'm trying to make a guessing game with three questions and three guesses total but I can't get the value from the inputs so I can't progress any further. Rough draft for my code
guesses = 3
def guess():
if guesses >= 0:
alive = True
else:
print("You Failed")
Q1 = "What is 1+1"
Q2 = ""
Q3 = ""
def retry():
input("Wrong Answer Try Again")
def questions():
Q1 = input("What is 1+1")
def answer():
if Q1 == "2":
print("Q2")
else:
retry()
if retry() == 2:
print("Q2")
questions()
answer()
I've tried using lists functions if statements but I can't get the value of the inputs no matter what as its always a local variable.

Here's a simple approach to this problem.
The crucial part is the list of 2-tuples. Each tuple maintains a question and the correct answer to that question. By adding more questions and answers to the list your program can become more elaborate without having to change anything else in the code.
Something like this:
Questions = [("What is 1+1", "2"), ("What is 2+2", "4"), ("What is 3+3", "6")]
score = 0
TRIES = 3
for q, a in Questions:
for _ in range(TRIES): # number of tries allowed
if input(f'{q}? ').lower() == a.lower() :
score += 1
print('Correct')
break
else:
print("Incorrect please try again")
else:
print('Maximum tries exceeded')
print(f'Your final score is {score}')

Related

How to store return value of function into a variable and subsequently use it in while loop?

Hi I'm literally new to python and programming in general ---- a complete beginner. I'm 2 hours in in some youtube python beginner course and he made some guessing game to demonstrate the application of a while loop.
I replicated it so I can practice coding but I made some modifications to it on my own.
He made the guessing game where you can have 3 tries to guess the word using a combination of while loop, if and else functions, and Boolean variable.
My version is similar but I wanted it to have a counter where you are informed of how many tries you have left.
secret_word = "Aircraft"
answer = ""
guess_count = 0
guess_limit = 3
remaining_guess = guess_limit - guess_count
while answer != secret_word and remaining_guess != 0:
if guess_count < guess_limit and remaining_guess == 3:
def re_guesses(remaining_guess_1):
print("You have " + str(remaining_guess_1) + " remaining guesses")
int(remaining_guess_1)
return remaining_guess_1
remaining_guess = re_guesses(remaining_guess)
def guess_word(guess_count_1):
answer = input("Enter answer: ")
guess_count_1 += 1
return guess_count_1
guess_count = guess_word(guess_count)
elif guess_count < guess_limit and remaining_guess == 2:
def re_guesses(remaining_guess_1):
print("You have " + str(remaining_guess_1) + " remaining guesses")
int(remaining_guess_1)
return remaining_guess_1
remaining_guess = re_guesses(remaining_guess)
def guess_word(guess_count_1):
answer = input("Enter answer: ")
guess_count_1 += 1
return guess_count_1
guess_count = guess_word(guess_count)
else:
def re_guesses(remaining_guess_1):
print("You have " + str(remaining_guess_1) + " remaining guesses")
int(remaining_guess_1)
return remaining_guess_1
remaining_guess = re_guesses(remaining_guess)
def guess_word(guess_count_1):
answer = input("Enter answer: ")
guess_count_1 += 1
return guess_count_1
guess_count = guess_word(guess_count)
if remaining_guess == 0:
print("You lost!!")
else:
print("I can't believe you won!")
I tried to store the return value (remaining_guess_1) again to the remaining_guess as I converted into an integer. I did the same to the return value of guess_count_1 and stored it in the orginal variable of guess_count.
I was expecting the result to be that the counter will subtract 1 try after every wrong answer but instead it is stuck to "You have 3 remaining guesses".
Please someone explain what I'm doing wrong and how to make it work. Thank you.
I tried out your code and found some ways to simplify the while loop process so that you don't have all of those "if/else" blocks. Moving around the definitions and the "while" loop, I came up with the following code.
secret_word = "Aircraft"
answer = ""
guess_limit = 3
remaining_guesses = guess_limit
def re_guesses(remaining_guess_1):
print("You have " + str(remaining_guess_1) + " remaining guesses")
int(remaining_guess_1)
def guess_word():
answer = input("Enter answer: ")
return answer
re_guesses(remaining_guesses)
while remaining_guesses != 0:
answer = guess_word()
if (answer == secret_word):
break
else:
print(answer, ' was not the correct answer')
remaining_guesses -= 1
re_guesses(remaining_guesses)
if remaining_guesses == 0:
print("You lost!!")
else:
print("I can't believe you won!")
The function definitions and the initial prompt are moved before the while loop is called. Also, instead of returning the guess count, I revised the "guess_word" function to return the entered answer. Then based on the correctness (or incorrectness) of the answer, the loop is exited with a "break" call if the answer was correct, or the remaining guess count gets decremented if incorrect. If the user answers correctly before the remaining count hits zero, they are notified that they won. Also, I didn't see a use anymore for the guess count so I removed that variable both from the variable list and from the input parameter for the "guess_word" function.
Go ahead and study the code and see if it meets your needs and provides you with some ideas.
Regards.

How to create a function in Python?

I am new to coding and I am learning python. I’m trying to write a simple program to test my skills, but I’m having some difficulties with it; I want to turn it into a function in order to make the program cleaner, but I get this error: http://prntscr.com/im5pt7
Here is what I want to put inside a function:
name = input(str("\nFull Name: "))
position = input(str("Position at the company: "))
print("\nConfirm Staff Data:\n")
name_confirm = "Name: %s"%(name)
position_confirm = "Position: %s"%(position)
print(name_confirm)
print(position_confirm)
confirmAns = input("Is the information right? (Y/N)")
if confirmAns == "y" or confirmAns == "Y":
message = "\nSearching for %s"%(name)
print(message)
hoursWorked = int(input("Insert hours worked: "))
if hoursWorked <= 0:
print("Please insert a valid number")
elif hoursWorked > 0:
print("\nCalculete Paycheck")
hourRate = int(input("Insert the rate of each hour worked: "))
bonus = input("If a bonus was given insert it here: ")
fine = input("If a fine was given insert it here: ")
print('\n')
payment = hoursWorked*hourRate-int(fine)+int(bonus)
paymentMsg = "Your Payment is: $%d"%(payment)
print(paymentMsg)
elif confirmAns == "n" or confirmAns == "N":
ctypes.windll.user32.MessageBoxW(0, "The software will close to avoid slowness.", "Warning", 1)
else:
print("Please answer with Y or N")
I've tried this but it did not work.
Here is all the code (working but with out the function so I need to copy and paste code): https://pastebin.com/PA9mxMkk
What is happening is that the function as other statements needs to hold it's code into a new indentation level
print('a')
def test(var):
print(var)
not this way
print('a')
def test(var):
print(var)
because this way it will give you the error that you are seeing.
All python code should be indented after the ':' character, in python the indentation should be 4 spaces, or people use the tab key, your code has an issue with indentation which I can't be bothered finding;
for example a 'class'
class this_is_a_class():
#indentation
#code goes here
pass
or a 'for loop' or 'while loop';
numbers = [0,1,2,3,4,5,6,7,8,9]
for number in numbers:
#indentation
print(number)
x = 0
while x < 10:
#indentation
x += 1
print('This is going to print 10 times')
or an 'if statement';
true_boolean = True
if true_boolean:
#indentation
print(True)
or a 'function';
def function():
#indentation
print('You have called a function')
What is actually happening, is python is reading through your code 'Token' by token and 'interpreting' what your code does. But considering you don't know what a function is; gloss over this paragraph.
Now for your question about how functions work. A function is used organize code. You can call a function multiple times, which makes your code more organized and easier to work with, this is why as your code got longer, you ran into this problem; Lets for example say i wanted to print 'hello world' 10 times.
I could write this code on 10 seperate lines;
print("hello world")
print("hello world")
#etc... More chance for error
or I could use a function and call it 10 times;
def say_hello_world():
#indentation
print("hello world")
for each_call in range(0,10):
say_hello_world() #This is the function call
You can also pass 'arguments into a function' for example;
def say_hello(person):
#indentation
print('hello', person)
say_hello('Alex')
Now any words that are in quotations in this answer can be google searched with the word 'python' and you can find out much more about how python works.
I hope this gets you started with python. Although all of these concepts can be used in other programming languages.
The first step which is often difficult in learning python in understanding indentation.
for example.
def hello_world(world):
print("hello ", world)
#your function code goes here.
#you need to indent back to be out of function block.
hello_world("there!")
out: hello there
so in your case it should be like this.
def AnsNo():
name = input(str("\nFull Name: "))
position = input(str("Position at the company: "))
print("\nConfirm Staff Data:\n")
name_confirm = "Name: %s"%(name)
position_confirm = "Position: %s"%(position)
print(name_confirm)
print(position_confirm)
confirmAns = input("Is the information right? (Y/N)")
if confirmAns == "y" or confirmAns == "Y":
message = "\nSearching for %s"%(name)
print(message)
hoursWorked = int(input("Insert hours worked: "))
if hoursWorked <= 0:
print("Please insert a valid number")
elif hoursWorked > 0:
print("\nCalculete Paycheck")
hourRate = int(input("Insert the rate of each hour worked: "))
bonus = input("If a bonus was given insert it here: ")
fine = input("If a fine was given insert it here: ")
print('\n')
payment = hoursWorked*hourRate-int(fine)+int(bonus)
paymentMsg = "Your Payment is: $%d"%(payment)
print(paymentMsg)
elif confirmAns == "n" or confirmAns == "N":
print("working")
else:
print("Please answer with Y or N")
return

Why does my python function return the wrong result?

I'm attempting to create a simple Python game, 'higher or lower'. I'm extremely new to programming so please give me any improvements.
This is what I have so far:
import random
score = 0
def check_choice(lastcard, newcard, userInput):
if newcard >= lastcard:
result = "higher"
else:
result = "lower"
if result == userInput:
print("Correct! \n")
return True
else:
print("Incorrect! \n")
return False
def generate_card():
return str(random.randint(1,13))
def get_user_choice():
choice = input("Please enter 'higher' or 'lower': ")
return choice
def change_score(result):
global score
if result:
score += 1
else:
score -= 1
def play_game():
play = True
card = generate_card()
while play:
print ("Current card is: " + card)
choice = get_user_choice()
if choice == "stop":
play = False
newcard = generate_card()
result = check_choice(card, newcard, choice)
change_score(result)
card = newcard
play_game()
For the most part, everything works correctly. The majority of the game works and returns "Correct!" or "Incorrect!" based on the user's input. However, from time to time it will often report back as incorrect even when the user has chosen the correct choice.
For example, the previous card was 1. When the user entered higher, the next card was a 13 but it reported back as higher being incorrect.
Your cards are being stored as strings:
def generate_card():
return str(random.randint(1,13))
And string comparison isn't want you want here:
>>> '13' > '2'
False
This is a lexicographic comparison, which is what you want when, for example, you're putting things in alphabetical order. But for a higher/lower game, you want a numeric comparison. For that, you want to keep the card as a number, and change get_user_choice so that it converts the user input into a number:
def get_user_choice():
choice = input("Please enter 'higher' or 'lower': ")
return int(choice)
The result is unexpected because the cards are stored with strings, not integers:
def generate_card():
return str(random.randint(1,13))
Strings are compared lexicographical:
>>> 7 < 11
True
>>> "7" < "11"
False

Int is not callable

I have researched this subject, and cannot find a relevant answer, here's my code:
#Imports#
import random
from operator import add, sub, mul
import time
from random import choice
#Random Numbers#
beg1 = random.randint(1, 10)
beg2 = random.randint(1, 10)
#Variables + Welcoming message#
correct = 0
questions = 10
print ("Welcome to the Primary School Maths quiz!!")
print ("All you have to do is answer the questions as they come up!")
time.sleep(1)
#Name#
print("Enter your first name")
Fname = input("")
print ("Is this your name?" ,Fname)
awnser = input("")
if awnser == ("yes"):
print ("Good let's begin!")
questions()
if input == ("no"):
print("Enter your first name")
Fname = input("")
print ("Good let's begin!")
#Question Code#
def questions():
for i in range(questions):
ChoiceOp = random.randint (0,2)
if ChoiceOp == "0":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1*beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "1":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1-beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "2":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1+beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
questions()
If I'm perfectly honest I'm not quite sure what's wrong, I have had many problems with this code that this wonderful site has helped me with, but anyway this code is designed to ask 10 random addition, subtraction and multiplication questions for primary school children any help I am thankful in advance! :D
You have both a function def questions() and a variable questions = 10. This does not work in Python; each name can only refer to one thing: A variable, a function, a class, but not one of each, as it would be possible, e.g. in Java.
To fix the problem, rename either your variable to, e.g., num_questions = 10, or your function to, e.g., def ask_question()
Also note that you call your questions function before it is actually defined. Again, this works in some other languages, but not in Python. Put your def quesitons to the top and the input prompt below, or in another function, e.g. def main().

How to restart a simple coin tossing game

I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.

Categories