I am trying to get the below code to run in Python and I keep getting a error at the return n point. Can someone please look at the code and see where I messed up at?
while True:
n = input(prompt)
try:
n = float(n)
if n < n1 or n > n2:
print('Error. Input was out of range')
else:
break
except:
print('Error. Please enter a number')
return n
def main():
average = 0
count = 0
while(True):
name = input("Please enter a student name or '*' to finish: ")
if name == '*':
break
scores = 0
scores += getPosFloat('Please enter a score for ' + name + ': ', 0, 100)
scores += getPosFloat('Please enter another score for ' + name + ': ', 0, 100)
scores += getPosFloat('Please enter another score for ' + name + ': ', 0, 100)
print('The average score for ' + name+ ' is: %.2f' % (scores/3))
#please give the proper argument
average += getPosFloat('Please enter average score for ' + name + ': ', 0, 100)
count += 1
if count!=0:
print("The class average is: ",(average)/count)
main()
You can't return a value outside a function. (I'm assuming that is all the code you have since that is all you provided )
You are missing your function definition. It looks like you should have
def getPosFloat(prompt, n1, n2):
while True:
n = input(prompt)
try:
n = float(n)
if n < n1 or n > n2:
print('Error. Input was out of range')
else:
break
except:
print('Error. Please enter a number')
return n
before your main() There are still other errors, but that will get you started
Related
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 ')
I have been trying to fix my code and have not been able to do so. My assignment asks me to output the second smallest score along with the student's name. I got the score part right but not the name part. Can you please help me?
n = int(input("Enter number of student: "))
minscore = 1000
i = 1
name = 0
while i <= n:
print ("Please enter the name of student: ",i)
x = str(input())
print ("Please enter the score of student: ",i)
y = int(input())
if y < minscore:
minscore2 = minscore
minscore = y
name = x
elif y < minscore2:
minscore2 = y
i += 1
print ("Second lowest score is",x,"with score",minscore2)
Your problem is you need to save the lowest name with the score.
n = int(input("Enter number of student: "))
minscore = 1000
i = 1
name = ''
name2 = 0
while i <= n:
print ("Please enter the name of student: ",i)
x = str(input())
print ("Please enter the score of student: ",i)
y = int(input())
if y < minscore:
minscore2 = minscore
minscore = y
name2 = name
name = x
elif y < minscore2:
minscore2 = y
name2 = x
i += 1
print ("Second lowest score is",name2,"with score",minscore2)
A better way to go about this is to use lists and the .sort() method
n = int(input("Enter number of students: "))
names_with_scores = []
i = 1
while i <= n:
names_with_scores.append([input("Please enter the name of student number " + str(i) + " : "), input("Please enter the score of student number " + str(i) + " : ")])
# ^^^ Add name and scores to list inside a list ^^^ #
i += 1
def sort_func(e):
return e[1]
names_with_scores.sort(key=sort_func)
# Sorts the list in order of score #
print ("Second lowest score is " + str(names_with_scores[1][0]) + " with a score of " + names_with_scores[1][1])
So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()
I have this code that counts up -3, -2, -1. I have also written another that counts down 3, 2, 1. If the condition is true for another after an input, the program should stop. For Example, The input i enter -3 for negatives it gives -3, -2, -1, if i enter positive number like 3, the result should be 3, 2, 1 in a single combined code.
I have tried to put a function into an if statement of the first function but fails with "NameError: name 'countdown' is not defined" for count down but count up works.
print('+=+=+=+=+=+=+=+=+=+=+=+=+ F1')
#count up
def countup(n):
if (n >= 0):
print('Hello')
if n==0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
else:
print(n)
nth = n + 1
countup(nth)
result = int(input('Enter Number: '))
countup(result)
Have you tried replacing the second else with elif? And fixing the indenting? The resulting code should be this:
print('+=+=+=+=+=+=+=+=+=+=+=+=+ F1')
#count up
def countup(n):
if (n >= 0):
print('Hello')
if n==0:
print('Blastoff!')
elif (condition):
print(n)
countdown(n-1)
else:
print(n)
nth = n + 1
countup(nth)
result = int(input('Enter Number: '))
countup(result)
I solve the problem by doing this code below:
def countup(n):
if (n >= 0):
print('Blastoff 1')
else:
print(n)
nth = n + 1
return countup(nth);
def zero(n):
if (n==0):
print('You have erntered 0 program exiting')
exit()
def countdown(n):
if (n <= 0):
print('explode 2')
else:
print(n)
nth = n - 1
return (countdown(nth))
num = int(input("Enter number: "));
if (num <= 0):
print(countup(num))
elif num == 0:
print(zero(num))
else:
print(countdown(num))
The output is either negative or positive, regardless of what integer you fuse in
import time
total = 0
pos = 0
zeroes = 0
neg = 0
print('This program will add any seven numbers for you')
time.sleep(2)
print()
a = int(input('Please enter the first number: '))
total = total + a
if a > 0:
pos = pos + 1
elif a == 0:
zeroes = zeroes + 1
elif a < 0:
neg = neg + 1
time.sleep(2)
b = int(input('Please enter the second number: '))
total = total + b
if b > 0:
pos = pos + 1
elif a == 0:
zeroes = zeroes + 1
elif a < 0:
neg = neg + 1
time.sleep(2)
c = int(input('Please enter the third number: '))
total = total + c
if c > 0:
pos = pos + 1
elif c == 0:
zeroes = zeroes + 1
elif c < 0:
neg = neg + 1
time.sleep(2)
d = int(input('Please enter the fourth number: '))
total = total + d
if d > 0:
pos = pos + 1
elif d == 0:
zeroes = zeroes + 1
elif d < 0:
neg = neg + 1
time.sleep(2)
e = int(input('Please enter the fifth number: '))
total =total + e
if e > 0:
pos = pos + 1
elif e == 0:
zeroes = zeroes + 1
elif e < 0:
neg = neg + 1
time.sleep(2)
f = int(input('Please enter the sixth number: '))
total = total + f
if f > 0:
pos = pos + 1
elif f == 0:
zeroes = zeroes + 1
elif f < 0:
neg = neg + 1
time.sleep(2)
g = int(input('Please enter the seventh number: '))
total = total + g
if g > 0:
pos = pos + 1
elif g == 0:
zeroes = zeroes + 1
elif g < 0:
neg = neg + 1
time.sleep(2)
print()
print('The sum of your entries is: ', + total)
time.sleep(2)
print()
print('You entered', + pos, 'positive numbers')
time.sleep(2)
print()
print('You entered', + zeroes, 'zeroes')
time.sleep(2)
print()
print('You entered', + neg, 'negative numbers')
print()
time.sleep(3)
Hello! I have the variable 'neg' keeping a running total of all of the negative numbers that the user enters. It seems as if the negative numbers aren't always being added to the 'neg' running total at the end of the code.
I've been working with Python 3x for about a week now, so be gentle :)
Thanks in advance for the help!
Edit: I have reworked this into a (working) loop per the advice of Kevin, is this a good loop? It seems to work, I'm just looking for pointers as I'm kind of struggling with Python logic. Big thanks to Kevin, wish I could upvote you!
New code posted below:
import time
sums = 0
pos = 0
neg = 0
zero = 0
numb = 0
user_numb = 0
running = True
print('This program will add any 7 numbers for you')
time.sleep(.5)
print()
while running:
user_numb = int(input('Please enter a number: '))
sums = user_numb + sums
numb = numb + 1
print()
if user_numb > 0:
pos = pos + 1
elif user_numb < 0:
neg = neg + 1
elif user_numb == 0:
zero = zero + 1
if numb == 7:
running = False
print()
time.sleep(2)
print('The sum of the numbers entered was: ', + sums)
print()
time.sleep(2)
print('You entered', + pos, 'positive numbers')
print()
time.sleep(2)
print('You entered', + neg, 'negative numbers')
print()
time.sleep(2)
print('You entered', + zero, 'zeroes')
print()
print()
time.sleep(3)
In the section with b you forgot in the copy/pasted code to change all 'a' into 'b' and have still twice an 'a' there:
b = int(input('Please enter the second number: '))
total = total + b
if b > 0:
pos = pos + 1
elif a == 0: # CHANGE TO 'b'
zeroes = zeroes + 1
elif a < 0: # CHANGE TO 'b'
neg = neg + 1
so you see wrong results only in case the second number is a 0 or negative.