In the code below, I am trying to input the number (e.g. 2 3 4). Suppose if the length of the input is not equal to mat_dim_col, I want to input again. However, the function is retaining the previous input and not returning the latest one.
Matrix row entry function.
def mat_row(mat_dim_col,r):
inp = input("Enter " +
str(mat_dim_col) +
" values, all space seperated for row " +
str(r) + " : " ).split()
print(inp)
if len(inp) == mat_dim_col:
print(inp)
row_ent = [int(x) for x in inp]
return row_ent
else:
print("Invalid entry, try again!")
mat_row(mat_dim_col,r)
When you recurse, you need to return the value it provides, otherwise, you might end up getting a correct response after a few attempts but it won't be returned through the stack correctly.
def mat_row(mat_dim_col,r):
inp = input("Enter " +
str(mat_dim_col) +
" values, all space seperated for row " +
str(r) + " : " ).split()
print(inp)
if len(inp) == mat_dim_col:
print(inp)
row_ent = [int(x) for x in inp]
return row_ent
else:
print("Invalid entry, try again!")
""" RETURN mat_row response """
return mat_row(mat_dim_col,r)
Related
The output should be as follows:
Input:
Give the text: hippo
Give the character: x
Output:
xxxxxxx
xhippox
xxxxxxx
Input 2:
Give the text: sausage
Give the character: **
Output 2:
Invalid input! Type only one character!
The code im using:
text = input("Give the text: ")
plaque = input("Give the character: ")
def make_plaque(string):
decorated = 'plaque' * (len(string) + 2) + "\n" #top row
decorated = decorated + 'plaque' + string + "*\n" #middle row
decorated = decorated + 'plaque' * (len(string) + 2) + "\n" #bottom row
return decorated
plaque = make_plaque(text)
print(plaque)
Trying to make it work but still unsuccessful
You should really state your issue better. I assume the issue is that you don't have any error checking for your expected single character input. I would use a loop.
not_valid = True
plaque_char = ""
while not_valid:
plaque_char = input("Give the character: ")
if len(plaque_char) != 1:
print("Please enter one character.")
else:
not_valid = False
Using this code to manage the input of your plaque character should give you the desired error checking. However you can play with it to get it to detect multiple character or no characters if you want. I think; my syntax is good, but I've been using a lot of C++ lately, so if it is off sorry.
text = input("Give the text: ")
char_check=False
while char_check is False:
plaque = input("Give the character: ")
if len(plaque)>1:
print("Invalid input! Type only one character!")
else:
char_check=True
def make_plaque(string):
decorated = plaque * (len(string) + 2) + "\n" #top row
decorated = decorated + plaque + string + "{}\n".format(plaque) #middle row
decorated = decorated + plaque * (len(string) + 2) + "\n"#bottom row
return decorated
plaque = make_plaque(text)
print(plaque)
this code will do!
I need to remove all excess white space and leave one space, between my words while only using if and while statements. and then state the amount of characters that have been removed and the new sentence
edit, it must also work for punctuation included within the sentence.
This is what I have come up with however it leaves me with only the first letter of the sentence i choose as both the number, and the final sentence. can anyone Help.
def cleanupstring(S):
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
else:
lasti = i
result += i
return result
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
Your code should be something like this:
def cleanupstring(S):
counter = 0
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
counter += 1
else:
lasti = i
result += i
return result, counter
sentence = input("Enter a string: ")
outputList = cleanupstring(sentence)
print("A total of", outputList[1], "characters have been removed from your string.")
print("The new string is:", outputList[0])
The counter keeps track of how often you remove a character and your [0] and [1] work now the way you want them to.
This is because outputList is now a tuple, the first value at index 0 is now the result and the second value at index 1 is the counter.
Hi having trouble trying to fix an error that occurs when I put just a '#' or rogue value in case someone doesn't want to add any data. I don't know how to fix it and I'm hoping to just end the code just like I would with data.
#Gets Data Input
def getData():
fullList = []
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
while inputText != "#":
nameList = []
nameList2 = []
nameList = inputText.split()
nameList2.extend((nameList[0],nameList[1]))
nameList2.append((float(nameList[2]) + float(nameList [3]))/2)
fullList.append(nameList2)
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
print("\n")
return fullList
#Calculates Group Average
def calc1(fullList):
total = 0
for x in fullList:
total = total + x[2]
groupAverage = total/(len(fullList))
return(groupAverage)
#Finds Highest Average
def calc2(fullList):
HighestAverage = 0
nameHighAverage = ""
for x in fullList:
if x[2] > HighestAverage:
HighestAverage = x[2]
nameHighAverage = x[0] + " " + x[1]
return (HighestAverage, nameHighAverage)
#Returns Marks above average
def results1(groupAverage,r1FullList):
r1FullList.sort()
print("List of students with their final mark above the group average")
print("--------------------------------------------------------------")
print("{:<20} {:<12}".format("Name","Mark"))
for x in r1FullList:
if x[2] > groupAverage:
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f}".format(name,x[2]))
def calc3(x):
if x[2] >= 80:
return 'A'
elif x[2] >= 65:
return 'B'
elif x[2] >= 50:
return 'C'
elif x[2] < 50:
return 'D'
else:
return 'ERROR'
def results2(fullList):
print("List of Studens with their Final Marks and Grades")
print("-------------------------------------------------")
print("{:<20} {:<12} {:<12}".format("Name","Mark","Grade"))
for x in fullList:
grade = calc3(x)
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f} {:<12}".format(name,x[2],grade))
#Checks for boundary and invalid data
def checkInput(question):
while True:
textInput = input(question)
if textInput == "#":
return textInput
splitList = textInput.split()
if len(splitList) !=4:
print("Invalid Format, Please Try Again")
continue
try:
a = float(splitList[2])
a = float(splitList[3])
if float(splitList[2]) < 0 or float(splitList[2]) > 100:
print("Invalid Format, Please Try Again")
continue
if float(splitList[3]) < 0 or float(splitList[3]) > 100:
print("Invalid Format, Please Try Again")
continue
return(textInput)
except ValueError:
print("Invalid Input, Please Try Again")
continue
#Main Program
#Input Data
fullList = getData()
#Process Data
groupAverage = calc1(fullList)
HighestAverage, nameHighAverage = calc2(fullList)
#Display Results
print("The group average was %.2f" % groupAverage)
print("The student with the highest mark was: %s %0.2f" %(nameHighAverage,HighestAverage))
results1(groupAverage,fullList)
print("\n")
results2(fullList)
Your program works OK for me, unless you enter a # as the first entry, in which case fullList is [] and has length 0. Hence, DivisionByZero at this line: groupAverage = total/(len(fullList)).
You could modify your code to check for this and exit:
import sys
fullList = getData()
if not fullList:
print('No Data!')
sys.exit()
elif used_prefix and cmd == "xp":
if self.getAccess(user) >= 1:
f = open("users/" + user.name.lower() + ".txt", 'r')
word = f.readline().split("X Points = ")
if word == "0":
room.message("You have no X Points")
else:
room.message("You Have " + word + " X Points")
f.close()
else:
room.message("You are not whitelisted " + user.name.capitalize())
When I try to use XP it shows Can't convert 'list' object to str implicitly as the error in the console. I'm using python 3.3.
You might need
word = f.readline().split("X Points = ")[1].strip()
as you are splitting, it will return the list of items split as a list. You need to take the element corresponding to the actual value
Example
data = "X Points = 10"
print data.split("X Points = ")
Output
['', '10']
So, we need to get the second element. Thats why we use [1]
The main issue is that split returns a list, not a string.
if self.getAccess(user) >= 1:
with open("users/{}.txt".format(user.name.lower()), 'r') as f:
word = f.readline().split("X Points = ")[1]
if word == "0":
room.message("You have no X Points")
else:
room.message("You Have {} X Points".format(word))
else:
room.message("You are not whitelisted {}".format(user.name.capitalize()))
I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.