I'm writing something in python, and I don't understand why this section of code isn't working.
m = 1
f = 0
gender_choice = False
while gender_choice == False:
gender = input('Are you male or female? Type m for male or f for female. ')
if gender == m or gender == f:
print
gender_choice = True
else:
print
print "Hey, this is a text based game. Read and follow bro."
print gender
I think I understand that there is an issue with setting a string to "m" or "f", but unless I change raw_input to input, the loop will continue. Also, as is currently written, if the user enters anything other than a number, m, or f, I will get an error that the string is undefined, for example, if they enter "y".
Ok, first of check your indentation!
This is how I would think that you'd like it to look:
m = 1
f = 0
gender_choice = False
while gender_choice == False:
gender = input('Are you male or female? Type m for male or f for female. ')
if gender == m or gender == f:
print
gender_choice = True
else:
print
print "Hey, this is a text based game. Read and follow bro."
print gender
Then your else statement will only get executed when your if statement gets evaluated as False, which is always at the moment since it evaluates whether gender == 1 or gender == 0 which will only happen if your user does not "Read and follow bro." I do not know if you need the m and f variables later in your code but I'm going to assume that you do, so what I'd do is this:
gender_choice = False
while gender_choice == False:
gender = raw_input('Are you male or female? Type m for male or f for female. ')
if gender == "m":
print
gender_bool = 1
gender_choice = True
elif gender == "f":
print
gender_bool = 0
gender_choice = True
else:
print "\nHey, this is a text based game. Read and follow bro.\n"
print gender
That way your logic works and the m and f variable has been put into one variable (gender_bool) that can be evaluated in later logic, the if statements evaluates something that makes more sense (imho) and you use raw_input so that you can enter anything in there without raising errors (and I added some \n (linebreaks) to please my OCD :P).
Related
Title
I'm currently trying to get a user to input a chessboard using dashes (-) and the letters corresponding to the pieces. But the list isn't saving properly. Here's the code that's screwing up.
def make_a_chessboard():
chessboard = []
possible_char = ["-","K","k","Q","q","R","r","N","n","B","b","P","p"]
rows = 8
cols = 8
for r in range(rows):
user_input = input("")
while len(user_input) != 8:
print("That is not the correct length. Please try again.")
user_input = input("")
for i in range(len(user_input)):
flag1 = False
while flag1 == False:
if user_input[i] not in possible_char:
print("One of the characters used is not supported. Please try again.")
user_input = input("")
else:
for c in range(cols):
chessboard[r][c].append(user_input[c])
flag1 = True
return(chessboard)
This gives me the IndexError: list index out of range error. What am I doing wrong?
I'd recommend a bit of a restructure of the code so you test the validity once and completely of your input for each row, and then we can build the list of each position on a particular row, and append this to the chessboard list. The below is totally untested, so if there's syntax errors let me know and I'll edit it up.
def is_valid_row(user_in):
possible_char = ["-","K","k","Q","q","R","r","N","n","B","b","P","p"]
if len(user_in) != 8:
print("Please enter a string of 8 characters")
return False
for each_char in user_in:
if each_char not in possible_char:
print("You have entered illegal char {}".format(each_char))
return False
# Neither of those other two have returned false
# so we're good to assume it's valid
return True
def make_a_chessboard():
chessboard = []
rows = 8
# Process each row (you do this line by line, right?)
for r in range(rows):
user_input = input("")
while not is_valid_row(user_input):
user_input = input("")
# We now have valid input (or we're stuck in while-loop-hell)
# break the input into a list (of 8 valid chars)
each_row = [x for x in user_input]
# Now append it to chessboard
chessboard.append(each_row)
return(chessboard)
SPOILER This questions is about the Hackerrank Day 8 challenge, in case you want to try it yourself first.
This is the question they give:
Given n names and phone numbers, assemble a phone book that maps
friends' names to their respective phone numbers. You will then be
given an unknown number of names to query your phone book for. For
each name queried, print the associated entry from your phone book
on a new line in the form name=phoneNumber; if an entry for is not
found, print Not found instead.
Note: Your phone book should be a Dictionary/Map/HashMap data
structure.
The first line contains an integer, n, denoting the number of
entries in the phone book. Each of the n subsequent lines describes
an entry in the form of 2 space-separated values on a single line. The
first value is a friend's name, and the second value is an 8-digit
phone number.
After the n lines of phone book entries, there are an unknown number
of lines of queries. Each line (query) contains name a to look up,
and you must continue reading lines until there is no more input.
Note: Names consist of lowercase English alphabetic letters and are
first names only.
They go further then to give the input:
3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
which expects the output:
sam=99912222
Not found
harry=12299933
I am having trouble with the unknown number of names to query. I tried using a try/except block to stop at an EOFError but I keep timing out on their test cases 1, 2 and 3. It works on two of the other test cases but not those and I assume it must be because I am stuck in a kind of infinite loop using my while True statement? This is what I wrote:
phonebook = {}
entries = int(raw_input())
for n in range(entries):
name, num = raw_input().strip().split(' ')
name, num = [str(name), int(num)]
phonebook[name] = num
while True:
try:
search = str(raw_input())
if search in phonebook.keys():
output = ''.join('%s=%r' % (search, phonebook[search]))
print output
else:
print "Not found"
except EOFError:
break
I am still fairly new to python so maybe I'm not using the try/except or break methods correctly? I would appreciate if anyone could tell me where I went wrong or what I can do to improve my code?
The only mistake you are doing is that you are using
phonebook.keys()
You can loop without using .keys() . It will save time.
phonebook = {}
entries = int(raw_input())
for n in range(entries):
name, num = raw_input().strip().split(' ')
name, num = [str(name), int(num)]
phonebook[name] = num
while True:
try:
search = str(raw_input())
if search in phonebook:
output = ''.join('%s=%r' % (search, phonebook[search]))
print output
else:
print "Not found"
except EOFError:
break
The above code will work with all the test cases.
In python-3
# n, Enter number of record you need to insert in dict
n = int(input())
d = dict()
# enter name and number by separate space
for i in range(0, n):
name, number = input().split()
d[name] = number
# print(d) #print dict, if needed
# enter name in order to get phone number
for i in range(0, n):
try:
name = input()
if name in d:
print(f"{name}={d[name]}")
else:
print("Not found")
except:
break
Input:
3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
Output:
sam=99912222
Not found
harry=12299933
n = int(input())
d = dict()
for i in range(0, n):
name, number = input().split()
d[name] = number
#print(d) Check if your dictionary is ready
for i in range(0, n):
name = input()
if name in d:
print(f'{name}={d[name]}')
else:
print("Not found")
Try this, It'll work.
run this code to pass all the test cases:
n = int(input())
d = {}
for i in range(n):
tp = input()
a, b = tp.split()
d.update({a: b})
inputs = []
input1 = input().strip()
try:
while len(input1) > 0:
inputs.append(input1)
input1 = input().strip()
except:
pass
for i in inputs:
if i in d.keys():
c = 1
print(i + "=" + d[i])
else:
print('Not found')
Lets make life easy
Hacker rank 30 Day Code - Day no 8 (#Murtuza Chawala)
n = int(input())
i = 0
book = dict() #Declare a dictionary
while(i < n):
name , number = input().split() #Split input for name,number
book[name] = number #Append key,value pair in dictionary
i+=1
while True: #Run infinitely
try:
#Trick - If there is no more input stop the program
query = input()
except:
break
val = book.get(query, 0) #Returns 0 is name not in dictionary
if val != 0:
print(query + "=" + book[query])
else:
print("Not found")
n = int(input())
PhoneBook = dict(input().split() for x in range(n))
try:
for x in range(n):
key = input()
if key in PhoneBook:
print (key,'=',PhoneBook[key],sep='')
else:
print('Not found')
except:
exit()
n= int(input())
dct={}
for i in range(n):
info=input().split()
dct[info[0]]=info[1]
while 1:
try:
query=input().lower()
if query in dct:
print(query+'='+dct[query])
else:
print('Not found')
except EOFError:
break
Below snippet works for me.
noOfTestCases = int(input())
phoneDict = {}
for i in range(noOfTestCases):
name, phoneNumber = input().split()
phoneDict[name] = phoneNumber
for i in range(noOfTestCases):
try:
name = input()
if name in phoneDict:
print(name+'='+phoneDict[name])
else:
print("Not found")
except:
break
Input
3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
Output
sam=99912222
Not found
harry=12299933
# Enter your code here. Read input from STDIN. Print output to STDOUT
entries = int( input() )
# print(entries)
data = {}
for i in range(entries):
# print("i=",i)
name, num = input().strip().split(" ")
# print(name)
# print(num)
data[name]=num
# print(data)
while True:
try:
search = input()
if search in data.keys():
print(search,"=",data[search], sep="")
else:
print("Not found")
except EOFError:
break
Input (stdin)
3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
Your Output (stdout)
sam=99912222
Not found
harry=12299933
Expected Output
sam=99912222
Not found
harry=12299933
#Using Setter and Getter
n = int(input())
d = {}
while n:
x, y = input().split()
d.setdefault(x,y)
n -= 1
while True:
try:
inp = input()
if d.get(inp):
print(f"{inp}={d.get(inp)}")
else:
print(f"Not found")
except EOFError:
break
n=int(input())
d=dict()
for i in range(n):
name,number = input().split()
d.update({name:number})
for i in range(n):
name=input()
if name in d:print(name +"="+d[name])
else:
print("Not found")
I'm trying to make a simple 2 player game on python 2.7 .
The program will determine the result of a rock, paper, scissors game, given Player 1 and Player 2’s choices. The program will print out the result, score by each player and the total number of game played.
My question is:
The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
1.The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? ")).lower()
player_2 = str(input(">>Player 2? ")).lower()
2.Both player must input their choices before the program can be terminated. That means when player 1's input "-1", the program doesn't terminate immediately. It will proceed to ask player 2 for input before it get terminated. How can I make the program terminate itself immediately when player 1's input is "-1"?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? "))
if (player_1=='-1'):
print 'End of game'
break
player_2 = str(input(">>Player 2? "))
3.My code is very long, any suggestions or tips on shortening it without sacrificing any of the function?
use function definitions. Sample:
if (player_1=='-1' or player_2=='-1'):
print 'End of game'
break
elif dif in [-1, 2]:
print ('Player 1 wins.')
score1 = score1 + 1
showScore()
elif dif in [1, -2]:
print('Player 2 wins.')
score2 = score2 + 1
showScore()
else:
print('Tie')
showScore()
continue
def showScore():
print '==================='
print 'Score:'
print 'Player 1: ' + `score1`
print 'Player 2: ' + `score2`
print 'Total game played: ' + `times`
print ''
Here's a good read
For starters, I converted your program to Python 3. It's better in every way. For one thing, it has a normal definition for input.
In general, if you have N of something, where N is greater than 1, it's better to use an array. If you see repetition, move the data into an array and call a function. When N is 2, you won't necessarily shorten the code (my version is longer than yours) but you'll avoid treating the players differently because they both pass through the same logic.
Put the main logic in a function, too, and reserve the "main" code for dealing with startup & command-line stuff.
When you see a string of elifs, that's also a use data instead indicator. In my victor function, I iterate over tuples of winning combinations. You might consider how to use a dict instead.
import sys, os
def print_results( msg, times, scores ):
print( (msg) )
print( '===================' )
print( 'Score:' )
print( 'Player 1: %d' % scores[0] )
print( 'Player 2: %d' % scores[1] )
print( 'Total game played: %d' % times )
print( '' )
def victor( inputs ):
results = ( ('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock') );
for (a, b) in results:
if a == inputs[0] and b == inputs[1]:
return 1
if b == inputs[0] and a == inputs[1]:
return 2
return 0
def play(times, scores):
inputs = ['', '']
for (i, choice) in enumerate(inputs):
prompt = '>>Player %d? ' % (i + 1)
choice = input(prompt).lower()
if choice == '-1':
return False
inputs[i] = choice
result = victor(inputs)
if result == 0:
print_results('Tie', times, scores)
else:
scores[result - 1] += 1
print_results('Player %d wins' % result, times, scores)
times += 1
return True
print('''Welcome to play Rock, Paper, Scissors game. Enter -1 to end''')
scores = [0, 0]
times = 0
while play(times, scores):
pass
if scores[0] == scores[1]:
player = 'Tie'
else:
if scores[0] > scores[1]:
i = 1
else:
i = 2
player = 'Player %d' % i
print( '*******************' )
print( 'Winner: %s' % player )
print( '*******************' )
I can't seem to find how to, in Python 2.7, fill in a variable name instead of an index. I only find answers for other programming languages.
The file that is imported contains multiple columns, but I only want to add columns defined and asked for in the Query function to Data_BM. So how can IlocX be seen as an index.
Even if there is an easier way, I would just like to know how to put a variable on an index position. Thank you in advance.
# function for the datafile name
def datafilename():
print "Type the data filename, for example: myfile.csv : \n"
dataname = raw_input()
print dataname, 'Correct? [Y/N]'
yn = raw_input()
if yn == 'Y' or yn == 'y':
return dataname
else:
datafilename()
# function for the column numbers
def query(var):
print 'Type column number for',var,':'
loc = raw_input()
try:
loc = int(loc)
except:
loc = loc
print loc, 'Correct? [Y/N]'
yn = raw_input()
if yn == 'Y' or yn == 'y':
if type(loc) == int:
return loc
elif loc == 'NA' or loc == 'na':
return loc
else:
print 'Please type column as integer value'
query(var)
else:
query(var)
#Ask for column locations
loc1 = query("X")
loc2 = query("Y")
loc3 = query("Z")
loc4 = query("A")
loc5 = query("B")
Iloc1 = int(loc1-1)
Iloc2 = int(loc2-1)
Iloc3 = int(loc3-1)
Iloc4 = int(loc4-1)
Iloc5 = int(loc5-1)
# Asking for data file name
dataname = datafilename()
#Get data
Data_BM = pd.read_csv(dataname)
Data_BM = Data_BM[Iloc1,Iloc2,Iloc3,Iloc4,Iloc5]
I updated my file, I forgot to put in the query function. The user is asked to fill in the column number for for example X. The user types 1, which is loc1. Iloc 1 = 0. So 0 is the indexnumber. How can I have Iloc1 be the indexnumber in Data_BM = Data_BM[Iloc1,Iloc2,Iloc3,Iloc4,Iloc5] and the same accounts for the others. The reason I want this is because the columns might change but I want to make it easy for the user.
Short answer is no,
Long answer is why?
If you have a list of variables like a1, a2, a3, a4, ..., an, make a list of them, or a dictionary if you want to access it by strings.
The closest thing you can do is:
vars = {}
for i in range(10):
vars["Ilock"+str(i)] = something()
vars["Ilock4"] = 42
But it's ugly and not convenient.
I have looked over this code 100 times and I feel like it may be something small that I am missing. Program will allow you to login, and display the menu but after entering your selection it continuously displays the menu again.
import sys
def main():
login = 'yes'
choice = 0
hours = [0] * 7
wages = 0
totalHours = 0
totalWages = 0
print
login = raw_input('Do you want to login?')
while not (login == 'yes' or login == 'no'):
print
print 'Please enter a yes or no'
while login == 'yes':
print
userId = raw_input ('Enter user name:')
passWord = raw_input('Enter password:')
while passWord != userId:
print 'Incorrect Password, please try again.'
passWord = raw_input('Enter password:')
while passWord == userId:
print 'Login Success!'
print
print 'Enter 1 to view upcoming schedule'
print 'Enter 2 to view previous schedule'
print 'Enter 3 to calculate wages due'
print 'Enter 4 to verify clock in/out times'
print
choice = raw_input('Enter 1 to 4 from menu.')
def readFromNext(nextWeek):
inFile = open('nextweek.txt', 'r')
str1 = inFile.read()
print str1
str2 = inFile.read()
print str2
print
inFile.close()
def readFromLast(lastWeek):
inFile = open('lastweek.txt', 'r')
str1 = inFile.read()
print str1
str2 = inFile.read()
print str2
print
inFile.close()
def getHours(hours):
counter = 0
while counter < 7:
hours[counter] = input('Enter hours worked per day')
counter = countr + 1
return hours
def getTotalHours(hours, totalHours):
counter = 0
while counter < 7:
totalHours = totalHours + hours[counter]
counter = counter + 1
return totalHours
def getWages(wages):
wages = input('Enter your hourly wage.')
return wages
def getTotalWages(totalHours, wages):
totalWages = totalHours * wages
print 'Your total pay due is:' , totalWages
return totalWages
def readFromClock(clockHours):
inFile = open('clockhours.txt', 'r')
str1 = inFile.read()
print str1
str2 = inFile.read()
print str2
print
inFile.close()
while choice != '5':
if choice == '1':
readFromNext(nextWeek)
print 'Upcoming schedules'
if choice == '2':
readFromLast(lastWeek)
print 'Previous schedules'
if choice == '3':
hours = getHours(hours)
totalHours = getTotalHours(hours, totalHours)
wages = getWages(wages)
totalWages = gettotalWages(totalHours, wages)
print 'Paycheck calculator'
if choice == '4':
readFromClock(clockHours)
print 'Clock in/out times'
main()
What do you expect it to do? You have added many functions but they appear to be unused. You end up printing the menu over and over again because you are in the loop
while passWord == userId:
...
You have to do something with the choice variable and break out of that loop if you want anything else to happen.
For example:
choice = raw_input('Enter 1 to 4 from menu.')
if choice == 1:
readFromNext(nextWeek)
elif choice == 2:
readFromLast(lastWeek)
elif choice == 3:
getTotalWages(totalHours, wages)
elif choice == 4:
getHours(hours)
Obviously you will need to figure out which function maps to which user input, but currently you are not doing anything with the user's choice, merely asking them to choose over and over again with no control over the termination of the loop.
You are not changing the value of login in your while not loop.
login = 'default'
while not (login == 'yes' or login == 'no'):
print 'Please enter a yes or no'
login = raw_input('Do you want to login?')
... for example. The way you currently have it is never going to end:
while not (login == 'yes' or login == 'no'):
print
print 'Please enter a yes or no'
This is conceptually identical as:
while True:
if login == 'yes' or login == 'no':
break
print
print 'Please enter a yes or no'
So if the login is never changed, it will never end.