I can't figure out what I am doing wrong. I have tried using a break, and tried setting what the variable !=, I am doing this on cengage and it is very finnicky.
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
while leftOrRight != "X":
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
your input() is outside the while loop, so leftOrRight never changes, never get to X so it will not exit the loop:
leftOrRight = None
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
According to your code you are not changing the value for leftOrRight after entering the loop so the condition for your while loop is never false I would suggest the following edit:
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = '' #anything random
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
so that you get a prompt every time the loop is executed and you can click X to exit
Your program just got the character that had the largest id in the ascii table.
And only doing the first string as the longString = max(n) wasn't even in the while loop.
also max returns the largest value, so in this case it was just converting the text into an ascii number.
instead you should use len(string) which returns the length of the string.
Unlike max() which is used like:
11 == max(11,10,1,2) as 11 is the largest character.
n = (input("Input: ")) #get initial input
longest = 0 #define the varible which we will keep the length of the longest string in
longest_str = "" #define the varible which stores the value of the longest string.
while n: #you don't need that other stuff, while n does the same as while n != ''
n = str(input("Input: ")) #get input
length = len(n) #gets the length of the input
if length > longest: #if the length of our input is larger than the last largest string
longest = length #set the longest length to current string length
longest_str = n #set the longest string to current string
#once the user hits enter (typing "") we exit the while loop, and this code runs afterwards.
print("Longest input was", longest_str, "at", longest, "characters long")
Because there are two specific counts we are accumulating for, and the outlying char is at the end of our input, we can set our while to True to break when we hit a char other that "L" or "R".
leftOrRight = ""
# Write your loop here.
while True:
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
if leftOrRight == "L":
leftTotal = leftTotal + 1
elif leftOrRight == "R":
rightTotal = rightTotal + 1
else:
break
# Output number of left or right-handed students.
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
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 ')
digit= open('pi.txt','r')
guess = digit.readline()
while guess.isdigit():
if digit == ".":
digit = pi.read(1)
elif digit == "\n":
seed += 1
pi.seek(seed)
digit = pi.read(1)
else:
if int(guess) == int(digit):
print(guess, "is correct")
correct += 1
else:
print("Sorry, number is", digit, "not", guess)
wrong += 1
guess = input("enter another digit guess or \"q\": ")
digit = pi.read(1)
print("\nThanks for playing\nNumber Correct:", correct, "\nNumber Incorrect:", wrong)
pi.close()
OUTPUT:
Thanks for playing
Number Correct: 0
Number Incorrect: 0
Need to figure it out how to add numbers for the number correct and incorrect and I have no idea what to do.
& Hope this help!
Maintain two lists correct_responses and incorrect_responses
correct_responses = []
incorrect_responses = []
while guess.isdigit():
if digit == ".":
digit = pi.read(1)
elif digit == "\n":
seed += 1
pi.seek(seed)
digit = pi.read(1)
else:
if int(guess) == int(digit):
print(guess, "is correct")
correct += 1
correct_responses.append()
else:
print("Sorry, number is", digit, "not", guess)
wrong += 1
guess = input("enter another digit guess or \"q\": ")
digit = pi.read(1)
print("\nThanks for playing\nNumber Correct:", correct, "\nNumber Incorrect:", wrong)
pi.close()
I am going to write a guessing game with the computer.
I choose one number in my head and the Computer is going to find it out, and it can guess between a range.
The problem is I don’t know how can I update this range during the program run.
import random
x = 1
y = 99
guess= random.randint(x,y)
print(guess)
play='true'
while play=='true':
a=x
b=y
results = input()
if results == 'd':
play='false'
else:
if results == 'b':
a=guess
print('My number is bigger!')
newguess= random.randint(a,b)
print (newguess)
elif results == 'k':
b=guess
print('My number is smaller!')
newguess= random.randint(a,b)
print (newguess)
print ('Wooow , computer you did it! ')
Sorry about all the explanations in the code but this is a version of the game that I did a while ago. What I did was I wanted to shrink the guessing range each time the user said high or low. e.g. if the computer chooses 50, and the user says 'High' then the program will not chose a number greater than 50, the same applies for 'Low". Enjoy
import random
count = 0 #Number of attemps. how many times while loop runs.
guess = random.randint(1,100)#The guess generator
(l,u) = (0,100)
lower_guess = l
upper_guess = u
n = 0
print('Chose a number between ', l, ' and ', u , '.' )
#The game. These are outside the function so that they don't print in every loop because they are unwanted for some Y inputs.
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')#User states
#The function
while n != 'guess':
count +=1 #adds 1 to count each time loop runs
if Y == 'L':
lower_guess = guess+1
guess = random.randint(lower_guess , upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
elif Y == 'H':
upper_guess = guess - 1
guess = random.randint(lower_guess, upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
elif Y == 'Y':
print('I guessed it in ' + str(count) + ' attempts')
break
else:
count = 0
lower_guess = l
upper_guess = u
guess = random.randint(1,100)
print('That input was invalid. The game has restarted.')
print('You can chose a new number or keep your old one.')
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
I am making a connect four like game in python, what I have so far is creating the board and implementing game play against the computer. I am running into the issue that does not allow me to play past the second row. Any ideas on why?
#Define the board
row = int(input("Please enter # of rows: ")) #User input Rows
column = int(input("Please enter # of columns: ")) #User input Columns
board = [] #empty board
space = ' '
p1 = 'x'
p2 = 'o'
#create board based on user input
for i in range(0,row):
board.append([])
for j in range(0, column):
board[i].append(space)
print(board)
#print board with character decorations
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))
print(len(board))
while True:
#User input column
myC = int(input("Player 1, choose your column: "))
i = len(board)-1
x = len(board)-1
while i >= 0:
if board[x][myC] == space:
i = i+1
board[x][myC] = 'x'
break
elif board[x][myC] == p1 or p2:
i = i+1
x = x - 1
print(x)
board[x][myC] = 'x'
break
# print the board!
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))
#Computer input column
from random import randint
theC = randint(0, len(board)-1)
print("Computer's Turn: Column " , theC)
i = len(board)-1
x = len(board)-1
while i >= 0:
if board[x][theC] == space:
board[x][theC] = 'o'
i = i+1
break
elif board[x][theC] == p1 or p2:
i = i+1
x = x - 1
print(x)
board[x][theC] = 'o'
break
# print the board!
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))
I believe I figured out what's going on. Your x is always initialized to len(board)-1 and then if the space is occupied it is reduced by one. If you make a (>2)x(>2) board and row 0 is occupied then this will always force x = 2.
This is close to correct, but what you actually need is to iterate through all rows until you find the first unoccupied row. I created a loop that will find the first row and assign that to the value of x. I tested it out and I'm now able to play passed 2 rows.
#Define the board
row = int(input("Please enter # of rows: ")) #User input Rows
column = int(input("Please enter # of columns: ")) #User input Columns
board = [] #empty board
space = ' '
p1 = 'x'
p2 = 'o'
#create board based on user input
for i in range(0,row):
board.append([])
for j in range(0, column):
board[i].append(space)
print(board)
#print board with character decorations
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))
print(len(board))
while True:
#User input column
myC = int(input("Player 1, choose your column: "))
i = len(board)-1
x = len(board)-1
while i >= 0:
if board[x][myC] == space:
i = i+1
board[x][myC] = 'x'
break
# Find last empty row for new piece
elif board[x][myC] == p1 or p2:
for j in range(x-1,-1,-1):
if board[j][myC] == space:
x = j
break
i = i+1
#x = x - 1
print(x)
board[x][myC] = 'x'
break
# print the board!
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))
#Computer input column
from random import randint
theC = randint(0, len(board)-1)
print("Computer's Turn: Column " , theC)
i = len(board)-1
x = len(board)-1
while i >= 0:
if board[x][theC] == space:
board[x][theC] = 'o'
i = i+1
break
# Find last empty row for new piece
elif board[x][theC] == p1 or p2:
for j in range(x-1,-1,-1):
if board[j][theC] == space:
x =j
break
i = i+1
#x = x - 1
print(x)
board[x][theC] = 'o'
break
# print the board!
for i in board:
line=''
print('+'+'-+'*len(i))
for j in range(len(i)):
line = line + '|'+i[j]
line = line + '|'
print(line)
print('+'+'-+'*len(i))
Hopefully this will be very simple all I need help with is getting a count of the letter grades and then printing them along with the list.
Here is my code:
def getScores():
f_obj = open("scores.txt", "r")
data = f_obj.readlines() #read file into a list of record strings
f_obj.close()
return data
def displayData(data):
print("Name Avg Grade")#print headings
for record in data:
name, ex1, ex2, ex3 = record.split()
exam1 = float(ex1)
exam2 = float(ex2)
exam3 = float(ex3)
avg = round(exam1 + exam2 + exam3) / 3
if avg >= 100:
letterGrade = "A"
elif avg >= 89:
letterGrade = "B"
elif avg >= 79:
letterGrade = "C"
elif avg >= 69:
letterGrade = "D"
elif avg >= 59:
letterGrade = "F"
Just above here is where im stuck I cannot figure out how to do a count with the certain letter grades.
print("%-10s %5s %5s" % (name, round(avg, 1), letterGrade))
print()
print(
def addStudent():
name = input("Enter student name: ")
ex1 = int("Enter Exam 1 grade: ")
ex2 = int("Enter Exam 2 grade: ")
ex3 = int("Enter Exam 3 grade: ")
return name + "\t" + ex1 + "\t" + ex2 + "\t" + ex3
def storeData(data):
f_obj = open("scores.txt", "w")
f_obj.writelines(data)
f_obj.close()
def main():
scoreData = getScores() # read data file into a list
while True:
print("""
Program Options
1.) Display Students.
2.) Add a new student:
3.) Exit Program """)
option = input("Enter option 1, 2, or 3: ")
if option == "1":
displayData(scoreData)
elif option == "2":
scoreData.append(addItem()) # add record string to our list
elif option == "3":
storeData(scoreData)
print("Good bye.")
break
else:
print("Not a valid entry. Please enter 1, 2, or 3.")
main() # start the program
Hint: you already know how to determine if a grade is an A, B, C, etc. So all you need to do is increment a counter at the same time.
For example, you'd add in something like this to count the number of A grades:
if avg >= 100:
letterGrade = "A"
numAs += 1
Then do the same thing for each other grade type. Since this appears to be homework, I'll let you figure out how to do all this. Most importantly, even though Python isn't strict about this, think about the correct place to declare the counter variables.
Once you've got that working, here's an "extra credit" assignment: see if you can do all that using just a single array.