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()))
Related
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)
I have a txt file with names of people.
I open it and want to get only the names with the length the user entered, using the filter and lambda functions.
The problem is that the list I get is empty [].
names_file = open('names.txt').read().split()
user_choice = input("Enter name length: ")
print(list(filter(lambda c : len(c) == user_choice, names_file)))
What is the problem ?
See this line
user_choice = input("Enter name length: ")
You are taking a string input. If you want to take an integer input you need to write int(input()). I hope this will solve the problem.
user_choice = int(input("Enter name length: "))
should fix it.
My task is to have the user input an unlimited amount of words while using enter.
Example:
(this is where the program asks the user to input names)
Please input names one by one.
Input END after you've entered the last name.
(this is where the user would input the names)
Sarah
Tyler
Matthew
END
(by pressing enter, they are entering the names into a list until they enter END)
I'm not sure where the coding for this will be. I assume I would use a while loop but I'm not sure how. Thanks.
I'm really really new to programming and I'm really lost. This is what I have so far:
def main() :
name = []
print("Please input names one-by-one for validation.")
diffPasswords = input("Input END after you've entered the last name.")
while True :
if
Try using the below while loop:
l = []
while 'END' not in l:
l.append(input('Name: '))
l.pop()
print(l)
Output:
Name: Sarah
Name: Tyler
Name: Matthew
Name: END
['Sarah', 'Tyler', 'Matthew']
it's simply done with a while loop.
name_list=[]
while True:
i = input('enter').rstrip()
if i == 'END':
break
name_list.append(i)
Basically keep on getting a new line but if it equals END\n then stop. The \n is from the enter. Otherwise add it to the list but make sure to omit the last character because that is the newline character(\n) from the enter.
import sys
list = []
while True:
c = sys.stdin.readline()
if c == "END\n":
break
else:
list.append(c[0:-1])
print(list)
I have to write a program that takes user input for a website and keyword, and then reads the source code of the website for that word. I have to code it so it detects many variations of the word (ex. hello vs. hello, vs. hello!) and am not sure how to do this. I have it coded like this so far to detect the exact input, but I'm not sure how to get multiple variations. Any help would be greatly appreciated, thank you!
def main():
[n,l]=user()
print("Okay", n, "from", l, ", let's get started.")
webname=input("What is the name of the website you wish to browse? ")
website=requests.get(input("Please enter the URL: "))
txt = website.text
list=txt.split(",")
print(type(txt))
print(type(list))
print(list[0:10])
while True:
numkey=input("Would you like to enter a keyword? Please enter yes or no: ")
if numkey=="yes":
key=input("Please enter the keyword to find: ")
else:
newurl()
break
find(webname,txt,key)
def find(web,txt,key):
findtext=txt
list=findtext.split(sep=" ")
count = 0
for item in list:
if item==key:
count=count+1
print("The word", key, "appears", count, "times on", web)
def newurl():
while True:
new=input("Would you like to browse another website? Please enter yes or no: ")
if new=="yes":
main()
else:
[w,r]=experience()
return new
break
def user():
name=input("Hello, what is your name? ")
loc=input("Where are you from? ")
return [name,loc]
def experience():
wordeval=input("Please enter 3 words to describe the experience, separated by spaces (ex. fun cool interesting): ")
list=wordeval.split(sep=" ")
rate=eval(input("Please rate your experience from 1-10: "))
if rate < 6:
print("We're sorry you had a negative", list[0], "and", list[2], "experience!")
else:
print("Okay, thanks for participating. We're glad your experience was", list[1], "!")
return[wordeval,rate]
main()
What you're looking for is the re module. You can get indices of the matches, individual match instances, etc. There are some good tutorials here that you can look at for how to use the module, but looping through the html source code line by line and looking for matches is easy enough, or you can find the indices within the string itself (if you've split it by newline, or just left it as one long text string).
I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.
I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.