How do I use in input from one function in another? - python

So I'm writing a higher or lower game and I am experimenting with functions. I have a couple functions in my code but I need 2 in particular to kind of work with each other in order for my code to run properly (my code isn't finished yet so there are still a lot of mechanics I need to add).
def winner(opponent1, opponent2):
opponent1_flwrs = opponent1['follower_count']
opponent2_flwrs = opponent2['follower_count']
score = 0
if opponent1_flwrs > opponent2_flwrs:
if higher_or_lower == "A" or higher_or_lower == "a":
score += 1
return "You're right! Current score: " + score
else:
clear()
print(art.logo)
return "Sorry, that's wrong. Final score: " + score
elif opponent2_flwrs > opponent1_flwrs:
if higher_or_lower == "B" or higher_or_lower == "b":
score += 1
return "You're right! Current score: " + score
else:
clear()
print(art.logo)
return "Sorry, that's wrong. Final score: " + score
def game(opponent1, opponent2:
"""
Contains the code necessary for the game to begin and will continue to execute
as long as the user is the winner
"""
print(art.logo)
print(f"Compare A: {opponent1['name']}, a {opponent1['description']}, "
f"from {opponent1['country']}")
print(art.vs)
print(f"Against B: {opponent2['name']}, a {opponent2['description']}, "
f"from {opponent2['country']}")
higher_or_lower = input("Who has more followers A or B? ")
I have a file that contains the data so the values for opponent1, opponent2, and opponent1_flwrs, opponent2_flwrs are taken from that data.
I want the higher_or_lower input from the game function to be able to do the same thing in the winner function and have the same value if that makes sense. Also later on I'm going to add a while loop that's going to call on these functions continuously until the user has lost.

firstable, sorry for the bad English, but I think that you can just pass the higher_or_lower variable to the winner function like this:
def winner(opponent1, opponent2, chosen_option, current_score):
chosen_option= chosen_option== 'a'
correct_option= opponent1['follower_count']> opponent2['follower_count']
if chosen_option== correct_option:
score += 1
return "You're right! Current score: " + score
else:
clear()
print(art.logo)
return "Sorry, that's wrong. Final score: " + score
def game(opponent1, opponent2, score):
"""
Contains the code necessary for the game to begin and will continue to execute as long as the user is the winner
"""
print(art.logo)
print(f"Compare A: {opponent1['name']}, a {opponent1['description']}, from {opponent1['country']}")
print(art.vs)
print(f"Against B: {opponent2['name']}, a {opponent2['description']}, from {opponent2['country']}")
higher_or_lower = input("Who has more followers, A or B? ").lower()
winner(opponent1, opponent2, higher_or_lower)
in the main loop you have to declare the score variable so you don't reset it every time you call the function

Related

Why is the correct answer printing both score = 3 and score = 1?

When you enter the correct answer ("Bad Guy"), it prints score = 3 and score = 1 at the same time? How do I prevent this so after getting it right in one attempt, it displays (and saves) score = 3, and after getting it right on the second attempt, it displays (and saves) the score as 1? By the way, if the player guesses correctly the first time, they gain 3 points.If they get it wrong, they try again. If they guess correctly the second time, they only gain 1 point. If they still get it wrong, the game ends. Please explain what's wrong and try to fix this problem please.
Here's the code I'm using for this:
score = 0
print("Round 1:")
with open('songs.txt') as songs_list:
song_name = songs_list.readline()
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score+=3
print("Correct! Score = 3")
else:
print("Incorrect! Try again.")
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score +=1
print("Correct! Score = 1")
else:
print("Incorrect! Unlucky, you lost. I hope you enjoyed playing!")
import sys
sys.exit()
You should indent the second set of if-else statements. This means the second set will only occur if the first answer is wrong.
score = 0
print("Round 1:")
with open('songs.txt') as songs_list:
song_name = songs_list.readline()
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score+=3
print("Correct! Score = 3")
else:
print("Incorrect! Try again.")
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score +=1
print("Correct! Score = 1")
else:
print("Incorrect! Unlucky, you lost. I hope you enjoyed playing!")
import sys
sys.exit()
Your most immediate problem is that you never print score. Your only reports to the user are the literal strings Score = 3 and Score = 1. You'll need something like
print("you got 3 more points; new score =", score)

Self teaching python. Having trouble with score incrementing after each round

TL:DR Trying to set up a scoring system, it doesn't seem to go up when you get than answer right
As the title says I'm teaching myself python, thus this is only the second code I have written (hints in why I'm learning python). I'm more than happy to take criticism on everything from syntax to how to better comment. With that being said, let's get to my issue.
This is a small guessing game. The book I'm reading taught the "for guessTaken" and subsequent code. My problem is in one small aspect of my code. The scoring system won't increment.
I set up the code in the for loop called games then try to have it display at that start of each round and go up with each correct guess. However, it will display 0 for the first few rounds then it will show 2 ( or whatever your current score is I think...). I think the problem is I'm calling the score +1 int in an if statement but I've moved the code around and can't figure it out.
I am aware that it's not beautiful! There are also a few bugs (number of games played isn't what you enter.)Right now I'm only working on the scoring system.
#this is a guess the number game.
import random
#Get's user's name
print("Hello. Welcome to Print's guessing game. Please enter your name: ")
userName = input()
#askes if they are ready
print("Are you ready to play " + userName + "?")
ready = input().lower()
if ready == 'yes' :
print("Let's get started")
else:
while ready != 'yes':
print("Let me know when you are ready")
ready = input().lower()
#Game start
#number of games
games = int(input("How many games would you like to play?"))
if games >= 1:
print("Let's get started")
for games in range (int(games), 1, -1):
while games != 1:
print("I am thinking of a number between 1 and 20 ")
secretNumber = random.randint(1, 20)
score = 0
print("Current score: " + str(score))
print("Debug: " + str(secretNumber))
for guessTaken in range (7, 1, -1):
print("you have " + str(guessTaken - 1 ) + " guesses left")
guess = int(input())
if guess < secretNumber:
print("Your guess is to low. Please guess again")
elif guess > secretNumber:
print("Your guess is too high. Maybe something a little lower?")
else:
break # This conditon is for the right guess.
if guess == secretNumber:
print("good Job " + userName + "! you guessed the number right!")
score = int(score + 1)
print("your score is " + str(score))
games = int(games - 1)
else:
print("Nope, the number I was thinking of was " + str(secretNumber))
print("you have " + str(games) + " games left")
elif games == 0:
while games == 0:
print("Would you like to exit? Yes or No ")
exit = input().lower()
if exit == 'yes':
quit()
else:
games = int(input("How many games would you like to play?"))
else:
print("wtf")
Your score variable is being initialized to zero every time your code goes through the while loop. If you want it to track the total score for all of the games, initialize it right after your print("Let's get started"). This will reset their score whenever they tell you how many games they want to play.
If you don't want their score to reset until they quit your program, you will have to initialize it at the beginning of your program. Up by your import random would work well.

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

Python - Sorting file highest to lowest and alphabetically

I have created an arithmetic code, that asks the user 10 questions, and then stores their name and score in a database e.g. C:\class1.txt and I'm now at the stage, where I should be able to sort the file containing the name and the score of multiple pupils from each individual class, in both highest to lowest (scores) and alphabetically. The program should ask a question at the end of the code, asking the teacher if they want it sorted alphabetically or highest to lowest by score. They should also be able to pick the class they want sorted, and it should be printed.
I am asking for guidance on this, I do not want to cheat, I am just now clueless at this stage; with a teacher that is useless.
Thanks in advance
import random
USER_SCORE = 0
questions = 0
classnumber = ("1","2","3")
name1= input("Enter Your Username: ")
print("Hello, " + name1)
print(" Welcome to the Arithmetic Quiz")
classno = input("What class are you in?")
while classno not in classnumber:
print("Enter a valid class")
print("ENTER ONLY THE NUMBER n\ 1 n\ 2 n\3")
classno=input("What class are you in?")
while questions <10:
for i in range(10):
num1=random.randint(1,10)
num2=random.randint(1,10)
on=random.choice("*-+")
multiply=num1*num2
subtract=num1-num2
addition=num1+num2
if on == "-": #If "-" or subtract is randomly picked.
print("MAKE SURE YOU ENTER A NUMBER OTHERWISE YOU WILL BE MARKED DOWN")
questions+=1
print(" Question" ,questions, "/10")
uinput=input(str(num1)+" - "+str(num2))
if uinput == str(subtract):
USER_SCORE+=1
print(" Correct, your USER_SCORE is: " ,USER_SCORE,)
else:
print (" Incorrect, the answer is: " +str(subtract))
USER_SCORE+=0
if on == "+":
print("MAKE SURE YOU ENTER A NUMBER OTHERWISE YOU WILL BE MARKED DOWN")
questions+=1
print(" Question",questions, "/10")
uinput=input(str(num1)+" + "+str(num2))
if uinput == str(addition):
USER_SCORE+=1
print(" Correct, your USER_SCORE is: ",USER_SCORE,)
else:
print(" Incorrect, the answer is: " +str(addition))
USER_SCORE+=0
if on == "*":
print("MAKE SURE YOU ENTER A NUMBER OTHERWISE YOU WILL BE MARKED DOWN")
questions+=1
print(" Question",questions, "/10")
uinput=input(str(num1)+" * "+str(num2))
if uinput == str(multiply):
USER_SCORE+=1
print(" Correct, your USER_SCORE is: " ,USER_SCORE,)
else:
print(" Incorrect, the answer is: " +str(multiply))
USER_SCORE+=0
if USER_SCORE >9:
print("Well done," ,name1, "your score is" ,USER_SCORE, "/10")
else:
print(name1," your score is " ,USER_SCORE, "/10")
def no1():
with open("no1.txt", 'a')as file:
file.write(str(name1)+" achieved a score of: "+str(USER_SCORE)+"/10 \n")
def no2():
with open("no2.txt", 'a')as file:
file.write(str(name1)+" achieved a score of "+str(USER_SCORE)+"/10 \n")
def no3():
with open("no3.txt", 'a')as file:
file.write(str(name1)+" achieved a score of "+str(USER_SCORE)+"/10 \n")
if classno=="1":
no1()
if classno=="2":
no2()
if classno=="3":
no3()
#crclayton
I found this for alphabetical sorting, however, I still don't know how to sort the file from highest to lowest
viewclass= input("choose a class number and either alphabetically, average or highest?")
if viewclass=='1 alphabetically':
with open('class1.txt', 'r') as r:
for line in sorted(r):
print(line, end='')
elif viewclass=='2 alphabetically':
with open('class2.txt', 'r') as r:
for line in sorted(r):
print(line, end='')
elif viewclass=='3 alphabetically':
with open('class3.txt', 'r') as r:
for line in sorted(r):
print(line, end='')
As I said in the comment, in order to code you need to be able to break your problem into smaller components. Each of those smaller problems should be their own function. It'll be easier to keep track of things and solve smaller problems.
Here are some examples of the sort of functions you should make. I can't stress enough that your questions on S.O. should be about those individual problems, not wanting to know generally how to do things.
Try to fill in the blanks of this structure.
import random
def get_score():
# here do your code to calculate the score
score = random.randint(0,10)
return score
def write_list_to_file():
# for each item in list, write that to a file
pass
def sort_list_alphabetically(unsorted_list):
# figure out how to sort a list one way
return sorted_list
def sort_list_numerically(unsorted_list):
# figure out how to sort a list the other way
return sorted_list
def get_sort_method_from_user():
# get input however you want
if soandso:
return "Alphabetical"
else:
return "Numerical"
def get_user_name():
# do your stuff
return name;
questions = 0
list_of_scores = []
while questions < 10:
name = get_user_name();
user_score = get_score();
output_line = name + " got a score of " + user_score
list_of_scores.append(output_line)
sort_method = get_sort_method_from_user();
if sort_method == "Alphabetical":
new_list = sort_list_alphabetically(list_of_scores)
else:
new_list = sort_list_numerically(list_of_scores)
write_list_to_file(list_of_scores)

Inputting scoring (python 2.7.5)

I'm having trouble inputting scoring in my python quiz code. Here is the script:
#This is the Test script for )TUKT(, Developed by BOT.
print ""
print "Welcome to the Ultimate Kirby Test."
print ""
begin = (raw_input("Would you like to begin?:"))
if begin == "yes":
print ""
print "Alright then! Let's start, shall we?"
print "Q1. What color is Kirby?"
print "1) Black."
print "2) Blue."
print "3) Pink."
print "4) Technically, his color changes based on the opponent he swallows."
choice = input("Answer=")
if choice ==1:
print "Incorrect."
print ""
elif choice ==2:
print "Incorrect."
print ""
elif choice ==3:
print "Tee hee.... I fooled you!"
print ""
elif choice ==4:
score = score+1
print "Well done! You saw through my trick!"
print ""
elif choice > 3 or choice < 1:
print "That is not a valid answer."
print ""
print "Well done! You have finished my test quiz."
print("Score:")
print ""
#End of Script
The error always says
score = score+1 is not defined.
I did not get anywhere researching.
Thanks! Help is very much appreciated!
You forgot to define a variable called score. You can't reference a value that doesn't exist!
Just declare it at the start:
score = 0
In the line score = score + 1, Python goes: 'so I need to create a variable called score. It contains the value of score, plus 1.' But score doesn't exist yet, so an error is thrown.
The varibale score has never been defined. Insert score = 0 as first line of your scirpt.

Categories