How to define a variable inside the print function? - python

I am a newbie in this field, and I am trying to solve a problem (not really sure if it is possible actually) where I want to print on the display some information plus some input from the user.
The following works fine:
>>> print (" Hello " + input("tellmeyourname: "))
tellmeyourname: dfsdf
Hello dfsdf
However if I want to assign user's input to a variable, I can't:
>>> print (" Hello ", name = input("tellmeyourname: "))
tellmeyourname: mike
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
print (" Hello ", name = input("tellmeyourname: "))
TypeError: 'name' is an invalid keyword argument for this function
I have researched inside here and other python documentation, tried with %s etc. to solve, without result. I don't want to use it in two lines (first assigning the variable name= input("tellmeyourname:") and then printing).
Is this possible?

Starting from Python 3.8, this will become possible using an assignment expression:
print("Your name is: " + (name := input("Tell me your name: ")))
print("Your name is still: " + name)
Though 'possible' is not the same as 'advisable'...
But in Python <3.8: you can't. Instead, separate your code into two statements:
name = input("Tell me your name: ")
print("Your name is: " + name)
If you often find yourself wanting to use two lines like this, you could make it into a function:
def input_and_print(question):
s = input("{} ".format(question))
print("You entered: {}".format(s))
input_and_print("What is your name?")
Additionally you could have the function return the input s.

no this is not possible. well except something like
x=input("tell me:");print("blah %s"%(x,));
but thats not really one line ... it just looks like it

Related

Python print and input on same line

I am trying to execute this but not able to.
Can someone assist?
teamname1 = print(input((plyer1,' Name of your team? '))
teamname2 = print(input(plyer2,' Name of your team? '))
print(teamname1)
print(teamname2)
Three issues:
the first line contains one parenthesis too many
input() takes only one argument, the prompt. If plyer1 is a
string, you must concatenate it
same as in comment: print() does not return anything, and can be
omitted because the prompt of the input() command is already
displayed.
You probably need something like this:
plyer1 = 'parach'
plyer2 = 'amk'
teamname1 = input(plyer1 + ' Name of your team? ')
teamname2 = input(plyer2 + ' Name of your team? ')
print(teamname1)
print(teamname2)
I'm not exactly sure what you're trying to do with the teamname variables. If you could modify the question/code it would help a lot.
As far as print and input on the same line, I think this might be what you're going for.
print("player1" + " " + input("Name of your team: "))
print("player2" + " " + input("name of your team: "))
P.S. There are many tutorials on-line that could help. Make sure to look around first, then come here.

callig str when using functions

im writing some code to print a triangle with so many rows but when i try it it says,
how many rows in the triangle 5
Traceback (most recent call last):
File "U:\School\Homework\year 8\module 3\IT\python\lesson 10\extention task set by Mr Huckitns.py", line 6, in <module>
triangle(5)
File "U:\School\Homework\year 8\module 3\IT\python\lesson 10\extention task set by Mr Huckitns.py", line 5, in triangle
print((x*(str(" ")))(int(i)*(str("*")))((int(row)-int(i))*(str(" "))))
TypeError: 'str' object is not callable
anybodyknow whats going on here
the code i am using is
inttrow=int(input("how many rows in the triangle "))
def triangle(row):
for i in range(1,row):
x=int(inttrow)-int(i)
print((x*(str(" ")))(int(i)*(str("*")))((int(row)-int(i))*(str(" "))))
triangle(5)
The problem is the punctuation in your print statement. You're printing three strings in succession, but you forgot to put any concatenation operation between them. Try this:
print ((x*(str(" "))) + (int(i)*(str("*"))) + ((int(row)-int(i))*(str(" "))))
Further, why are you doing all these type coercions -- all of those variables already have the proper types. Cut it down to this:
print (x*" " + i*"*" + (row-i)*" ")
You are trying to contatenate strings by placing them near each other in the code like this:
("hello")(" ")("world")
Try that on the command line and see what happens. It is not the syntax of the language you are using. Then try using the plus sign.
"hello" + " " + "world"

basic strings and variables python

Write a function, called introduction(name, school) that takes, as input, a name (as a string) and a school, and returns the following text: “Hello. My name is name. I have always wanted to go to school.”
This is my code
def introduction("name","school"):
return ("Hello. My name is ") + str(name) + (". I have always wanted to go to The") + str(school) + (".")
I'm getting this error:
Traceback (most recent call last):
File "None", line 5, in <module>
invalid syntax: None, line 5, pos 23
def introduction("name","school"):
should be
def introduction(name,school):
The names you provide as the formal parameters of the function are essentially variables that the values of the actual parameters get assigned to. Including a literal value (like a string) wouldn't make much sense.
When you call or invoke the function, that is where you provide a real value (like a literal string)
def introduction(name,school):
return ("Hello. My name is ") + str(name) + (". I have always wanted to go to The") + str(school) + (".")
print introduction("Brian","MIT")
The definition of the function should take variables and not strings. When you declare, "introduction("name","school"):", that is what you are doing. Try this:
def introduction(name, school):
Here:
>>> def introduction(name, school):
... return ("Hello. My name is ") + str(name) + (". I have always wanted to go to The") + str(school) + (".")
...
>>> print introduction("Sulley", "MU")
Hello. My name is Sulley. I have always wanted to go to TheMU.
>>>
The arguments to the function are variable names, not string constants, and therefore should not be in quotes. Also, the parentheses around the string constants and the conversions of the arguments to strings in the return statement are not necessary.
def introduction (name,school):
return "Hello. My name is " + name + ". I have always wanted to go to " + school + "."
Now, if you call the function like print(introduction("Seth","a really good steak place")) # Strange name for a school... then the arguments you're calling the function with are string constants and so these you should put in quotes.
Of course, that doesn't apply if the arguments aren't constants...
myname = "Seth"
myschool = "a really good steak place" # Strange name for a school...
print(introduction(myname,myschool))
...and so you are instead providing the variables myname and myschool to the function.

New line for input in Python

I am very new to Python programming (15 minutes) I wanted to make a simple program that would take an input and then print it back out. This is how my code looks.
Number = raw_input("Enter a number")
print Number
How can I make it so a new line follows. I read about using \n but when I tried:
Number = raw_input("Enter a number")\n
print Number
It didn't work.
Put it inside of the quotes:
Number = raw_input("Enter a number\n")
\n is a control character, sort of like a key on the keyboard that you cannot press.
You could also use triple quotes and make a multi-line string:
Number = raw_input("""Enter a number
""")
If you want the input to be on its own line then you could also just
print "Enter a number"
Number = raw_input()
I do this:
print("What is your name?")
name = input("")
print("Hello" , name + "!")
So when I run it and type Bob the whole thing would look like:
What is your name?
Bob
Hello Bob!
# use the print function to ask the question:
print("What is your name?")
# assign the variable name to the input function. It will show in a new line.
your_name = input("")
# repeat for any other variables as needed
It will also work with: your_name = input("What is your name?\n")
in python 3:
#!/usr/bin/python3.7
'''
Read list of numbers and print it
'''
def enter_num():
i = input("Enter the numbers \n")
for a in range(len(i)):
print i[a]
if __name__ == "__main__":
enter_num()
In the python3 this is the following way to take input from user:
For the string:
s=input()
For the integer:
x=int(input())
Taking more than one integer value in the same line (like array):
a=list(map(int,input().split()))

what is wrong in my python code?

#!usr/bin/python
listofnames = []
names = input("Pls enter how many of names:")
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print listofnames
error
inname = input("Enter the name " + str(x))
File "", line 1, in
NameError: name 'Jhon' is not defined
Use raw_input instead. See http://docs.python.org/library/functions.html#raw_input. input will do the same thing as eval(raw_input(prompt)), so entering in Jhon will try to find the symbol Jhon within the file (which doesn't exist). So for your existing script you'd have to input 'Jhon' (notice the set of quotes) in the prompt so the eval will convert the value to a string.
Here's the excerpt warning from the input documentation.
Warning
This function is not safe from user
errors! It expects a valid Python
expression as input; if the input is
not syntactically valid, a SyntaxError
will be raised. Other exceptions may
be raised if there is an error during
evaluation. (On the other hand,
sometimes this is exactly what you
need when writing a quick script for
expert use.)
Below is the corrected version:
#!usr/bin/python
# The list is implied with the variable name, see my comment below.
names = []
try:
# We need to convert the names input to an int using raw input.
# If a valid number is not entered a `ValueError` is raised, and
# we throw an exception. You may also want to consider renaming
# names to num_names. To be "names" sounds implies a list of
# names, not a number of names.
num_names = int(raw_input("Pls enter how many of names:"))
except ValueError:
raise Exception('Please enter a valid number.')
# You don't need x=1. If you want to start your name at 1
# change the range to start at 1, and add 1 to the number of names.
for x in range(1, num_names+1)):
inname = raw_input("Enter the name " + str(x))
names.append(inname)
print names
NOTE: This is for Python2.x. Python3.x has fixed the input vs. raw_input confusion as explained in the other answers.
input gets text from the user which is then interpreted as Python code (hence it's trying to evaluate the thing you entered, Jhon). You need raw_input for both of them and you'll need to convert the number entered (since it's a string) to an integer for your range.
#!usr/bin/python
listofnames = []
names = 0
try:
names = int(raw_input("Pls enter how many of names:"))
except:
print "Problem with input"
for x in range(0, names):
inname = raw_input("Enter the name %d: "%(x))
listofnames.append(inname)
print listofnames
In python3, input() now works like raw_input(). However to get your code to work with Python3 a couple of changes are still required
#!usr/bin/python3
listofnames = []
names = int(input("Pls enter how many of names:"))
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print(listofnames)

Categories