Having trouble with def functions [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
I have been taking this class for a bit with python for a bit and I have stumbled into a problem where any time I try to "def" a function, it says that it is not defined, I have no idea what I am doing wrong and this has become so frustrating.
# Define main
def main():
MIN = -100
MAX = 100
LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):
scores.append(random.randint(MIN, MAX))
#Print the score list
print(scores)
print("Highest Value: " + str(findHighest(scores)))
Every time I try to test run this, I get
"builtins.NameError" name 'LIST SIZE' is not defined.
I cant take out the main function! It's required for the assignment, and even if I take it out I still run into errors.

Your MIN, MAX, and LIST_SIZE variables are all being defined locally within def main():
By the looks of it, you want the code below those lines to be part of main, so fix the indentation to properly declare it as part of main.
def main():
MIN = -100
MAX = 100
LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):
scores.append(random.randint(MIN, MAX))
#Print the score list
print(scores)
print("Highest Value: " + str(findHighest(scores)))

import random
# Define main
def main():
MIN = -100
MAX = 100
LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):
scores.append(random.randint(MIN, MAX))
#Print the score list
print(scores)
print("Highest Value: " + str(findHighest(scores)))
main()
Output:
[79]
NOTE: You will get another error message:
NameError: name 'findHighest' is not defined
Which I think findHighest should be a function in some part of your code.

Related

How would I add the results of a 'for' loop into a dictionary? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I am required to take 52 random outputs of cards. I got that in a for loop. The problem is, I need to save that output inside a variable.`
import random
r=random.randint(0, 9)
cards={'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2={}
for i in range(52):
global res
res = key, val = random.choice(list(cards.items()))
print("Your deck contains " + str(res))
cards2.update(i) # All output should go in here
I tried using cards2.update, but it didn't work.
I also tried using cards2.(keys).
I just need to create 52 random samples and store them as dictionary value pairs.
First remove the double assignment (res = key, val). And I don't see any point in using a global variable here. Just do _dict[key] = value as shown below, and it will work fine. Also remember that you can’t get all 52 random cards, because if the key exists then the value will be replaced.
import random
r = random.randint(0, 9)
cards = {'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2 = {}
for i in range(52):
key, val = random.choice(list(cards.items()))
cards2[key] = val
print(cards2)

Stuck in while loop and it doesnt work how I thought it would work [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
I'm trying to do a number guessing game where the computer selects a random number and you have to guess it and get an output that's either: Your number is too high, too low or correct number + needed attempts.
However with this code:
import numbers
from random import randint
#set x to a random number between 1 and 50
randomnummer = randint(1,51)
print (randomnummer)
#counter = 0
#ask to input a number between 1 and 50 and check if input is valid
def nummer_eingabe():
usernummer = (input("Please enter a number between 1 and 50: "))
usernummer = int(usernummer)
#counter = counter + 1
if usernummer >= 1 and usernummer <= 50:
return usernummer
else:
print("Pleae enter a valid number.")
return nummer_eingabe()
#declare number from function
checked_user_nummer = nummer_eingabe()
#define counter
counter = 0
while checked_user_nummer != randomnummer:
counter += 1
if checked_user_nummer > randomnummer:
print("You need to guess lower. Try again :)")
nummer_eingabe()
continue
elif checked_user_nummer < randomnummer:
print("You need to guess higher. Try again :)")
nummer_eingabe()
continue
elif checked_user_nummer == randomnummer:
strcounter = str(counter)
print("Nice! You needed " + strcounter + " tries to find the right number")
break
#dont allow console to close right away
input()
it goes well until it gets stuck giving the same feedback (either too high or too low)
How do I get out of the While loop? I tried changing up the continue statement with a break but that just causes the code to stop after the second time the input was given.
Also please dont mind the print(randomnummer) on line 5; that's just for debugging purposes.
You never reassign the variable. You call nummer_eingabe() but you discard the result.
You're now in a stage where you no longer want to debug your code using print() statements but learn how to debug small programs.
Make sure you don't write code in Notepad and use a decent IDE like Pycharm instead. Set a breakpoint wherever your code gets stuck (just click left of the code and right of the line number)
and hit the little bug icon to debug it. You will be able to see the variables on the go. After each single line of code, check if they match your expectation
After entering a value of 10, you'll see that the variable is still 50 - a clear indicator that the value did not get updated because you didn't make use of the return value of the function.
Don't call the function again on the while, instead do a while to check for a "trigger" and then use your while checked_user_number != randomnummer:
Then instead of break use the trigger = False and end the while.

How could I print the highest score and name of student grades using python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Using python I'm creating a code that receives a list of lists as parameter. This list of lists contains names and grades of students. The function also must print the name of the student with the best grade and its best grade. When I created the code and try to run it nothing occurs is there a way to improve my code? My desired output would be "The best student is: Caroline with a 9.6"
students=[["steve", 9.0], ["ben", 9.5], ["Caroline",9.6],["Tim", 9.1]]
highest_grade=[]
lowest_grade=[]
def best():
i = 1
max = min = students[0]
# first, calculate the max and min.
while i < len(students): # (possible improvement: replace this with a for loop)
if students[i] > max:
max = students[i] # replace max with the new max
if students[i] < min:
min = students[i] # replace min with the new min
i += 1
highest_grade.append(max)
lowest_grade.append(min)
print("The best student is:",best())
There are a few things you could do to improve it. You find the min score but don't use it, so I'm not sure if you need it. If you do need it, you could add it to your return statement. Here's a suggested way to do it that should be easy to follow:
students = [["steve", 9.0], ["ben", 9.5], ["Caroline", 9.6], ["Tim", 9.1]]
def best(students):
highest_grade_name = None
lowest_grade_name = None
my_max_score = -float("inf")
my_min_score = float("inf")
for name, score in students:
if score > my_max_score:
my_max_score = score
highest_grade_name = name
if score < my_min_score:
my_min_score = score
lowest_grade_name = name
return my_max_score, highest_grade_name
best_name, best_score = best(students)
print(f"The best student is {best_name} with a score of {best_score}")
max(students,key=lambda x:x[1])
I think would work
There could be quite a few improvements to this piece of code. Firstly, it would be far better if the students array was a dict, but it's understandable if it absolutely has to be an array of arrays.
Secondly, you're right, you should do this with a for loop:
def best_student_grade():
highest_grade = 0 # "max" is a terrible name for a variable
for student, grade in student:
if grade > highest_grade:
grade = highest_grade
best_student = student
return highest_grade, best_student
bstudent, bgrade = best_student_grade()
print(f"The best student is: {bstudent} with a {bgrade}")
You could even do this with a list comprehension, but I will leave that as an exercise to the reader.
In all honesty, I think it would benefit you in a lot of ways to read some introductory python or programming books.

Unsupported operand type(s) in Python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am new to python and am having trouble with functions/defining something properly.
Now I am getting the TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
I have to output it a certain way and meet specific directions given to me, but I just can't seem to figure this out. Any help would be greatly appreciated. I will include an image of the rules I have to follow, I figured out how to make it work when not following the rules but can't make it work when I try to stick to them.
Direction to follow for coding this
# A function that prompts the user for a name and returns it to the
# calling statement.
def getName():
name = input("Please enter your name: ")
return name
# A function that prompts the user for a score and returns it to the
# calling statement.
def score_input():
int(input("Enter your score: "))
# A function that receives two numbers and returns the average of those
# two values to the calling statement.
def find_avg():
(score_a + score_b) / 2
# A function that receives a string and a number (the name and the
# average score) and prints it out on the screen in the appropriate format.
def output():
print("Hi, {}. Your average score is {}".format(name, avg))
#############################################################################
# prompt for name
name = getName()
# prompt for two scores
score_a = score_input()
score_b = score_input()
# calculate the average
avg = find_avg()
# display the final output
output()
score_input doesn't have a return statement, so it returns None.
Two of your functions neglect to return the computed values, so they return None by default. Just change them to:
def score_input():
return int(input("Enter your score: "))
# ^^^^^^ added return
def find_avg():
return (score_a + score_b) / 2
# ^^^^^^ added return
and you won't get Nones when you call them.
Side-note: It's typically considered bad form to rely on non-constant globals. I'd suggest changing output to be more reusable by having it receive the items to output as arguments, e.g.:
def output(name, avg):
print("Hi, {}. Your average score is {}".format(name, avg))
then calling it with:
output(name, avg)
Same goes for find_avg. Packaging the script functionality up into a main method helps avoid accidentally relying on globals, which would get final code like this (comments omitted for brevity):
def getName():
return input("Please enter your name: ")
def score_input():
return int(input("Enter your score: "))
def find_avg(a, b):
return (a + b) / 2
def output(name, avg):
print("Hi, {}. Your average score is {}".format(name, avg))
#############################################################################
# Wrapping script functionality in main ensures all variables are local,
# not global, which ensures you don't accidentally depend on global state
def main():
name = getName()
score_a = score_input()
score_b = score_input()
avg = find_avg(score_a, score_b)
output(name, avg)
if __name__ == '__main__':
main() # Called only when invoked as a script, not when imported as a module
You don't return the input from the function score_input. So the return type is None.
In order to make your code work you would need to add return {expression} in the function.
This is how I would change the code:
# A function that prompts the user for a name and returns it to the
# calling statement.
def getName():
name = input("Please enter your name: ")
return name
# A function that prompts the user for a score and returns it to the
# calling statement.
def score_input():
return int(input("Enter your score: "))
# A function that receives two numbers and returns the average of those
# two values to the calling statement.
def find_avg():
return (score_a + score_b) / 2
# A function that receives a string and a number (the name and the
# average score) and prints it out on the screen in the appropriate format.
def output():
print("Hi, {}. Your average score is {}".format(name, avg))
#############################################################################
# prompt for name
name = getName()
# prompt for two scores
score_a = score_input()
score_b = score_input()
# calculate the average
avg = find_avg()
# display the final output
output()

How can I return with a local variable in definition in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to create a simple AI program which plays stick game. The problem is that I would like to subtract chosen stick from the total stick number. This simple code shows some error such as nonexisting value. I could not assign returning value for my values. Is there another way to subtracts value with functions?
import random
msg = input('Determine stick numbers:')
print('Stick number is determined as:', msg)
# First player move
def robot(stick):
y = stick % 4
if y==0:
y=randint(1,3)
mov=int(y)
print('machine chose:', mov)
total = stick-mov
return total
def human(stick2):
mov2= int(input('your turn:'))
print('human chose:', mov2)
total = stick2-mov2
return total
players= {
'1': robot,
'2': human
}
number1= input('Determine first player machine(1) or human(2):')
number2= input('Determine second player (1) or (2):')
player1=players[number1]
player2=players[number2]
print(player1, player2)
print('the game begins')
while True:
player1(int(msg))
if msg == 0: break
print('remained sticks:', msg)
player2(int(msg))
print('remained sticks:', msg)
if msg == 0: break
Your players are references functions:
players= {
'1': robot,
'2': human
}
Later you call them player1 and player2:
player1=players[number1]
player2=players[number2]
But when you use these functions you don't do anything with the return value:
player1(int(msg))
...
player2(int(msg))
So those functions return something, but you ignore the value. You need to either print that return value or assign it to a variable so you can do something with the value later.
Since your return values are called total perhaps you want:
total = player1(int(msg))
print('new total:', total)
return does work, of course; it returns a value. However in your code you are not capturing that value and it is immediately thrown away.
It's really not clear what you want, but perhaps you want something like this:
msg = player1(int(msg))

Categories

Resources