I am learning how to use Python. I would like to learn how I can pass in arguments for a function. In Java I know we can use BufferedReader or Scanner to receive user input. How do we get user input with Python? I have a function to print spaces based on user input. How do I do this?
def right_justify(s):
s = " " * 70 - s.len()
print(s)
right_justify(s)
I want to print enough spaces so s's rightmost character appears in the 70th column on the user's screen.
Stolen from: https://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard
Raw_Input
raw_input is used to read text (strings) from the user:
name = raw_input("What is your name? ")
print "your name is: ",name
type(name)
output:
What is your name? fred
your name is: fred
type 'str'>
Related
I am searching a text file that is a "phoneBook" for an assignment and am using regex finditer, but if a name has the letter a in it twice it prints that line twice which is what I am trying to avoid. Also is there a way to have it ignore case?
def searchPhonebook(s): #This will search the phonebook(s) for the inputed data that is assigned to d
print()
d=input("Please enter the Name, Character, Phone Number, or a number: ") #Variable d which is the inputted data
print()
import re
pattern = re.compile(d)
for line in open("phone.txt"):
for match in re.finditer(pattern,line):
print(line)
So when I search 'a' it returns
Jack Hammer,277-4829
Jack Hammer,277-4829
Mike Rafone,345-3453
Earl Lee Riser,701-304-8293
So I would like it to return each one once, and also find capitalization of 'a', like Abby
Don't use findall(). Just test whether the line matches the pattern:
for line in open("phone.txt"):
if re.search(pattern, line):
print(line)
Actually, I'm not sure why you're using re at all. Do your users really enter regular expression patterns? If they're just entering a plain string, use if d in line:
I am making a small project in python that lets you make notes then read them by using specific arguments. I attempted to make an if statement to check if the string has a comma in it, and if it does, than my python file should find the comma then find the character right below that comma and turn it into an integer so it can read out the notes the user created in a specific user-defined range.
If that didn't make sense then basically all I am saying is that I want to find out what line/bit of code is causing this to not work and return nothing even though notes.txt has content.
Here is what I have in my python file:
if "," not in no_cs: # no_cs is the string I am searching through
user_out = int(no_cs[6:len(no_cs) - 1])
notes = open("notes.txt", "r") # notes.txt is the file that stores all the notes the user makes
notes_lines = notes.read().split("\n") # this is suppose to split all the notes into a list
try:
print(notes_lines[user_out])
except IndexError:
print("That line does not exist.")
notes.close()
elif "," in no_cs:
user_out_1 = int(no_cs.find(',') - 1)
user_out_2 = int(no_cs.find(',') + 1)
notes = open("notes.txt", "r")
notes_lines = notes.read().split("\n")
print(notes_lines[user_out_1:user_out_2]) # this is SUPPOSE to list all notes in a specific range but doesn't
notes.close()
Now here is the notes.txt file:
note
note1
note2
note3
and lastly here is what I am getting in console when I attempt to run the program and type notes(0,2)
>>> notes(0,2)
jeffv : notes(0,2)
[]
A great way to do this is to use the python .partition() method. It works by splitting a string from the first occurrence and returns a tuple... The tuple consists of three parts 0: Before the separator 1: The separator itself 2: After the separator:
# The whole string we wish to search.. Let's use a
# Monty Python quote since we are using Python :)
whole_string = "We interrupt this program to annoy you and make things\
generally more irritating."
# Here is the first word we wish to split from the entire string
first_split = 'program'
# now we use partition to pick what comes after the first split word
substring_split = whole_string.partition(first_split)[2]
# now we use python to give us the first character after that first split word
first_character = str(substring_split)[0]
# since the above is a space, let's also show the second character so
# that it is less confusing :)
second_character = str(substring_split)[1]
# Output
print("Here is the whole string we wish to split: " + whole_string)
print("Here is the first split word we want to find: " + first_split)
print("Now here is the first word that occurred after our split word: " + substring_split)
print("The first character after the substring split is: " + first_character)
print("The second character after the substring split is: " + second_character)
output
Here is the whole string we wish to split: We interrupt this program to annoy you and make things generally more irritating.
Here is the first split word we want to find: program
Now here is the first word that occurred after our split word: to annoy you and make things generally more irritating.
The first character after the substring split is:
The second character after the substring split is: t
I am taking a beginners Python course and am currently creating this sample dictionary:
dictVar = {25:"The square root of 5","Vitthal":"SOME DUDE'S NAME",3.14:"Pi"}
The course is teaching how to use an interactive prompt to request the name of a Key in the dictionary which assigns it to the variable "inputKeyToDelete"
inputKeyToDelete = input("Please enter the key you wish to delete from the dictionary. Your key to delete is: ")
When I enter the key Vitthal the key-value pair is deleted, but when I enter the key 25 or 3.14 nothing occurs which is the cause for my question.
the instructor is using the following to perform the lookup\delete.
if inputKeyToDelete in dictVar:
dictVar.pop(inputKeyToDelete)
print("Ok, the key-value pair for Key '" + inputKeyToDelete + "' has been removed.")
Any tips is appreciated.
input always returns a string in python 3. "25" != 25 in python, so the key isn't found. You need to add code to deal with numeric keys. Here is one way:
inputKeyToDelete = input('enter a number:')
try:
inputKeyToDelete = eval(inputKeyToDelete)
except NameError:
pass
print (inputKeyToDelete)
print(type(inputKeyToDelete))
Or just change your example to only use string keys.
Note: In python 2, input would convert to integer for you, which might be confusing you a bit.
Replace your code with below line. Take user input and type cast to int because python takes string as a input.
inputKeyToDelete = int(input("Please enter the key you wish to delete from the dictionary. Your key to delete is: "))
import sys
super_heroes = {'Iron Man' : 'Tony Stark',
'Superman' : 'Clark Kent',
'Batman' : 'Bruce Wayne',
}
print ('Who is your favorite Superhero?')
name = sys.stdin.readline()
print ('Do you know that his real name is', super_heroes.get(name))
I'm doing a simple code here that should read an input in a dictionary and print it out after a string of letters, but when ran it prints out
"
Who is your favorite Superhero?
Iron Man
Do you know that his real name is None
"
Even Though the input is in my dictionary.
Your input is having a newline at the end of the line.
I have tried it online REPL. Check it
try following to resolve it.
name = sys.stdin.readline().strip()
After stripping Check here
sys.stdin.readline() returns the input value including the newline character, which is not what you expect. You should replace sys.stdin.readline() with input() or raw_input(), which are really more pythonic ways to get input values from the user, without including the newline character.
raw_input() is preferable to ensure that the returned value is of string type.
To go a little bit further, you can then add a test if name in super_heroes: to perform specific actions when the favorite superhero name is not in your dictionary (instead of printing None). Here is an example:
super_heroes = {'Iron Man' : 'Tony Stark',
'Superman' : 'Clark Kent',
'Batman' : 'Bruce Wayne',
}
print ('Who is your favorite Superhero?')
name = raw_input()
if name in super_heroes:
print ('Do you know that his real name is', super_heroes[name], '?')
else:
print ('I do not know this superhero...')
sys.std.readline() appends a line break at the end of user input you may want to replace it before getting your Super Hero:
name = name.replace('\n','')
First off, here's the code. (Still new in function creating)
Function Testing!!
def UserInfo(name, age, birth):
"""Read this by doing UserInfo__doc__"""
print("Name:",name)
print("Age:",age)
print("Birth:",birth)
return
n_input=input("Name?>> ")
a_input=int(input("Age?>> "))
b_input=input("Birth date?(MM DD YYYY)>> ")
UserInfo(n_input, a_input, b_input)
CodeOutput
('name:', 'Jaymz')
('age:', 25)
('birth:', '02 26 1991')
The int portion of the code outputs no " ' " (which I knew) but still with "()" and ","...
The string portion outputs all the stuff I don't want surrounding my output...
How would you get rid of that in your code?(I learn by seeing other code first on how people do it)
ps. Brainfart?.... Do I have to do a "format" on the output code? or is format only for numbers?
you get this output because you're using python 2.x. Python 2 thinks you're printing a tuple. Python 3 would issue what you want.
As jojonas suggested, using from __future__ import print_function also works for all versions. You're not able to use print without parentheses after importing that, which is for the best.
But ...
To treat all cases, use format instead (using {} to indicate the location of the string to insert):
def UserInfo(name, age, birth):
"""Read this by doing UserInfo__doc__"""
print("Name: {}".format(name))
print("Age: {}".format(age))
print("Birth: {}".format(birth))
Note: this also works but is not as powerful:
print("Name: "+name) # would need `str` for integer, ex `str(age)`
print("Name: %s" % name) # old-style formatting