How to add two user data inputs in python? - python

Write a Python program that takes the user's name as input and displays and welcomes them.
Expected behavior:
Enter your name: John
Welcome John
The Python code for taking the input and displaying the output is already provided
#take the user's name as input
name = input("Enter your name: ")
print(name)
#the vaiable that includes the welcome message is alredy provided.
#Please complete this part using the knowledge obtained in this lesson.
greeting = ("Welcome John")
#print the welcome message
print(greeting)
Out put I got with one error

greeting = (f' Welcome {name}')
Or
greeting = ('Welcome ' + name )

The problem I see is an error in your code where you have hard coded the name "John" with the output. What you ought to do instead, is to output the Variable alongside the greeting message.
greeting = (f"Welcome {name}")
Using this will output the welcome message alongwith the name that's entered. What I have done is used an F-string however there's other ways to do it as well. Hope that answer's your question.

You have hard coded the greeting
greeting = ("Welcome John")
Given you have a name the user has provided, you can use string formatting to interpolate that name into your greeting like this:
greeting = (f"Welcome {name}")
(Notice, you put the variable in curly braces)

# take the user's name as input
name = input("Enter your name: ")
print(name)
# Please complete this part using the knowledge obtained in this lesson.
greeting = ("Welcome" +" "+ name)
# print the welcome message
print(greeting)

Related

How do I make a 'properly formatted HTML link for an email address'?

I am in a computer science class. I was just given this assignment today. It was completely blank spare a docstring at the top.
'''
Write a function that returns a properly formatted HTML link for
an email address.
Uber Geek Option:
Include code that checks to see if the email itself is properly formatted
Hacker Option:
Also include code that checks to see if the email is valid
'''
How do I begin this? I have tried sites such as WikiHow and RealPython. This may be an information error, but I am sure my teacher wrote what he meant in this assignment.
EDIT: I fixed most of the code, but I cannot get it to understand and replace the inputted email with the emAdd variable.
import re
def isvalidEmail(email):
pattern = "^\S+#\S+\.\S+$"
objs = re.search(pattern, email)
try:
if objs.string == email:
return True
except:
return False
def emailAddress():
emAdd = input("Enter your email address: ")
if ('#' and '.') and ('.net' or '.com') not in emAdd:
print("Enter a properly formatted email address.")
emailAddress()
else:
cke = isvalidEmail(emAdd)
if cke == True:
print('<a href="mailto:'+emAdd+'?">')
else:
print("enter a valid email.")
emailAddress()
put_me_in_another_file = '<a href="mailto:'+emAdd+'?">'
emailAddress()
file = open("email.html","w")
# Adding input data to the HTML file
file.write("<html>\n<head>\n<title> \nYour Email in A Webpage \
</title>\n</head> <body><h1>Welcome to <u>Your Email</u></h1>\
\n<h2>A hyperlink to send emails to the inputted email should appear below.</h2><a href=mailto:emAdd?>\n</body></html>")
# Saving the data into the HTML file
file.close()

What have I missed?

I'm trying to teach myself Python and am working through some tutorials online. I've created a basic program which asks you to input a name and password (which are stored as variables). It then asks you to re-type them and if they match prints Access Granted.
I've defined some functions with global variables. However if I # out the global declaration my program still seems to work. From what I've read variables not declared as global inside a function should be local. So with the global declaration # out my program shouldn't work. But it does. What have I missed?
import sys
#password = ""
#name = ""
#inputName = ""
#inputPassword = ""
#accountAnswer = ""
def username():
#global inputName
print("What is your name?")
inputName = input()
while name != inputName:
print("Sorry, you are not a registered user.")
print("What is your name?")
inputName = input()
#return
def pwrd():
#global inputPassword
print("Please enter your password:")
inputPassword = input()
while inputPassword != password:
print("Sorry, incorrect Password:")
print("Please re-enter your password:")
inputPassword = input()
continue
#return
print("Hi there, would you like to create an account? (y/n)")
while True:
accountAnswer = input()
if accountAnswer == "y":
break
if accountAnswer == "n":
break
print("That was an incorrect response")
print("Would you like to create an account? (y/n)")
if accountAnswer == "y":
print("Great! Let's get you set up.")
else:
print("OK, no worries.")
sys.exit()
print("Choose a username")
name = input()
print("Now choose a password.")
password = input()
print("let's try logging in.")
username()
pwrd()
print("Access Granted")
print(name, password)
The thing that you should familiarize yourself with is Scope. You can find a lot of info about it on line but in short scope is where your variable is visible.
So in your example, let's try to follow the steps that interpreter is doing when entering your function.
username()
Print text
Assign value from input() to a variable named inputName. Note that it doesn't matter if the variable existed before or not. If it didn't the interpreter will create it.
Enter while loop.
Check if a variable named name is equal to inputName. The interpreter can't see the variable name in current scope, so it tries to look one lever higher, which is your main script. It finds the variable so it uses that one (which you declared in line 51).
I hope that you understand the main concept here. This however should not be used as your default method. It's better to create functions which take arguments rather than using global variables or higher scope.
One small note at the end. I do recommend you to try using an editor like PyCharm. It will warn you about such situations. It will also help you get better with following code style rules (a document is called PEP8) which include how to name variables, where to put and how many spaces etc. It may sound not needed for now but it will save you a lot of changing habits later.
Good luck!

How do i check if a user info is correct python

So i am making a password system.
It ask for the user to enter the password, then check if it's right. I am getting a error with:
%Run HelloPython.py
File "/home/pi/Python Coding/HelloPython.py", line 17
print('Welcome home,', name,)
^
SyntaxError: expected an indented block
Something is wrong.
Code:
print('What is your name?')
# Stores everything typed up until ENTER
name = sys.stdin.readline()
print('Hello', name,'Enter password.')
password = sys.stdin.readline()
if password == ("1"):
print('Welcome home,', name,)
else:
print("Password:", password,"Is incorect. Please try again.")
SyntaxError: expected an indented block
Indent your if-else statements like below.
To check "is equal to", use == instead of = which is an assignment.
readline returns a string, so you should compare it with '1' string.
readline includes a newline \n at the end, so call strip() on it.
import sys
print('What is your name?')
# Stores everything typed up until ENTER
name = sys.stdin.readline()
print('Hello', name, 'Enter password.')
password = sys.stdin.readline().strip()
if password == '1':
print("Welcome home,", name)
else:
print("Password:", password, "Is incorrect. Please try again.")
So I've re-wrote your code. You're forgetting to indent your if-statements. http://www.secnetix.de/olli/Python/block_indentation.hawk
import sys # Import the 'sys' module
print('What is your name?')
name = sys.stdin.readline()
print('Hello ', name, '. Enter password.')
password = sys.stdin.readline()
# Use '=='
if password == 1:
print("Welcome home, ", name)
# Here you need indentation.
else:
print("Password: ", password," is incorect. Please try again.")
This is not your only error, but it is probably the most easily overlooked:
if password = 1:
What's going on here: 1 is getting stored to the variable password (Since = is the storing operator). Then if password is getting evaluated; variables are truthy in python, so that will evaluate to True, regardless of what you had stored in password above.
To remedy this, use == for comparing password, and also since password is a string, put the 1 in quotes so that it is compared as a string.
if password == "1":
You need to fix your indentation as well, python is dependent on whitespace.

Having trouble with the self parameter

I am working on a small project and I am not sure if the error I am getting is due to the IDLE I am using or something I am doing wrong.
I am using OOP in python running on the Wing IDLE. I have the latest version of the python shell running on a Windows 8 PC.
In my program I have a method that takes user input and using that input it creates the parameters required to create a shelf.
'def subject_creator(self):
subject_name = input("Enter the subject name:")
subject_file = subject_name + "file"
name = subject_name
return subject_name, subject_file, name'
Ideally the program would then use the three returned statements namely subject_name, subject_file, and name in opening the new shelf.
'def __init__(self, subject_name, subject_file, name ):
subject_name = shelve.open ("subject_file", "c")
self.name = name
print("The", self.name ,"note has been created")'
while True:
print ("""
1.Create new note
2.Add new term
3.Look up term
4.Exit/Quit
""")
ans= input("What would you like to do?: ")
if ans=="1":
subject_creator()
note = Notebook(subject_name, subject_file, name)
subject_name.sync()
However when I run the program and in my main menu I select choice 1 which runs the code above, I receive and error that states.
<module>
builtins.TypeError: subject_creator() missing 1 required positional argument: 'self'
This is somewhat puzzling as I include the self parameter when I wrote the code for subject creator as shown above. Other than this I have no other errors.
Any feedback would be greatly appreciated.
You are confusing "function" and "method".
In Python, a method is a function defined inside a class scope, and it will receive the object as its implicit first argument:
class Example:
def try_me(self):
print "hello."
You would use it like this:
x = Example()
x.try_me()
and try_me() will receive x as its first (here, ignored) argument. This is useful so that the method can access the object instance's attributes etc.
Contrast this with a regular function, i.e. one defined outside of a class:
def try_me_too():
print "hello."
which is simply invoked like
try_me_too()
Tangentially, your example code does not pick up the values returned by your subject_creator function:
> if ans=="1":
> subject_creator()
> note = Notebook(subject_name, subject_file, name)
The scope where this happens doesn't have variables named subject_name etc. You need to create them somehow.
if ans=="1":
ick, bar, poo = subject_creator()
note = Notebook(ick, bar, poo)
(I chose nonsense variable names mainly to emphasize that these are different from the variables defined, and only available, inside subject_creator.)
Just to complete this, here is a demonstration of how self is useful.
class Otherexample:
def __init__(self, greeting):
self.greeting = greeting
def try_me_also(self):
print self.greeting
use like this:
y = Otherexample("hello.")
y.try_me_also()
Here, the greeting is a property of the object we created; the __init__ method receives it as its argument, and stores it as an attribute of the instance. The try_me_also method uses self to fetch this attribute, and print it.
This line causes your error
subject_creator()
You should change
def subject_creator(self):
subject_name = input("Enter the subject name:")
subject_file = subject_name + "file"
name = subject_name
return subject_name, subject_file, name
to
def subject_creator():
subject_name = raw_input("Enter the subject name:")
subject_file = subject_name + "file"
name = subject_name
return subject_name, subject_file, name
You don't need a parameter in your function if you won't use it.
Also,if you are using python 2.x, consider using raw_input() and not input(). For more info, please read differences between input() and raw_input().

How to identify more than one value in the method using suds python

Hi How to identify more than one value in the particular method.For example my method will take two values to send some balance(eg: amount and account number). I did for one value and I am getting errors if method has more than one value
url='http://www.testfire.net/bank/ws.asmx?WSDL'
client = Client(url)
print client
for method in client.wsdl.services[0].ports[0].methods.values():
print "the existing methods in webservice are:" +method.name
while True:
try:
s = raw_input("Enter the name of the method you want to scan: ")
name= getattr(client.service,s)
break
except suds.MethodNotFound as e:
print "Please enter a valid method."
value=raw_input("enter a value for method: ")
result=name(value)
print result
Pls provide suggestions

Categories

Resources