I have seen loads of answers that say to use {} or str() + to make the input() only get given 1 argument.
But what parts of the input need to go with those? This is my code
name.append(input("What is their name"))
score.append(input("What did", name[x], "score"))
I'm pretty sure the 3 arguments are the "what did", "name[]x" and "score"
How would I make these one argument while keeping the same order and meaning?
You can format the string so that you only pass 1 argument:
score.append(input("What did %s score" % name[x]))
However if you want to add multiple arguments do this:
score.append(input("%s scored %d points!" % (name[x], points)))
You are adding three arguments in total while the function expects only one so pass one argument only:
name.append(input("What is their name"))
score.append(input("What did %s score" % name[x]))
The % syntax is the old syntax. Try to learn the new syntax as well
score.append(input("What did {} score".format(name[x])))
This website has some good breakdowns of common usages between the old and the new: https://pyformat.info/
Related
I have a simple python script that calculates if the price of one variable is less than the other. For example, var1 should always be passed to the calculation function first, and var2 should always be passed second. Then, the function needs to check if var1 is less than var2 Currently, for the calculation function, I have positional parameters, and it is on the end user to correctly pass the parameters in the correct order for the calculation. It seems intuitive enough to know what position to pass each parameter in, but I am wondering if there is a way to safeguard against users being sloppy and passing parameters to the wrong positions?
Example code one:
def get_values():
var_one = 1
print("Var1: ", var_one)
var_two = 2
print("Var2: ", var_two)
print("")
calculate(var_one, var_two)
def calculate(var_one, var_two):
if var_one < var_two:
print("Var1 is less than Var2")
else:
print("Var2 is greater than Var1")
if __name__ == "__main__":
get_values()
Output:
Var1: 1
Var2: 2
Var1 is less than Var2
This is all fine and well. This is the correct way to call the function and it prints logically correct output. However, if I flip the parameter positions in the function call and change the values of var_one and var_two, this happens:
Example Code 2:
def get_values():
var_one = 3
print("Var1: ", var_one)
var_two = 2
print("Var2: ", var_two)
print("")
calculate(var_two, var_one)
def calculate(int_one, int_two):
if int_one < int_two:
print("Var1 is less than Var2")
else:
print("Var2 is greater than Var1")
if __name__ == "__main__":
get_values()
Output:
Var1: 3
Var2: 2
Var1 is less than Var2
As seen here, when var_one is greater than var_two and when we pass the parameters in the wrong position, the output contains a clear logical error. Looking at the code, Var1 is clearly greater than Var2. While it is intuitive how you need to position the parameters here, is there anything that can be done in the calculate() function signature to safeguard against this kind of human/user error, and to ensure var_one always gets passed first to the function before var_two?
***It is important to note that I am using static values here. However, let's say I am pulling in dynamic / changing integers from an API, and I always want to make sure value1 is less than value2, then this needs to be enforced.
I don't believe that doing this is possible in Python, or any other language. Since part of the calculate function behaves in a different, but "allowed" way, it can't tell if the inputs have been swapped.
As a human, you want to read the name of the variables that they are passing in. The issue is what happens when someone names their variables first_value and second_value? How do you know which one goes first? Or if they say initial_number and updated_number? The function can't read the mind of the programmer to determine what variable they felt to be "one" or "two"
One solution to this is providing a good docstring to make sure that the user knows how your function should be called. The pycharm way to do it is below.
def calculate(int_one, int_two):
"""
Determines which of two numbers is greater (fill with info about what it actually does)
:param int_one: The first number. Must be the first value received.
:param int_two: The second number. Must be the second value received.
:return: Nothing
"""
if int_one < int_two:
print("Var1 is less than Var2")
else:
print("Var2 is greater than Var1")
So, I have the following function which should resemble the already implemented " print " function in Python. ( I know it is silly to make a function that only uses a pre-defined function but I am practicing with different things ) The thing that I want to do with my function is: make it act the same as the pre-defined one. That is, when the print function is called with no parameters, I would like it to print an empty line just as " print() " does. How do i do that ?
def print_str( string, how_many_times, tail ):
print ( string * how_many_times, end = tail )
print doesn't take a single string, it takes 0 or most strings as argument. end has a reasonable default. You can imagine a (simplified) definition of
def print(*args, end='\n'):
...
You need to do the same for yours. A reasonable default for how_many_times would be 1. If you don't want print_str to take multiple arguments, "" would be a reasonable default for string.
def print_str(string="", how_many_times=1, tail='\n'):
print(string * how_many_times, end=tail)
You can do something like this:
def myfunc(a=None):
if a == None:
print()
else:
print("hi")
If no arguments are presented it prints nothing, but if an argument is given it prints 'hi'.
This question already has answers here:
Why does Python not perform type conversion when concatenating strings?
(8 answers)
Closed 7 months ago.
fname3 = input("Enter the Blue print name: ")
import re
with open (fname3) as file:
fileText=file.read()
q1,q2,q3 = [ int(n) for n in re.findall(": (\d+)",fileText) ]
p1,p2,p3 = re.findall("(.*):",fileText)
qb=q1+q2
qc=q1+q2+q3
print("This BLUEPRINT CONTAINS--------------|")
print(p1+" Questions: "+q1)
This code above is giving an error of line: print(p1+" Questions: "+q1)
but print(p1+" Questions: "+p1) is giving correct output abd also print("q1")
but combining them is outputting an error
but gives error print("questions: "+q1)
This code opens a txt file which contains the following:
Part A: 12 10*2 = 20
Part B: 6 4*5 = 20
Part C: 5 3*10 = 30
Another way to do this is with something called f-strings (available in Python 3.6+, but the latest version is 3.7):
print (f"{p1} Questions: {q1}")
Notice how there is an f before the quotes (applies to all types of quotes), and any variable you want has to be in {}
You need to convert to a string with str:
print(p1 + " Questions: " + str(q1))
Alternatively, simply use multiple arguments when calling print:
print(p1, "Questions:", q1)
Note that the spaces are added automatically with this method.
The problem is in the types of your variables.
Questions:, p1, p2 and p3 are all of type str.
Conversely, q1, q2 and q3 are of type int.
The print calls work separately because print can convert its arguments to str. However, you are first trying to add two strings (p1 and Questions:) to an int (q2), which is what fails.
Rather than naive addition/concatenation, you should prefer str.format calls:
print('{p} Questions: {q}'.format(p=p1, q=q1))
These make it easier to understand what the string will look like and automatically perform conversion of your arguments.
Python is strongly typed language. In most cases, it does not do any implicit type conversion. Consider, should "5"+7 be 12 or "57"? How about 7+"5"?
On ambiguous cases like this, Python will simply raise error rather than trying to guess what you meant.
You need to do the type conversion explicitly:
print(p1+" Questions: "+str(q1))
or with Python 3 f-string:
print(f"{p1} Questions: {q1}")
or print function accepts multiple arguments, that will, by default, be separated by space:
print(p1, "Questions:", q1)
Here is essentially what I am trying to do:
Class MyClass():
def __init__(self):
self.name="Bob"
person=MyClass()
print " hello {1} how are you?".format(1=person.name)
This gives an error saying keyword cant be an expression
I know there are many ways around this for example:
print "hello " + person.name
But for longer sentences I prefer the first format as it is easier to understand, if anyone knows how to fix it, or even just explain to me why it is wrong that would be greatly appreciated.
print " hello {} how are you?".format(person.name)
if you want to use position, it begin at 0
print " hello {0} how are you?".format(person.name)
0 means the first element inside format function
print " {0},{1},{0}".format('a', 'b')
a,b,a
what does this mean:
print "{0} ({1})"
in this code:
for x in [None,3,4.5,"foo",lambda : "moo",object,object()]:
print "{0} ({1})".format(x,type(x))
As mentioned in the comments, they are placeholders for your string, here is a bit of an explanation with some examples. Also mentioned, is the documentation here, which explains this very well.
When you provide the arguments for your format method, the values of these arguments will be set in these placeholders. The order in which the arguments will be used, depends on how you write these placeholders. You can actually even have empty placeholders "{}", which will just take the arguments in order.
Observe the following examples.
Assuming the following two arguments are set:
arg1 = "pretzels"
arg2 = "thirsty"
In order placeholders:
print("These {0} are making me {1}".format(arg1, arg2))
Outputs:
These pretzels are making me thirsty
Out of order placeholders:
print("These {1} are making me {0}".format(arg1, arg2))
Outputs:
These thirsty are making me pretzels
No value provided in placeholders:
print("These {} are making me {}".format(arg1, arg2))
Output:
These pretzels are making me thirsty