Simple python code is not working [duplicate] - python

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 5 years ago.
The following code is not working:
person = input('Enter your name: ')
print('Hello', person)
Instead of printing Hello <name> it is giving me the following traceback:
Traceback (most recent call last):
File "C:/Users/123/Desktop/123.py", line 1, in <module>
person = input('Enter your name: ')
File "<string>", line 1, in <module>
NameError: name 'd' is not defined

To read strings you should use:
person = raw_input("Enter your name: ")
print('Hello', person)
When you use input it reads numbers or refers to variables instead. This happens when you are using Python 2.7 or below. With Python 3 and above you have only input function.
Your error states that you entered "d" which is a variable not declared in your code.
So if you had this code instead:
d = "Test"
person = input("Enter your name: ")
print('Hello', person)
And you type now "d" as name, you would get as output:
>>>
('Hello', 'Test')

What is the error?
You used this:
person = input('Enter your name: ')
You should have used this:
person = raw_input('Enter your name: ')
Why these are different
input tries to evaluate what is passed to it and returns the value, whereas raw_input just reads a string, meaning if you want to just read a string you need to use raw_input
In Python 3 input is gone, and raw_input is now called input, although if you really want the old behaviour exec(input()) has the old behaviour.

Related

Create a username using Python

I'm just learning Python and have to create a program that has a function that takes as arguments a first and last name and creates a username. The username will be the first letter of the first name in lowercase, the last 7 of the last name in lowercase, and the total number of characters in the first and last names. For example, Jackie Robinson would be jobinson14. I have to use sys.argv.
This is my code:
import sys
def full_name(first, last):
first = input(first)
last = input(last)
username = lower((first[0] + last[:7])) + len(first+last)
return username
first = sys.argv[1]
last = sys.argv[2]
username = full_name(first, last)
print ("Your username is",username)
When entering Darth Vader
Expected output:
Your username is dvader10
Actual output:
Darth
Please help!
Actual output:
Darth
Not exactly. You are using input(first), which is waiting for you to type something...
Using sys.argv means you need to provide the arguments when running the code
python app.py Darth Vader
And if you remove the input() lines, this would return without prompting for input, and not show Darth
As shown, you are trying to read from arguments and prompt for input.
If you did want to prompt, then you need to remove the import
def full_name(first, last):
return (first[0] + last[-7:] + str(len(first+last))).lower()
first = input('First Name: ')
last = input('Last Name: ')
username = full_name(first, last)
print("Your username is",username)
And just run the script directly. But you say you have to use sys.argv, so the solution you're looking for is to not use input() at all.
When you call the input() function and assign it to first, like this:
first = input(first)
what you're doing is printing first (so "Darth"), waiting for the user to enter something, and then assigning that to first. That's why your script prints Darth -- it's waiting for you to tell it what first is.
But since you already passed the first and last name via the command line, you don't want to do that -- so just remove those two input lines. Make sure to convert the len to a str before you add it to the other strings!
def full_name(first, last):
return (first[0] + last[:7] + str(len(first+last))).lower()
You ask to input names even if they are in sys.argv.
Input("Enter name: ") accepts string that help to understand what you should input.
As OneCricketeer commented, you trying to get first 7 letters instead of last.
Here is an example that accepts names from command line otherwise prompt to input.
import sys
def full_name(_first, _last):
return f"{(_first[0] + _last[-7:])}{len(_first + _last)}"
if __name__ == '__main__':
first = last = ""
if len(sys.argv) == 3:
if sys.argv[1]:
first = sys.argv[1].lower()
if sys.argv[2]:
last = sys.argv[2].lower()
if not first:
first = input("Input first name: ").lower()
if not last:
last = input("Input last name: ").lower()
username = full_name(first, last)
print("Your username is", username)

How to fix : expected at most 1 argument, got 3 [duplicate]

This question already has answers here:
Error - input expected at most 1 argument, got 3
(2 answers)
Closed 3 years ago.
I am trying to ask the user about their favorite subject, but I get the following error message:
Traceback (most recent call last):
File "C:\Users\BillyG\Documents\Revision\ICT\Challenge 5.py", line 2, in
module
favesub = input("Hello what is your favourite subject", firstname, "?")
TypeError: input expected at most 1 arguments, got 3
The code is:
firstname=input("What is your name: ")
favesub = input("Hello what is your favorite subject", firstname, "?")
print ("I love ", favesub, "aswell")
input expects a single string, so unlike print, where you can append multiple arguments and the string will be parsed as is, you have to format the string yourself. For Python 3.6 and higher, user input(f"Hello what is your favourite subject {firstname}?") or input("Hello what is your favourite subject {}?".format(firstname)) if you're using an older version of Python 3.
input() only takes one argument, but you're providing 3.
Try
input(f"Hello what is your favourite subject {firstname}?")
You can concatenate the strings simply using + while asking for user input in the second line. Currently you are passing it three arguments separated by a comma.
firstname=input("What is your name: ")
favesub = input("Hello what is your favourite subject " + firstname + "?")
print ("I love ", favesub," aswell")
# What is your name: Donald
# Hello what is your favourite subject Donald?Politics
# I love Politics aswell
Try this,
favesub = input("Hello what is your favourite subject"+firstname+"?")
problem here is that input() method can only take atmost one argument, whereas you are passing 1.
firstname = input("What is your name: ")
message = "Hello what is your favourite subject "+firstname+" ?"
favesub = input(message)
print ("I love ",favesub," aswell")

NameError when assigning input() to variable (Python2.7.11) [duplicate]

This question already has answers here:
Differences between `input` and `raw_input` [duplicate]
(3 answers)
Closed 3 years ago.
I get a name error even though I'm just trying to put a string into a variable.
I am trying to do this on Python 2.7.11. Does anyone have anything that helps? Upgrading Python is not an option for me.
def translate(phrase):
translation = ""
for letter in phrase:
if letter in " ":
translation = translation + "#"
result = (input("enter a phrase you want encrypted: "))
result = translate(result)
This is the error that's shown:
Traceback (most recent call last):
File "D:\hello\encrydecry\encryption1.py", line 158, in <module
>
result = (input("enter a phrase you want encrypted: "))
File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
In Python 2, when you use input(), Python interprets the input. So when you type hello, hello is interpreted as a variable, and you're essentially doing result = hello. Hence the error NameError: name 'hello' is not defined.
One option is to simply type the input between quotes, so it will be interpreted as a string: 'hello'.
To avoid the input being interpreted altogether, you have to use raw_input() instead of input(), which doesn't interpret the user input and always returns a string:
result = raw_input("enter a phrase you want encrypted: ")
def translate(phrase):
translation = ""
for letter in phrase:
if letter in " ":
translation = translation + "#"
result =raw_input("enter a phrase you want encrypted: ")
result = translate(result)

Python NameError: name 'hello' is not defined [duplicate]

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 7 years ago.
I get a NameError when I attempt to execute the following code with any possible input string in Python 3.0:
def onePerLine(str):
for i in str:
print(i)
word=input("Enter a phrase or word: ")
onePerLine(word)
The error is as follows:
Enter a phrase or word: hello
Traceback (most recent call last):File"C:\Users\R\Documents\Python30\func2.py",line 5, in <module> word=input("Enter a phrase or word: ")
File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
How do i fix this and get my code to run?
PS: I'm a newbie to python and to programming in general. Any assistance would be appreciated.
You are using Python 2, so you need to use raw_input
>>> x = input('')
hello
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
x = input('')
File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
Using raw_input
>>> x = raw_input('')
hello
>>> x
'hello'
You are using python 2 and you need to use raw_input instead of input which evaluate the string and assumes it as a variable name.
input([prompt])
Equivalent to eval(raw_input(prompt)).
...
Consider using the raw_input() function for general input from users.

How to define a variable inside the print function?

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

Categories