Remove trailing white space in python 3 - python

Having bit of trouble with a program i made. i am getting it to display a diamond but i have a problem, here is my code:
a = input("Enter width: ")
a = int(a)
b = a
for i in range(a):
i = i + 1
b = a - i
text = " " * b + " " + "* " * i
print(text[:-1])
for i in range(a):
i = i + 1
b = a - i
text = " " * i + " " + "* " * b
print(text[:-1])
Thanks for all the help! this is the answer

That's because print doesn't return the string, it returns None.
>>> print(print("foo"))
foo
None
Perhaps you wanted to do this:
text = " " * i + " " + "* " * b
print (text[:-1])
To remove the trailing white-space better use str.rstrip:
>>> "foo ".rstrip()
'foo'
help on str.rstrip:
>>> print (str.rstrip.__doc__)
S.rstrip([chars]) -> str
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.

You can write your slice like this (not on the print return value):
("* "*b)[:-1]
or, you can use join:
' '.join(['*']*b)

Related

Python: TypeError: can only concatenate str (not "int") to str : variable stored wrong

Hi Need clarification for python variable stored as wrong value , here is code :
userinput1 = int(input('enter start value\n'))
userinput2 = int(input('enter stop value\n'))
userinput3 = int(input('enter rampup time in seconds\n'))
userinput4 = float(input('enter increments delta \n'))
userinput5 = input('Enter sequence channels: A A A A or D D D D - A Ascend, D Descent , E Exclude \n')
command1 = "RAMP " + str(userinput5) + " " + userinput1 + " " + userinput2 + " " + userinput4 + " " + userinput3
port.write(command1.encode())
#### ERROR #####
command1 = str("RAMP " + str(userinput5) + " " + userinput1 + " " + userinput2 + " " + userinput4 + " " + userinput3)
TypeError: can only concatenate str (not "int") to str
Can you please clarify me correct method to store both type variable input in single variable command. type caste was done already.
You can concate only strings, so before concate all your userinputs you must "convert" them into strings
Example1:
command1 = "RAMP " + " ".join(map(str, [userinput5, userinput1, userinput2, userinput4, userinput3]))
Example2:
command1 = f"RAMP {userinput5} {userinput1} {userinput2} {userinput4} {userinput3}"

function doesnt show up when its supposed to

At school we have to write a program to use the pythagorean theory. Im writing it in python 3 but when I return cber the program just ends. bber on the other hand works fine. Can someone please help? Thanks already:)
Edit: Thanks for helping me, this is not everything with the function kiezen the user can choose two numbers and the j and the n are to decide which lines they are in the triangle, thats in the function kiezen too. This is all in one function called cijfers, I dont know if that makes a difference. I used return because that way I could let the user choose the numbers again if he/she entered something unvalid. And I forgot to remove the ifs in cber before posting it. I’ll try to
improve my program sometime soon. Thanks for all your feedback:)
def bber():
if (c >= a):
print(str(a) + "^2 + b^2 = " + str(c) + "^2")
print("b^2 = " + str(c) + "^2 - " + str(a) + "^2")
print("b = V(" + str(c**2) + " - " + str(a**2) + ")")
print("b = V" + str((c**2) - (a**2)) + " = " + str(math.sqrt((c**2) - (a**2))))
if (a >= c):
print("De rechthoekzijde kan niet langer zijn dan de schuine zijde.")
cijfers()
def cber():
if (a >= b):
print(str(a) + "^2 + " + str(b) + "^2 = c^2")
print("c^2 = " + str(a) + "^2 + " + str(b) + "^2")
print("c = V(" + str(a**2) + " + " + str(b**2) + ")")
print("c = V" + str((a**2) + (b**2)) + " = " + str(math.sqrt((a**2) + (b**2))))
if (b >= a):
print(str(a) + "^2 + " + str(b) + "^2 = c^2")
print("c^2 = " + str(a) + "^2 + " + str(b) + "^2")
print("c = V(" + str(a**2) + " + " + str(b**2) + ")")
print("c = V" + str((a**2) + (b**2)) + " = " + str(math.sqrt((a**2) + (b**2))))
def kiezen():
x = int(input("Wat is de lengte van de eerste zijde?"))
xz = input("Is deze zijde een rechthoekzijde (J/N)?")
print(" ")
y = int(input("Wat is de lengte van de tweede zijde?"))
yz = input("Is deze zijde een schuine zijde (J/N)?")
print(" ")
return kiezen()
if xz == "j" or "J":
if yz == "n" or "N":
b = y
a = x
return cber()
if yz == "j" or "J":
c = y
a = x
return bber()
There are a few problems going on.
You need to import modules.
In your code, you are using math.sqrt, so the first line required is to actually import the math module at the beginning of your file:
import math
You are not getting access to your variables inside your functions. To pass them to your function, you have to specify them as function parameters:
def bber(a, c):
On the positive side, your function bber reports the right answer inside your statement if (c >= a). However, the following conditional statement, if (a >= c), calls the function cijfers(), which doesn't actually exist. In that case, every time a is greater than or equal to c, the program will print a NameError.
The function cber works, but you don't actually need to have if statements, because you get the variable c no matter if b is greater than a or if a is greater than b. You might want to consider checking for other types of input (like text, negative numbers, floats, etc.), though.
Here is how you could simplify your cber function, also having to pass in actual parameters:
def cber(a, b):
print(str(a) + "^2 + " + str(b) + "^2 = c^2")
print("c^2 = " + str(a) + "^2 + " + str(b) + "^2")
print("c = V(" + str(a**2) + " + " + str(b**2) + ")")
print("c = V" + str((a**2) + (b**2)) + " = " + str(math.sqrt((a**2) + (b**2))))
The function kiezen isn't actually doing anything in your code. It is defined, but you don't use it anywhere, apparently.
Variables defined inside functions are local to that function while variables defined outside a function (i.e. no indentation) are global variables. When you need to use a global variable inside a function, you have to pass it as a function parameter. For more information on this topic, you can read about the concepts of "scope", "global scope" and "local scope". You can also find examples in the official Python documentation, here.
For now, so you can see how to use variables that are defined globally, I will use your incomplete kiezen function without actually making it a function, so the code is directly executed in your program.
One other problem here is that you can use the keyword return only inside a function, because that is what it is meant for: to return the result of a function.
This means that you have to change your code return cber() and return bber() by removing the return keyword.
You are missing a space at the end of your questions with input. When you type your answer, it will appear right next to the last character in your string.
When you want to check for multiple options (as you did with XZ == "j" or "J"), you can use a list instead and the keyword in.
Here are some modifications needed to make your program work in the end. Comments are present on lines with the # symbol.
# To use a function provided by the math module, you have to import it first
import math
# You have to get "a" and "c" from somewhere, so you pass them as parameters
def bber(a, c):
if (c >= a):
print(str(a) + "^2 + b^2 = " + str(c) + "^2")
print("b^2 = " + str(c) + "^2 - " + str(a) + "^2")
print("b = V(" + str(c**2) + " - " + str(a**2) + ")")
print("b = V" + str((c**2) - (a**2)) + " = " + str(math.sqrt((c**2) - (a**2))))
if (a >= c):
print("De rechthoekzijde kan niet langer zijn dan de schuine zijde.")
# Same scenario here: "a" and "b" must be defined somehow
# Note that the "if" statements were unnecessary
def cber(a, b):
print(str(a) + "^2 + " + str(b) + "^2 = c^2")
print("c^2 = " + str(a) + "^2 + " + str(b) + "^2")
print("c = V(" + str(a**2) + " + " + str(b**2) + ")")
print("c = V" + str((a**2) + (b**2)) + " = " + str(math.sqrt((a**2) + (b**2))))
# Note that a space has been added at the end of each string
# where you use "input".
X = int(input("Wat is de lengte van de eerste zijde? "))
XZ = input("Is deze zijde een rechthoekzijde (J/N)? ")
print(" ")
Y = int(input("Wat is de lengte van de tweede zijde? "))
YZ = input("Is deze zijde een schuine zijde (J/N)? ")
print(" ")
if XZ in ["j", "J"]:
if YZ in ["n", "N"]:
b = Y
a = X
# You have to remove the word "return", this is not a function
cber(a, b)
if YZ in ["j", "J"]:
c = Y
a = X
# You have to remove the word "return", this is not a function
bber(a, c)
As I mentioned earlier, this is not perfect because you would need to manage errors. For example, it will not work if you enter text instead of numbers, but that is a topic for another discussion.
Also, for the purpose of this exercise, you do not actually "need" to use the return keyword in your functions if your goal is just to print the output, but keep in mind that if you need to reuse the result of a function, you will have to return a value for it.
A quick example of that concept would be the following:
def my_function():
return 12
# my_variable will have a value of 12
my_variable = my_function()

Creating a map/contents of any object

In Python 3.6. What I'm trying to do is create a function that can accept any object and then generate a tree like contents.
Similar to a book:
1. Object
1.1 member: integer
1.2 member: list
2.1 list: element 1
2.2 list: element 2
1.3 member: string
My purpose is to use the numbers as a key for a technical readout, the number could also stand in for a more understandable ID number than id() generates. Because the objects I want to deal with are all types, I'd like the function to be recursive. Here is what I have so far:
def contents(a, n = 0, lim = 5, prefix=""):
index = 1
text = ""
j = None
if n < lim:
try:
for i in a.__dict__:
text = text + "\n" + ("\t" *(n)) + prefix + str(index) + ", " + str(i) + ": " + contents(a.__dict__[i], n = n + 1, prefix=str(n)+".") + ""
index += 1
except:
try:
for i, j in a.items():
text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(i) + ": " + contents(i, n = n + 1, prefix=str(n)+".") + ""
index += 1
except:
if isinstance(a, str):
text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(a) + " "
else:
try:
for i in a:
text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(i) + contents(i, n = n + 1, prefix=str(n)+".") + " "
index += 1
except:
text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(a) + " "
else:
text = text + "limit. \n"
return text
a is the object, n is the current number of recursion, lim is the recursion limit, prefix has to do with the object ID displayed.
Here's the testing object
class Aclass:
def __init__(self):
self.a = [12, 24]
self.b = 5
a = [Aclass(), 1, "2", 3, 4, Aclass(), {"c":"d","e":"f"}]
The problem I'm running into has to do with strange revursive behavior with lists, I already made an exception for strings, because the string would register as an iterable made up of iterables, which would recurse indefinitely if I hadn't put in a limit. Now simple lists of numbers like [1, 2, 3, 4] will often list the number twice as if it breaks down into a one item list [1] and then reports on the number inside: 1.
You should have a look at the pprint module, which is part of the standard distribution. It solves this problem already, and so might serve as a basis for your code. (I can easily see, for instance, adding numbers by subclassing the PrettyPrinter class.)
This code:
class Aclass:
def __init__(self):
self.a = [12, 24]
self.b = 5
a = [Aclass(), 1, "2", 3, 4, Aclass(), {"c":"d","e":"f"}]
import pprint
s = pprint.pformat(a, indent=4)
print(s)
Produces this output:
[ <__main__.Aclass object at 0x1060fb160>,
1,
'2',
3,
4,
<__main__.Aclass object at 0x1060fb198>,
{'c': 'd', 'e': 'f'}]

Python formatting print

I'm having some formatting issues with my call to print function. For lack of knowledge of better ways to format, i've ended up with an issue. here is what it should look like
However the actual result of my print returns this.
def tupleMaker(inputString):
s1 = inputString.split()
# Adding the surname at the end of the string
s2 = [s1[len(s1) - 1]]
# Number of other names(no surname)
global noOfNames
noOfNames = len(s1) - 4
# Adding all the other names
for i in range(noOfNames):
s2.append((s1[i + 3]))
# Adding the Reg number
s2.append(s1[0])
# Adding the Degree scheme
s2.append(s1[2])
# Adding the year
s2.append("Year " + s1[1])
# Making it a tuple
t = ()
for i in range(len(s2)):
t = t + (s2[i],)
return t
def formatting(t):
s1 = ""
for i in range(len(t)):
s1 += t[i]
if (i == 0):
s1 += ", "
elif (i == len(t) - 4):
s1 += " "
else:
s1 += " "
#print(t[0] + ", ", end="")
#for i in range(noOfNames):
#print (t[i+1], end= " ")
#print(format(t[1+noOfNames], "<32s"))
#print(format(thenames, "<32d") + format(regNo, "<7d") + format(degScheme, ">6s") + format(year, ">1s")
print("")
print(s1)
I would recommend looking at using pythons built in string.format() function a small tutorial is located here: https://pyformat.info/

Python 2.7 - Converting a single character string to an integer

I'm trying to make a program which reads from two text file line by line and stores the line which you have specified in Name_Input earlier (in variable line and line 2), it then strips off anything which is not a number from the string.
for line in Roster_Inputed:
if Name_Input in line:
line = re.sub('[^0-20]', '', line)
if line == "1":
print(Name_Input + " " + "should have " + line + " " + "ally.")
print " "
else:
print(Name_Input + " " + "should have " + line + " " + "allies.")
print " "
for line2 in Roster_Should_Have:
if Name_Input in line2:
line2 = re.sub('[^0-20]', '', line2)
if line2 == "1":
print(Name_Input + " " + "actually has " + line2 + " " + "ally.")
print " "
else:
print(Name_Input + " " + "actually has " + line2 + " " + "allies.")
print " "
The code reads from two files which contain names and number after a space, it then goes on to compare them to determine what it outputs to the user:
if line == line2:
print "All good"
elif line != line2:
print "Check " + Name_Input + "'s " + "spies"
print " "
What I need it to do is check if the value of "line" is greater than "line2" however I cannot do so because they are strings which contain numbers. Is there a way to temporarily convert them to integers?
You can use chr() and ord() functions:
>>> chr(97)
'a'
>>> ord('a')
97
Hope it helps.
What about calling int?
>>> int('345')
345
Since I have now gotten confirmation that the characters will always be integers and the integers are what you want to compare, I can now say use int():
>>> int('4')
4
In your case, if int(line) > int(line2): should do what you want. Since files usually have new-line characters at the end of each line, you should probably consider using int(line.strip()) and int(line2.strip()).

Categories