Define a function generateNChars(a_nNum, a_Char) that takes an integer a_nNum and a
character a_Char and returns a string, a_nNum characters long
def generateNChars(a_nNum, a_Char):
for i in range (0, a_nNum):
print(a_Char, end = "")
nNum = int(input("Entyer a number: "))
strChar = input("Enter a character: "))
result = generateNChars(nNum, strChar)
print(result)
I got "None" after printing this code. How can I fix this??
You need to add return keyword to return the value. When you don't use a return keyword, it returns None by default. Therefore when you print the function, you receive None. Also, keep in mind that a loop ends when return is used. So, instead of using a for loop, you can multiply, which will return the string repeated n number of times.
def generateNChars(a_nNum, a_Char):
return a_Char*a_nNum
nNum = int(input("Entyer a number: "))
strChar = input("Enter a character: "))
result = generateNChars(nNum, strChar)
print(result)
You have to return the string from the function. Now, the returned string gets assigned to the result variable and you can print it.
def generateNChars(a_nNum, a_Char):
temp = ""
for i in range (0, a_nNum):
temp+=a_Char
return temp
nNum = int(input("Entyer a number: "))
strChar = input("Enter a character: "))
result = generateNChars(nNum, strChar)
print(result)
Related
This question already has answers here:
Why is this printing 'None' in the output? [duplicate]
(2 answers)
Closed 1 year ago.
str = input("Please enter y to start the program: ")
while str == 'y':
def printNTimes(s, n):
for i in range(n):
print(s)
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
allTogether = printNTimes(phrase, number)
print(allTogether)
print()
str = input("Please enter y if you want to continue: ")
print("DONE")
Output:
Please enter y to start the program: y
Enter a string: Hi
Enter a positive number: 3
Hi
Hi
Hi
None
Please enter y if you want to continue:
You don't need print(allTogether), or the variable itself, because when you print it, you get an extra None (because the function returns None i.e, it does not return anything).
Also, put the function outside the while loop so that it is easier to read.
def printNTimes(s, n):
for i in range(n):
print(s)
str = input("Please enter y to start the program: ")
while str == 'y':
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
printNTimes(phrase, number)
print()
str = input("Please enter y if you want to continue: ")
print("DONE")
Just call the function. You could use return and then print the function, but this might be easier.
The problem is the function printNtime is actually being used as a subroutine, meaning it doesn't RETURN any values.
I am not sure what you want as a final output so here's two solution.
IF USED AS SUBROUTINE: just remove the print(allTogether)
IF USED AS A FUNCTION: you need to create a string variable in the function and return it.
def printNTimes(s, n):
mystring = ""
for i in range(n):
mystring = mystring + s + "\n"
return mystring
The issue you're seeing is because your routine, printNTimes(), returns a None value. You say:
allTogether = printNTimes(phrase, number)
print(allTogether)
allTogether is set to None because printNTimes does not return a value. When you call print(allTogether), that's what is printing the None.
It sounds like you intended your printNTimes() routine to assemble one big string of all the output and return it, which you would then print out via the print(allTogether) call. But your printNTimes() routine is calling the print() method and outputing the text then. So, you need to rewrite your printNTimes() method. Also, note that defining that function inside the loop is not necessary. Once is sufficient. So something like this should suffice:
def printNTimes(s, n):
s_out = ""
for i in range(n):
s_out += s + '\n'
return s_out
str_ = input("Please enter y to start the program: ")
while str_ == 'y':
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
allTogether = printNTimes(phrase, number)
print(allTogether)
print()
str_ = input("Please enter y if you want to continue: ")
print("DONE")
Also note that I renamed your str variable to str_. str is a Python type, a reserved word that should not be reused.
import random
userask = float(input("enter number: "))
userask = userask + ((random.randrange(20)*userask)/random.randint(3, 100))
print("new value is " + str(userask))
Let's say my input is 123.0123
I want the program to force the new value after such operation to have the same number of digits as my initial input, rounding the result.
An example: my input is 102.31, the new value should have two digits and be rounded.
I have read round() docs but could not find something useful for this. how would you do it?
You can try this:
import random
userask = input("enter number: ")
lst = userask.split('.')
digits = 0 if len(lst)==1 else len(lst[1])
userask = float(userask)
userask = userask + ((random.randrange(20)*userask)/random.randint(3, 100))
print("new value is " + '{:.{}f}'.format(digits).format(userask))
You can do the following:
import random
import re
inp = input("enter number: ")
if '.' in inp:
num_digits = len(inp.split('.')[1])
else:
num_digits = 0
val = float(inp)
val = val + ((random.randrange(20)*val)/random.randint(3, 100))
if num_digits:
res = round(val, num_digits)
else:
res = int(val)
print("new value is " + str(res))
This code will work also for int's as well for float's, notice that the second if is not mandatory if you don't mind that your output will be printed as float, meaning that for an int it will have a 0 in the decimal place (13 -> 13.0)
Notice
You should always check the input entered to match the desired behaviour of your program, in this case you should probably check that the value entered has the proper "looks" of a number either float or int.
In this case you could do something like:
checker = re.compile('^[0-9]+.?[0-9]*$')
is_valid = bool(checker.match(inp))
and if is_valid isn't True then the value entered is problematic
Given that there are two inputs- a String and a number.
I wish to append the string with the same .
Eg:
Input:
a 10
Output:
add a to the String 'a' such that it appears 10 times.
aaaaaaaaaa
another example:
Input:
ab 5
OUTPUT:
ababababab
You can have a function like below:
In [1389]: def myfunc(string, number):
...: s = string * number
...: return s
In [1391]: string = input("Enter string:")
In [1392]: number = input("Enter number:")
In [1396]: myfunc(string, number)
Out[1396]: 'aaaaaaaaaa'
Python multiplies the string to number if given like 'a' * 2.
It will Help You
num = int(input()) #for how many times we want to print string
string = input() # String which we want to print
for i in range(num): # loop will run for num (User Input) times which come from input
print(string)
if you want to print in a single line
print(string , end = " ")
Think Twice , Code Once
Simply You can do with using * operator
n = int(input("Enter a number"))
string = input("Enter a String")
print(string*n) # it prints your string n times
With Function
def num_multi(n , s):
return n*s
number = int(input("Enter a number"))
string = input("Enter a String")
print(number*string)
Python 3.x:
def printstring(string,number):
print(string * number)
return
number1 = int(input("Enter here: "))
string1= input("enter a number")
print(printstring(string1,number1))
I have an assignment where we have to convert alphanumeric phone numbers into just numbers. For example "555-PLS-HELP" should convert into "555-757-4357". I wrote some of it but it keeps giving me incorrect output.
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = str(input("Please enter a phone number: "))
counter = len(phone_number[:4])
total = phone_number[:4]
while counter > 0:
alpha = phone_number[-counter]
if alpha.isalpha():
total += num[alph.index(alpha)]
else:
total += alpha
counter -= 1
print(total)
I keep getting weird output.
For example:
Please enter a phone number: '555-PLS-HELP'
Gives:
555-4357
There are a few things to consider in your code:
Changing your first slice to counter = len(phone_number[4:]) produces a working solution: you'd like to iterate for the length of the rest of the number rather than the length of the area code prefix.
A simple for n in phone_number is preferable to taking len() and iterating using a counter variable and indexing from the rear with -counter, which is non-intuitive.
input() returns a str; there's no need for a superfluous cast.
This is a perfect situation for a dictionary data structure, which maps keys to values and is an explicit version of what you're already doing. Use zip to combine your strings into a dictionary.
In the list comprehension, each character is looked up in the keypad dictionary and its corresponding entry is returned. Using the dict.get(key, default) method, any items not present in the dictionary will be default.
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
keypad = dict(zip(alph, num))
phone_number = input("Please enter a phone number: ")
print("".join([keypad.get(x, x) for x in phone_number]))
Try it!
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = str(input("Please enter a phone number: "))
counter = len(phone_number)
total = ''
while counter > 0:
alpha = phone_number[-counter]
if alpha.isalpha():
total += num[alph.index(alpha)]
else:
total += alpha
counter -= 1
print(total)
Test:
Please enter a phone number: '555-PLS-HELP'
Output:
555-757-4357
Try the following:
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
# converts the above lists into a dict
lookup = dict(zip(alph, num))
phone_number = input("Please enter a phone number: ")
result = ''
for c in phone_number:
# if needs changing
if c.isalpha():
result += lookup[c.upper()]
# simply append otherwise
else:
result += c
print(result)
Result:
Please enter a phone number: 555-PLS-HELP
Output:
555-757-4357
You could just iterate through the inputted number, check if it's alphabet and get the corresponding number if so, all in one-line:
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = input("Please enter a phone number: ")
print(''.join([num[alph.index(x.upper())] if x.isalpha() else x for x in phone_number]))
Sample run:
Please enter a phone number: 555-PLS-HELP
555-757-4357
If it's an alphabet, this gets the index of the alphabet from alph and use that to look up in the num to get corresponding number. In the else case, just copies the number.
Why you are considering only last 4 characters of an a-priori unknown string? You could search first if phone_number has some alphabetic characters, and if it does, then starting from the first occurrence of such an alphabetic character you can replace it with the correct digit. This works for capital letters:
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = raw_input("Please enter a phone number: ")
def fstAlpha(string):
for i in range(0,len(string)):
if string[i].isalpha():
return i
return -1
index = fstAlpha(phone_number);
if index != -1:
for i in range(index,len(phone_number)):
if(phone_number[i].isalpha()):
to_replace = phone_number[i]
replace_with = num[alph.index(to_replace)]
phone_number = phone_number.replace(to_replace,replace_with)
print phone_number
Trying to write a function which takes input of 4 digit numbers and compares them, output of Ys and Ns to try and check if they are the same. EG 1234 and 1235 would output YYYN. At the minute it's very inefficient to keep using all these append commands. How could I simplify that?
def func():
results=[]
firstn= str(input("Please enter a 4 digit number: "))
secondn= str(input("Please enter a 4 digit number: "))
listone= list(firstn)
listtwo= list(secondn)
if listone[0]==listtwo[0]:
results.append("Y")
else:
results.append("N")
if listone[1]==listtwo[1]:
results.append("Y")
else:
results.append("N")
if listone[2]==listtwo[2]:
results.append("Y")
else:
results.append("N")
if listone[3]==listtwo[3]:
results.append("Y")
else:
results.append("N")
print(results)
Furthermore, how can I validate this to just 4 digits for length and type IE. Nothing more or less than a length of four / only numerical input? I have been researching into the len function but don't know how I can apply this to validate the input itself?
For the validation, you can write a function that will ask repeatedly for a number until it gets one that has len 4 and is all digits (using the isdigit() string method).
The actual comparison can be done in one line using a list comprehension.
def get_number(digits):
while True:
a = input('Please enter a {} digit number: '.format(digits))
if len(a) == digits and a.isdigit():
return a
print('That was not a {} digit number. Please try again.'.format(digits))
def compare_numbers(a, b):
return ['Y' if digit_a == digit_b else 'N' for digit_a, digit_b in zip(a, b)]
first = get_number(4)
second = get_number(4)
print(compare_numbers(first, second))
I think this should work.
def compare(a,b):
a,b = str(a),str(b)
truthvalue = {True:"Y",False:"N"}
return "".join([truthvalue[a[idx]==b[idx]] for idx,digit in enumerate(a)])
print(compare(311,321)) #Returns YNY
print(compare(321312,725322)) #Returns NYNYNY
def two_fourDigits():
results = []
firstn = input("Please enter the first 4 digit number: ")
while firstn.isnumeric() == False and len(firstn) != 4:
firstn= input("Please enter the second 4 digit number: ")
secondn = input("Please enter a 4 digit number: ")
while secondn.isnumeric() == False and len(secondn) != 4:
secondn= input("Please enter a 4 digit number: ")
for i in range(0, len(firstn)):
if firstn[i] == secondn[i]:
results.append("Y")
else:
results.append("N")
print(results)
You don't need to convert the input to a string, the input() function automatically takes in the values as a string.
Second, I added in input validation for firstn and secondn to check that they were numeric, and to check if they are the correct length (4). Also, there is no need to change the input to a list, because you can search through the strings.
I tried to do your function like this. Basically, the function uses the length of the first string to iterate through all the values of each list, and return Y if they are the same and N if they are not.
Because you don't make it a global variable which can be used from out of the function. Here is an example:
my_list = []
def my_func():
global my_list
my_list.append(0)
return "Something..."
my_list.append(1)
print my_list