I want to create a list, then enter an int, which will then add the int amount of strings to a list,then print it. So far so good:
list = []
number = int(raw_input("Enter a number: "))
while number > 0:
list.append(str(raw_input("Enter a word: ")))
number = number - 1
print list
However, how do I make it a little more advanced so that you cannot add the same string twice to the list?
You can keep a set of all the strings seen, only adding a string and if it has not been seen before, you don't need to keep a count variable either, you can loop until len(data) != number:
number = int(raw_input("Enter a number: "))
seen = set()
data = []
while len(data) != number:
inp = raw_input("Enter a word: ")
if inp not in seen:
data.append(inp)
seen.add(inp)
If the order was irrelevant you could just use a set altogether as sets cannot have dupes:
number = int(input("Enter a number: "))
data = set()
while len(data) != number:
inp = raw_input("Enter a word: ")
data.add(inp)
Check for whether the list already contain the entered string or not before appending. And don't use in-built keywords as variable names.
list_ = []
number = int(raw_input("Enter a number: "))
while number > 0:
x = raw_input("Enter a word: ")
if not x in list_:
list_.append(x)
number = number - 1
else:
print "Word is already available"
print list_
you can do something like this
mylist = []
number = int(raw_input("Enter a number: "))
while number > 0:
mystring = str(raw_input("Enter a word: "))
if mystring not in mylist:
mylist.append(mystring)
number = number - 1
else:
print('Choose different string')
next
print mylist
and try to avoid build-in function as variable name. Built-in functions are
https://docs.python.org/2/library/functions.html
Related
How can we check if a user enters the value 0 multiple times in a row?
I have tried below code- here I have tried to define multiple value in list, but if the user enters 000000000 or more, I have to define till 000000000 in list is there any other way to achieve this
list = [0,00,000,0000]
num = int(input("Enter a number: "))
if num in list:
print("Zero")
elif :
print(" None ")
You need to take the input as a string. And you can check if the user has entered a string that will have all zeros in it as follows
def all_zeros(string):
return all(ch == '0' for ch in string)
This worked for me
num = input("Enter: ")
if num.count('0') > 0 and num.startswith('0'):
print("0")
else:
print("none")
Since you asked in this way
How can we check if a user enters the value 0 multiple times in a row?
But, other answers were checking whether more than one 0's are present in the string or not. I assume you want to check continuous zero's only,
num = input("Enter Number: ") # returns string
if "00" in num: #checking substring
print("Found continuous zeros")
else:
print("Entered no continous zeros!")
value = int(num) # convert it to int if needed
It doesn't matter how many zeros in the string, all these [00,000,0000,00000...] belong to the same category.
Output:
>>> num = input("Enter Number: ")
Enter Number: 0008
>>> num
'0008'
>>> "00" in num
True
>>>
num = input("Enter: ")
if num.count("0") > 1 and int(num) == 0:
print("0")
else:
print("none")
don't change num to int it will remove all the trailing zeroes
Im new to programming and was set a task where I had to ask the user for there name and a number. I had to print the name where each individual letter is printed on a separate line. The second part is that I had to ask the user to enter a number and that it would repeat the same output by the number given by the user
My code:
name = input("Please enter your name:")
num = input("Please enter a number:")
for index,letter in enumerate(name,1):
for num in range(0,9):
print(letter)
My desired result was this:
Please enter your name: Taki
Please enter a number: 3
T
a
k
i
T
a
k
i
T
a
k
i
the result was this:
Please enter your name: Taki
Please enter a number:3
T
T
T
T
T
T
T
T
T
a
a
a
a
a
a
a
a
a
k
k
k
k
k
k
k
k
k
i
i
i
i
i
i
i
i
i
Plz help
A brute force approach is
name = input('Enter a name: ')
num = int(input('Enter a number: '))
for i in range(num):
for j in name:
print(j)
Here, name is a string which is iterated over each character in the j-loop.
In your code, the num loop from 0 to 9 is wrong. You need to print for num times, not 9 times (0-9). So the range has to be i in range(num). This is why each character was being printed 9 times in your output.
Also, remember to type cast num variable to int while taking the input as Python treats all inputs as string by default.
You have your loops in the wrong order. And your range should be to num not 9
name = input("Please enter your name:")
num = input("Please enter a number:")
for i in range(num):
for letter in name:
print(letter)
name = input("Please enter your name:")
num = input("Please enter a number:")
result = [char for char in name] * int(num)
print('\n'.join(result))
Another way to get it done, using itertools:
import itertools
count = 0
name = input("Please enter your name:")
num = int(input("Please enter a number:"))
for i in itertools.cycle(name):
if count > num * len(name)-1:
break
else:
print(i, end = "\n")
count += 1
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
Fellow python developers. I have a task which I can't seem to crack and my tutor is MIA. I need to write a program which only makes use of while loops, if, elif and else statements to:
Constantly ask the user to enter any random positive integer using int(raw_input())
Once the user enters -1 the program needs to end
the program must then calculate the average of the numbers the user has entered (excluding the -1) and print it out.
this what I have so far:
num = -1
counter = 1
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
counter += anyNumber
answer = counter + anyNumber
print answer
print "Good bye!"
Try the following and ask any question you might have
counter = 0
total = 0
number = int(raw_input("Enter any number: "))
while number != -1:
counter += 1
total += number
number = int(raw_input("Enter another number: "))
if counter == 0:
counter = 1 # Prevent division by zero
print total / counter
You need to add calculating average at the end of your code.
To do that, have a count for how many times the while loop runs, and divide the answer at the end by that value.
Also, your code is adding one to the answer each time because of the line - answer = counter + anyNumber, which will not result in the correct average. And you are missing storing the first input number, because the code continuously takes two inputs. Here is a fixed version:
num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
counter += 1
answer += anyNumber
anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1
else:
print answer/counter #print average
print "Good bye!"
There's another issue I think:
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
The value of the variable anyNumber is updated before the loop and at the beginning of the loop, which means that the first value you're going to enter is never going to be taken in consideration in the average.
A different solution, using a bit more functions, but more secure.
import numpy as np
numbers = []
while True:
# try and except to avoid errors when the input is not an integer.
# Replace int by float if you want to take into account float numbers
try:
user_input = int(input("Enter any number: "))
# Condition to get out of the while loop
if user_input == -1:
break
numbers.append(user_input)
print (np.mean(numbers))
except:
print ("Enter a number.")
You don't need to save total because if the number really big you can have an overflow. Working only with avg should be enough:
STOP_NUMBER = -1
new_number = int(raw_input("Enter any number: "))
count = 1
avg = 0
while new_number != STOP_NUMBER:
avg *= (count-1)/count
avg += new_number/count
new_number = int(raw_input("Enter any number: "))
count += 1
I would suggest following.
counter = input_sum = input_value = 0
while input_value != -1:
counter += 1
input_sum += input_value
input_value = int(raw_input("Enter any number: "))
try:
print(input_sum/counter)
except ZeroDivisionError:
print(0)
You can avoid using two raw_input and use everything inside the while loop.
There is another way of doing..
nums = []
while True:
num = int(raw_input("Enter a positive number or to quit enter -1: "))
if num == -1:
if len(nums) > 0:
print "Avg of {} is {}".format(nums,sum(nums)/len(nums))
break
elif num < -1:
continue
else:
nums.append(num)
Here's my own take on what you're trying to do, although the solution provided by #nj2237 is also perfectly fine.
# Initialization
sum = 0
counter = 0
stop = False
# Process loop
while (not stop):
inputValue = int(raw_input("Enter a number: "))
if (inputValue == -1):
stop = True
else:
sum += inputValue
counter += 1 # counter++ doesn't work in python
# Output calculation and display
if (counter != 0):
mean = sum / counter
print("Mean value is " + str(mean))
print("kthxbye")
Wondering if someone can help me on this. I know I can append data to a 1D list by using .append. What I am having trouble figuring out is how to append data to a 2D list and have Python place the data in the right list in the right spot.
I need to create a program that runs x times (with each name having 2 pairs of values), and after each time append the user input to a list. So at the end, I need something like this:
[[Name] [1,2] [3,4]]
[[Name] [4,5] [6,7]]
etc….
How do I tell Python which List and position to place the Names and values in ?
This is what I have so far for code.
def main():
how_many = int(raw_input("How many to enter? "))
counter = 0
list = [ [], [] ]
while counter < how_many:
name = raw_input("Enter the Name ")
first_val = int(raw_input("Enter first_val "))
first_val2 = int(raw_input("Enter first_val2 "))
sec_val = int(raw_input("Enter sec_val "))
sec_val2 = int(raw_input("Enter sec_val2 "))
counter = counter + 1
main()
OK - so I modified the code and added in a line to append the data, after the line with the counter + 1.
list.append([[name],[first_val,first_val2], [sec_val,sec_val2]])
What I would now like to do is print the list out (via rows and columns), but am getting a IndexError. This occurs when I try to enter/print out more than 4 values. The error appears to be in the last line. Is there a way I can modify the code to stop this and print out as many values as have been requested by the user ?
for r in range(how_many):
for c in range (how_many):
print list [r][c]
And yes, I will look into using tuples as well at some point.
def main():
how_many = int(raw_input("How many to enter? "))
counter = 0
list = []
while counter < how_many:
name = raw_input("Enter the Name ")
first_val = int(raw_input("Enter first_val "))
first_val2 = int(raw_input("Enter first_val2 "))
sec_val = int(raw_input("Enter sec_val "))
sec_val2 = int(raw_input("Enter sec_val2 "))
list.append([[name], [first_val, first_val2], [sec_val, sec_val2]])
counter = counter + 1
Assume we are reading the values from stdin (as in the question body)
you can use lists:
list = []
....
list.append([[name], [first_val, first_val2], [sec_val, sec_val2]])
but a tuple seems to be a better fit here:
t = (name, (first_val, first_val2), (sec_val, sec_val2))
list.append(t)
Since the values are not likely to change, a tuple feels like the better choice.
Think about how a field would be accessed in each case:
list:
name = list[i][0][0]
tuple:
name = list[i][0]
Again...it just seem more natural...