Building upon existing function - python

I was just playing around with functions in order to further my understanding of them and I was curious, is it at all possible to return the users first name and last initial using the following function without adding any additional functions?
name = raw_input("Please enter your full name: ")
def username(a):
print(a[0:6]+a[-1])
username(name)

If the length of input names can vary and number of names then you will have to use another function split and index. If the user can just enter a single name you will need to add an if or try...except.
a[:a.index(' ')]) will get the first name, from the beginning of the input to the first space
index returns ValueError if the character isn't found so if they might enter just first name surround with try...except
a.split()[-1][0] will get the first letter of the last name even if they enter more than two names (Billy Bob Joe -> Billy J)
name = raw_input("Please enter your full name: ")
def username(a):
print(a[:a.index(' ')]+' '+a.split()[-1][0])
username(name)

Your current function assumes a length of first and last name. You could try
print(a.split()[0] + ' ' + a.split()[1][0]). The split() will change the string to a list of two elements, element 0 is the first name and element 1 is the last name.
a[-1] will give you the last letter of your string, which it sounds like you don't want this for your purpose.

name = raw_input("Please enter your full name: ")
def username(a):
fullname = a.strip().split(' ')
if len(fullname) < 2:
print('Error: last name required')
print('Type: firstname <middle name> last name')
exit(1)
try:
print('%s %s' % (fullname[0], fullname[-1][0]))
except IndexError:
exit(1)
username(name)

This is how I have managed to implement the info that you folk have provided me.
'''
code to input full name and convert into username consisting of first + first
initial of last name or first and first initial of first name if input is one name.
'''
def fullname():
name = raw_input("Please enter your full name: ").lower()
try:
name = (name[:name.index(' ')]+''+name.split()[len(name.split())-1][0])
except:
name = name[0:]+name[0]
return name
# code to generate exponential numbers
def print_exponential():
base = int(raw_input("Please select a base number: \n"))
power = int(raw_input("Please select a power number: \n"))
exponential = 1
while power>0:
exponential = exponential * base
print base
if power >1:
print "*"
power = power -1
print "=%d" % exponential
'''
code to generate interactive menu with an error return for incorrect selection and exit clause.
'''
ans=True
while ans:
print ("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""")
ans=raw_input("What would you like to do? ").upper()
if ans=="U":
print fullname()
elif ans=="E":
print print_exponential()
elif ans=="Q":
print("\n Goodbye")
break
elif ans !="":
print("\n Error: Choice must be U, E or Q")

Related

How to know if any python function is asking for input or not and if asking then enter input? [duplicate]

This question already has answers here:
How can I mock user input (from "input" in 3.x, or "raw_input" in 2.x) for a unit test?
(7 answers)
Closed last month.
Suppose I have a function like this:
import random
def randomfunc():
x = random.randint(0,10)
# some code here which generates a name/text randomly and stores it in a .txt file locally/cloud
if x%2 == 0:
y=input("Enter your name:") # I need to enter that name/text exact here
print("Your name is ",y)
else:
print("You got an odd number")
Now, whenever I run this function then I want it to detect if it is asking for any input or not.
If it's asking for input then enter the input else do nothing.
Remember I can't change anything inside the function.
I tried this:
import builtins
from unittest.mock import patch
with patch('builtins.input') as input_mock:
input_mock.side_effect = [
'My Name',
]
print(input('Enter your name:'))
But the problem here is that the input is predetermined before the execution of the input statement.
In my case, my input value will be decided while the execution of randomfunc() as my input value is dynamic/it changes with time.
Also, when using wexpect module, it gives me OSError: [WinError 6] The handle is invalid.
Please suggest me some solution.
I believe that is what you want
def randomfunc():
x = random.randint(0, 10)
if x % 2 == 0:
y = input("Enter your name:")
print("Your name is ", y)
else:
print("You got an odd number")
def better_randomfunc(user_input):
with mock.patch('builtins.input') as MockClass:
MockClass.return_value = user_input
randomfunc()
This will replace every input() in randomfunc with your own one that'll return user_input. So if there's no input function it's going to do nothing like you asked.
To use this just call the better_randomfunc
better_randomfunc("My name")
And expect double space, if you want to get rid of that do print("Your name is", y) instead of print("Your name is ", y)
Edit: I improved it a little bit so that you can modify it based on prompt
import random
from unittest import mock
def randomfunc():
x = random.randint(0, 10)
if x % 2 == 0:
y = input("Enter your name: ")
print("Your name is", y)
else:
print("You got an odd number")
def better_input(prompt, user_input):
print(prompt + user_input)
return user_input
def better_randomfunc(user_input):
with mock.patch('builtins.input') as MockClass:
MockClass.side_effect = lambda prompt: better_input(prompt, user_input)
randomfunc()
better_randomfunc("My name")
You can replace the builtin input function
import random
input_values = [1,2,3,4]
input_iterator = iter(input_values)
def randomfunc():
x = random.randint(0,10)
if x%2 == 0:
y=input("Enter your name:")
print("Your name is ",y)
else:
print("You got an odd number")
def custom_input(v):
global input_iterator
print('custom input called')
# input(*args, **kwargs)
return next(input_iterator)
setattr(__builtins__, 'input', custom_input)
while(True):
try:
randomfunc()
except StopIteration:
print('done')
break
You got an odd number
custom input called
Your name is 1
custom input called
Your name is 2
custom input called
Your name is 3
You got an odd number
You got an odd number
You got an odd number
custom input called
Your name is 4
You got an odd number
custom input called
done

Checking if an input is an int after slicing a str

I'm working on a homework assignment (honestly been working for a while now) where we take input from the user, slice the string, and store the new strings in two different variables. The second part of the split string is supposed to be a number and I'm attempting to write an if statement to check if it is indeed a number. The problem is it's not because I split a string, so it's defined as a str. I know I could redefine the variable to an int() but that would produce an error if they weren't to enter an integer. Sorry if this isn't clear, this is my first question! (I can also post a screenshot of the instructions if that would be more helpful, I just don't know if that's encouraged on here.)
data_title = input("Enter a title for the data: ")
print("You entered: ", data_title)
column1 = input("Enter the column 1 header: ")
print("You entered: ", column1)
column2 = input("Enter the column 2 header: ")
print("You entered: ", column2)
data_point = input("Enter a data point (-1 to stop input): ")
while data_point != -1:
if ',' in data_point:
if data_point.count(',') < 2:
data_split = data_point.split(",")
data_stg = data_split[0]
data_int = data_split[1]
if data_split[1].isdigit() is True:
print("Data string: ", data_stg)
print("Data integer: ", data_int)
data_point = input("Enter a data point (-1 to stop input): ")
else:
print("Error: Comma not followed by an integer.")
data_point = input("Enter a data point (-1 to stop input): ")
else:
print("Error: Too many commas in input.")
data_point = input("Enter a data point (-1 to stop input): ")
else:
print("Error: No comma in string.")
data_point = input("Enter a data point (-1 to stop input): ")
The problem is in the in the 3rd if loop nested in the while loop. I have to make sure their input has an integer after the comma.
if data_split[1].isdigit() is True:
print("Data string: ", data_stg)
print("Data integer: ", data_int)
data_point = input("Enter a data point (-1 to stop input): ")
else:
print("Error: Comma not followed by an integer.")
data_point = input("Enter a data point (-1 to stop input): ")
As you give me the captured image, I couldn't see the full requests.
So I made an example for you.
while True:
a = input('please give me your data :')
if ',' not in a:
try:
if int(a) == -1: break
except:
pass
print( 'please give me the seperated inputs wiht ","')
else:
b, c = a.split(',')
try:
c = int(c)
except:
print( 'please give me int !!')
else:
print( b, c)
I believe this code would help you see what python is.

How can I make a python3 program not crash if it tries to add a string and a number together

Source code
import sys
hi = input("Input a number ")
yo = input("Input a second number ")
total = int(hi) + int(yo)
def convertStr(s):
try:
ret = int(s)
print(int(total))
except ValueError:
ret = str(total)
print("There was an error")
convertStr(total)
How can I make it so that the python can add two inputs together but not crash when I put a string in one of the values?
You can use your function convertStr(s) on input hi and yo. If input is not a number then ask again for input.

Python not too hard, just struggling with variable

Code:
loop = 0
def main():
while loop == 0:
Num = input("Please Enter The Number Of People That Need The Cocktails ")
print()
print(" Type END if you want to end the program ")
print()
for count in range (Num):
with open("Cocktails.txt",mode="w",encoding="utf-8") as myFile:
print()
User = input("Please Enter What Cocktails You Would Like ")
if User == "END":
print(Num, "Has Been Written To The File ")
exit()
else:
myFile.write(User+"/n")
myFile.write(Num+"/n")
print()
print(User, "Has Been Written To The File ")
Error:
line 9, in main for count in range (Num): TypeError: 'str' object
cannot be interpreted as an integer
I'm trying to set the variable as the number of times it will repeat how many cocktails they would like.
Example:
How many cocktails ? 6
The script should then ask the user to enter what cocktails he wants six times.
In Python, input() returns a string by default. Change Num to:
Num = int(input("Please Enter The Number Of People That Need The Cocktails "))
Also
MyFile.write(Num + "\n")
should read:
MyFile.write(str(Num) + "\n")
And just for the record, you can replace:
loop = 0
while (loop == 0):
with:
while True:
Cast int() on your input to make Num a workable integer. This has to be done because in Python 3, input always returns a string:
Num = int(input("Please Enter The Number Of People That Need The Cocktails "))
With your code in it's current state, you are trying to construct a range from a string, which will not work at all as range() requires an integer.
EDIT:
Now you must replace:
myFile.write(Num+"/n")
with:
myFile.write(str(Num)+"/n")
Num is an integer at this point, so you must explicitly make a string to concatenate it with a newline character.

Python program not accepting decimal raw input

I am working on small python payroll project where you enter employee name, wage, and hours worked. When I enter decimals for the wage input, I am getting "invalid entry" because of my exception handling. Why are decimals being returned as invalid? Also, how can I loop this program so that it keeps the same 3 questions until the user types "Done"?
Any help will be greatly appreciated!
Thanks!
import cPickle
def getName():
strName="dummy"
lstNames=[]
strName=raw_input("Enter employee's Name: ")
lstNames.append(strName.title() + " \n")
def getWage():
lstWage=[]
strNum="0"
blnDone=False
while blnDone==False: #loop to stay in program until valid data is entered
try:
intWage=int(raw_input("Enter employee's wage: "))
if intWage >= 6.0 and intWage <=20.0:
lstWage.append(float(strNum)) #convert to float
blnDone=True
else:
print "Wage must be between $6.00 and $20.00"
except(ValueError): #if you have Value Error exception. Explicit on error type
print "Invalid entry"
def getHours():
lstHours=[]
blnDone=False
while blnDone==False: #loop to stay in program until valid data is entered
try:
intHrs=int(raw_input("Enter number of hours worked: "))
if intHrs >= 1.0 and intHrs <=60.0:
blnDone=True
else:
print "Hours worked must be 1 through 60."
except(ValueError): #if you have Value Error exception. Explicit on error type
print "Invalid entry"
def getDone():
strDone=""
blnDone=False
while blnDone==False:
try:
srtDone=raw_input("Type \"DONE\" if you are finished entering names, otherwise press enter: ")
if strDone.lower()=="done":
blnDone=True
else:
print "Type another empolyee name"
except(ValueError): #if you have Value Error exception. Explicit on error type
print "Invalid entry"
##### Mainline ########
strUserName=getName()
strWage=getWage()
strHours=getHours()
srtDone1=getDone()
Here's the core of it:
>>> int("4.3")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '4.3'
You can't convert a string to an integer if it's not an integer. So when you do intWage=int(raw_input("Enter employee's wage: ")) it throws the ValueError. Perhaps you should convert it directly to float.
Because you're converting the input to int:
intWage=int(raw_input("Enter employee's wage: "))
You are assuming that the wage is an integer, which by definition does not have a decimal place. Try this:
intWage=float(raw_input("Enter employee's wage: "))
Try using
intWage=int(float(raw_input("Enter employee's wage: ")))
This will accept a decimal number as input.
Error w/ Floats
As others said before, you are assuming the input will be a float. Either use float() or eval()instead of int():
intWage = float(raw_input("Enter employee's wage: "))
Or use input() instead of int(raw_input()):
intWage = input("Enter employee's wage:")
Both will accomplish the same thing. Oh, and change intWage to floatWage atleast, or even better, don't use Hungarian Notation.
The Code
As for your code, I did a couple of things:
Used break and/or return to terminate loops instead of keeping track of booleans (that's the whole purpose of the break and continue statements)
Changed intWage to floatWage
Rewrote number comparisons in a more concise way (x <= y and x >= z can be written as z >= x >= y)
Added return statements. I don't get why you didn't put them yourself, unless you wanted to assign None to strUserName, strWage and strHours)
Added a loop as you requested when asking for an employee's details.
Modified getDone() to work w/ the loop.
import cPickle
def getName():
strName = "dummy"
lstNames = []
strName = raw_input("Enter employee's Name: ")
lstNames.append(strName.title() + " \n")
return strName
def getWage():
lstWage = []
strNum = "0"
while True: #Loop to stay in program until valid data is entered
try:
floatWage = float(raw_input("Enter employee's wage: "))
if 6.0 <= floatWage <= 20.0:
lstWage.append(floatWage)
return floatWage
else:
print "Wage must be between $6.00 and $20.00"
except ValueError: #Catches ValueErrors from conversion to float
print "Invalid entry"
def getHours():
lstHours = []
while True: #loop to stay in program until valid data is entered
try:
intHrs=int(raw_input("Enter number of hours worked: "))
if 1.0 <= intHrs <= 60.0:
return intHrs
else:
print "Hours worked must be 1 through 60."
except ValueError: #Catches ValueErrors from conversion to int
print "Invalid entry"
def getDone():
strDone = ""
while True:
srtDone = raw_input('Type "DONE" if you are finished entering names, otherwise press enter: ')
if strDone.strip().lower() == "done":
return True
else:
print "Type another empolyee name"
while not getDone():
strUserName = getName()
strWage = getWage()
strHours = getHours()
An Example of break and continue
The break statements inside a loop (for and while) terminate the loop and skip all 'else' clauses (if there are any).
Thecontinue statements skips the rest of the code in the loop and the continues the loop as if nothing happened.
The else clause in a for...else construct, executes its code block when the loop exhausted all the items and exited normally, i.e., when it's not terminated by break or something.
for no in range(2, 10):
for factor in range(2, no):
if no % factor == 0:
if factor == 2:
print "%d is even" % no
continue
# we want to skip the rest of the code in this for loop for now
# as we've already done the printing
print "%d = %d * %d" % (no, factor, n/x)
break
# We've asserted that the no. isn't prime,
# we don't need to test the other factors
else:
# if 'break' wasn't called
# i.e., if the loop fell through w/o finding any factor
print no, 'is a prime number'

Categories