I'm having trouble because I'm asking the user to input 6 numbers into a list and then total and average it depending on input from user. It's my HWK. Please help.
x = 0
list = []
while x < 6:
user = int(input("Enter a number"))
list.append(user)
x = x + 1
numb = input("Do you want a total or average of numbers?")
numb1 = numb.lower
if numb1 == "total":
Here is my answer:
def numberTest():
global x, y, z
L1 = []
x = 0
y = 6
z = 1
while(x < 6):
try:
user = int(input("Enter {0} more number(s)".format(y)))
print("Your entered the number {0}".format(user))
x += 1
y -= 1
L1.append(user)
except ValueError:
print("That isn't a number please try again.")
while(z > 0):
numb = input("Type \"total\" for the total and \"average\"").lower()
if(numb == "total"):
a = sum(L1)
print("Your total is {0}".format(a))
z = 0
elif(numb == "average"):
b = sum(L1)/ len(L1)
print("Your average is {0}".format(round(b)))
z = 0
else:
print("Please try typing either \"total\" or \"average\".")
numberTest()
I tried this a couple of times and I know it works. If you are confused about parts of the code, I will add comments and answer further questions.
Related
import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
After getting input from console, you should create a loop which breaks when guessed number equal to input. For example:
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while result != guess:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
break
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
After revision, code seems like:
import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while result != guess:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
break
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
It's because python programs runs from top to bottom, and when it reaches the bottom it's done and stops running. To stop this order we have multiple different ways:
We can call a function, as you do in you're program.
Selection Control Structures: As if statements
Iteration Control Structures: As loops
The last one is the one you need in this solution. Wrap code in a while loop, with the correct condition, in you're example, this would be
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
The best way woul be to use a will loop as follow:
while guess != num:
You should use while True:, because your guessing code runs only once without it
import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 10)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
att = 1
num = num_gen()
while True:
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
print('Your guess was HIGH! Please guess another number between 1 and 100: ')
att += 1
elif result == 'low':
print('Your guess was LOW! Please guess another number between 1 and 100: ')
att += 1
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
break
how can you expect it to run more than 1 time if you have not used any loop in the program. For example in this case you should use a while loop, then only it will prompt the user again and again and will check for the conditions, set a game variable to be True. When the number is matched then simply set the game variable to be False and it will end the loop.
import random
# Set the game variable initially to be True
game = True
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while game:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
game = False
The error I get from the program is undefined variable.
*
# Python 3.9.4
# import sys
# print(sys.version)
SubjectT = input("Enter your subject: ")
Tutor_Name = input("Enter your name: ")
Iterate = int(input("How many students are there? "))
# Set counter
# create count for each student
Accumulate = 0
for i in range(Iterate): # It will run how many time based on Iterate input
Score = float(input("Enter score: "))
Counter = True
while Counter:
if 80 <= Score < 100:
Accumulate1 = Accumulate + 1
elif 80 > Score >= 65:
Accumulate2 = Accumulate + 1
elif 65 > Score >= 50:
Accumulate3 = Accumulate + 1
elif Score < 50:
Accumulate4 = Accumulate + 1
else:
print("The number is a negative value or incorrect")
Again = input("Enter yes for restarting again or if you want to exit the program please press anything: ")
if Again in ("y", "Y", "YES", "Yes", "yes"):
continue
else:
break
print(f"Subject title:", {SubjectT}, "\nTutor:", {Tutor_Name})
print("Grade", " Number of students")
print("A", "Students: ", Accumulate1)
print("B", "Students: ", Accumulate2)
print("C", "Students: ", Accumulate3)
print("D", "Students: ", Accumulate4)
This is my first post in Stackoverflow.
pardon me for any inappropriate content.
Thanks you so much.
You stated
Counter = True
without iteration, thus it will run indefinitely. With while loop you need to set some constraints.
I realised why you had the While loop in there, but it still wasn't working for me effectively - if all answers were within range it never terminated. This should work for you, it does for me. I changed it so it checks every time somebody enters a score that it is within the correct range, so you don't have to repeat the whole loop in the event of incorrect values
SubjectT = input("Enter your subject: ")
Tutor_Name = input("Enter your name: ")
NoOfStudents = int(input("How many students are there? "))
# Set counter
# create count for each student
Accumulate = 0
Accumulate1 = 0
Accumulate2 = 0
Accumulate3 = 0
Accumulate4 = 0
def validRange(score):
if 0 <= score <=100:
return True
else:
return False
i = 1
while (i <= NoOfStudents): # It will run how many time based on Iterate
validInput = False
while (not validInput):
Score = float(input("Enter score: "))
if ( not validRange(Score)):
print("The number is a negative value or incorrect")
else:
validInput = True
if 80 <= Score < 100:
Accumulate1 = Accumulate1 + 1
elif 80 > Score >= 65:
Accumulate2 = Accumulate2 + 1
elif 65 > Score >= 50:
Accumulate3 = Accumulate3 + 1
elif Score < 50:
Accumulate4 = Accumulate4 + 1
i = i+1
print(f"Subject title:", {SubjectT}, "\nTutor:", {Tutor_Name})
print("Grade", " Number of students")
print("A", "Students: ", Accumulate1)
print("B", "Students: ", Accumulate2)
print("C", "Students: ", Accumulate3)
print("D", "Students: ", Accumulate4)
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid score, please re-enter: ")))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
I tried to make a python program, to validate the score, but it's still a mistake, I want to make a program if I enter a score of less than 0 it will ask to re-enter the score as well if I input more than 100. Where is my error?
Change the if statement:
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
while True:
if 0 <= score <= 100:
break
score = int(input("Invalid score, please re-enter: "))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
Here, the score at the same time can't be less than 0 and greater than 100. So as you want to break of the score is between 0 and 100, we use 0 <= score <= 100 as the breaking condition.
Also the loops were reversed, since you won't get what you expected to.
try this one:
array = []
total = 0
num_of_students = int(input("How many students in your class: "))
print("\n")
for x in range(num_of_students):
score = int(input("Input score {} : ".format(x + 1)))
while True:
if score < 0 or score > 100:
score = int(input("Invalid score, please re-enter: "))
else:
array.append(score)
break
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/num_of_students))
I renamed some of your variables. You should always try to using self explanatory variable names. I am also using string interpolation (should be possible for Python +3.6) and comparison chaining.
score_list = []
total = 0
number_of_students = int(input("How many students in your class: "))
print("\n")
for student in range(number_of_students):
score_invalid = True
while score_invalid:
score_student = int(input(f"Input score {student + 1} : "))
if (0 <= score_student <= 100):
score_invalid = False
else:
score_invalid = True
if score_invalid:
print("Invalid score!\n")
score_list.append(score_student)
print("\n")
print(f"Maximum: {max(score_list)}")
print(f"Minimum: {min(score_list)}")
print(f"Average: {sum(score_list) / number_of_students}")
You could try something like this:
score = -1
first_time = True
while type(score) != int or score <= 0 or score >= 101 :
if first_time:
score = int(input("Input score: "))
first_time = False
else:
score = int(input("Invalid score, please re-enter: "))
array.append(score)
I am currently learning python and decided to create a basic game HiLo. I've managed to code the basics but now I'd like to take it further and get the answers as a key press. At first I created a list with available answers as "h, l, etc." but now I'd the user to press UP ARROW KEY for high and DOWN ARROW KEY for low and check the answer is correct.
I've tried with msvcrt, keyboard and pyautogui modules but I could not seem to make it work.
import random
import pygame
from msvcrt import getch
name = input("Please enter your name: ")
print("Welcome {}".format(str(name)))
print(
"Okay {}. We will now play a game called high or low. In order to play this game you have to be 18 or older".format(
str(name)))
age = int(input("Please enter your age: "))
print(age)
if age < 18:
print("You are not old enough the play.")
exit
else:
print("OK! You are {}. You can play".format(str(age)))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Your first number is {}.".format(str(x)))
counter = 0
truecounter = 0
falsecounter = 0
while counter <= 10:
print("Press UP for high and DOWN for low.")
getch()
if and y > x: #If UP Arrow is pressed and Y is greater than X
truecounter += 1
print("Your answer is correct!. The other number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
elif and y < x: #If DOWN Arrow is pressed and Y is smaller than X
truecounter += 1
print("Your answer is correct!. The other number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
elif and y > x: #If DOWN ARROW is pressed and Y is greater than X
falsecounter += 1
print("Ooops! You guessed wrong. The number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
elif and y < x: #If UP ARROW is pressend and Y is smaller than X
falsecounter += 1
print("Ooops! You guessed wrong. The number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
counter += 1
print("Congrats! You got " + str(truecounter) + " out of 10!")
I expect that according to input of the user ( UP or DOWN arrow key) the code will check the numbers and add a point to true or false counter.
Here this works.
What are the problem with the keyboard libary?
import random
import keyboard
name = input("Please enter your name: ")
print("Welcome {}".format(str(name)))
print(
"Okay {}. We will now play a game called high or low. In order to play this game you have to be 18 or older".format(
str(name)))
age = int(input("Please enter your age: "))
print(age)
if age < 18:
print("You are not old enough the play.")
exit
else:
print("OK! You are {}. You can play".format(str(age)))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Your first number is {}.".format(str(x)))
counter = 0
truecounter = 0
falsecounter = 0
def check(key):
global UP_PRESS,DOWN_PRESS,run
if key.__dict__["event_type"] == "down":
DOWN_PRESS = True
run = True
elif key.__dict__["event_type"] == "up":
UP_PRESS = True
run = True
else:
raise KeyError("Not the right Key")
while counter <= 10:
print("Press UP for high and DOWN for low.")
UP_PRESS = False
DOWN_PRESS = False
run = False
while not run:
keyboard.unhook_all()
try:
event = keyboard.hook(check)
except:
print("ERROR: Press Arrow Up or Arrow Down")
print("\n")
if UP_PRESS and y > x: #If UP Arrow is pressed and Y is greater than X
truecounter += 1
print("Your answer is correct!. The other number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
elif DOWN_PRESS and y < x: #If DOWN Arrow is pressed and Y is smaller than X
truecounter += 1
print("Your answer is correct!. The other number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
else:
falsecounter += 1
print("Ooops! You guessed wrong. The number was " + str(y))
x = random.randint(1, 9)
y = random.randint(1, 9)
print("Let's see if you can do it again. The number is")
print(x)
counter += 1
print("Congrats! You got " + str(truecounter) + " out of 10!")
here is my current code:
total = 0.0
count = 0
data = input("Enter a number or enter to quit: ")
while data != "":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter to quit: ")
average = total / count
if data > 100:
print("error in value")
elif data < 0:
print("error in value")
elif data == "":
print("These", count, "scores average as: ", average)
The only problem now is "expected an indent block"
I would do something cool like
my_list = list(iter(lambda: int(input('Enter Number?')), 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
if you wanted to do conditions, something like this would work
def getNum():
val = int(input("Enter Number"))
assert 0 < val < 100 or val == 999, "Number Out Of Range!"
return val
my_list = list(iter(getNum, 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
To calculate an average you will need to keep track of the number of elements (iterations of the while loop), and then divide the sum by that number when you are done:
total = 0.0
count = 0
data = input("Enter a number or enter 999 to quit: ")
while data != "999":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter 999 to quit: ")
average = total / count
print("The average is", average)
Note that I renamed sum to total because sum is the name of a built-in function.
total = 0.0
count = 0
while True:
data = input("Enter a number or enter 999 to quit: ")
if data == "999":
break
count += 1
total += float(data)
print(total / count)