I'm trying to create a program that takes input from the user, -1 or 1 to play or quit, number of characters (n), two words for comparison (s1,s2), and calls this function: def strNcompare (s1,s2,n) and then prints the result. The function should return 0,-1,1 if n-character portion of s1 is equal to, less than, or greater than the corresponding n-character of s2, respectively. So for example is the first string is equal to the second string, it should return a 0.
The loop should end when the user enters, -1.
I'm just starting out in Python so the code I have is pretty rough. I know I need an if/else statement to print the results using the return value of the function and a while loop to make the program run.
This is what I have so far, it by no means works but my knowledge ends here. I don't know how to integrate the character (n) piece at all either.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = int(input("number of characters: ")
s1 = s1[:n]
s1 = s2[:n]
if com==-1:
break
def strNcompare(s1,s2,n):
return s1==s2
elif s1==s2:
print(f'{s1} is equal to {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("QUIT")
break
com = input ("String comparison [1(play), -1(quit)]: ")
As of 10/05/2019 - I revised the code and now I am getting a syntax error at "s1 = s1[:n]"
it did not made much sense and especially the variable 'n' is not completely clear to me. I would not code it like that but I tried to be as close to your logic as possible.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = input ("number of characters: ") #what is the purpose of this?
if s1==s2:
print(f'{s1} is equal than {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("Error")
Related
I'm stuck on an exercise where I must obtain a string from a user and then print it in reverse with each letter on its own line. I've done this successfully with a for loop but I was wondering how to do so without it.
user_string = input("Please enter a string: ")
for letter in (user_string)[::-1]:
print(letter)
You can reverse and use str.join to rebuild the string.
print("\n".join(reversed(input("Please enter a string: "))))
If you know how many characters there are in the string or array (calculate using the length method len()) then you could do:
while i < arr_length:
with i incrementing at the end of every round.
The rest of the code would be the same but using i as an index.
One method would be to cast the string to a list and use the list.pop() method until there are no characters left in the list.
user_input = list(input())
while len(user_input) > 0:
print(user_input.pop())
list.pop() will remove the last item in the list and return it.
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using loops) is : ", end="")
print(reverse(s))
Using index property we can easily reverse a given string
a = input()
print(a[::-1])
I want to take input of how many inputs the user is going to give next and collect those inputs in a single line. For eg. if user enters '3' next he has to give 3 inputs like '4' '5' '6' on the same line.
N = int(input())
result = 0
randomlist = []
for number in range(N):
K = int(input())
for number2 in range(K):
a = int(input())
if number2 != K - 1:#Ignore these on below
result += a - 1
else:
result += a
randomlist.append(result)
result = 0
break
for num in range(N):
b = randomlist[num]
print(b)
Now I want the input for K and a (also looped inputs of a) to be on the same line. I have enclosed the whole code for the program here. Please give me a solution on how to get input in the same line with a space in between instead of hitting enter and giving inputs
Based on what I read from your question, you are trying to request input from the user and the desired format of the input is a series of numbers (both integers and floats) separated by spaces.
I see a couple of ways to accomplish this:
Use a single input statement to request the series of numbers including the count,
Just ask the user for a list of numbers separated by spaces and infer the count.
To perform these operations you can do one of the following:
#Request User to provide a count followed by the numbers
def getInputwithCount():
# Return a list Numbers entered by User
while True:
resp = input("Enter a count followed by a series of numbers: ").split(' ')
if len(resp) != int(resp[0]) + 1:
print("Your Input is incorrect, try again")
else:
break
rslt = []
for v in resp[1:]:
try:
rslt.append(int(v))
except:
rslt.append(float(v))
return rslt
or for the simpler solution just ask for the numbers as follows:
def getInput():
# Return the list of numbers entered by the user
resp = input("Enter a series of numbers: ").split(' ')
rslt = []
for v in resp:
try:
rslt.append(int(v))
except:
rslt.append(float(v))
return rslt
Trying to only allow number inputs in python 3.x no letters and ask user to input a number if they enter a letter. I have two numbers that need to be entered and need it to reject singlarily as they are entered.
print ('Hello There, what is your name?') # String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname)# String responds "Nice to meet you" and input the users name that was entered
print() #adds a space
print ('We want to some math today!') # String tells user we want to do some math today
print() # adds a space
num1,num2 = float(input("Enter first number")), float(input("Enter second number"))
sum = num1+num2
if sum >100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') # If inputs are > 100 prints "They add up to a big number"
# and the users name
elif sum <=100 : # Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))
You need a while loop to continuously accept a valid input which in your case is a numerical one.
Another thing is that you need to check if the entered input is numerical or not, in that case you can use Python's inbuilt isdigit() function to do it.
Lastly, type cast your input to float or int while you add the both to avoid str related errors.
print ('Hello there, what is your name?') # String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname) # String responds "Nice to meet you" and input the users name that was entered
print() #adds a space
print ('We want to some math today!') # String tells user we want to do some math today
print() # adds a space
i = False
while i == False:
num1 = input("Enter first number: ")
if num1.isdigit():
i = True
else:
i = False
print() # adds a space
j = False
while j == False:
num2 = input("Enter Second number: ")
if num2.isdigit():
j = True
else:
j = False
sum = float(num1) + float(num2)
if sum > 100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') # If inputs are > 100 prints "They add up to a big number"
# and the users name
elif sum <= 100 : # Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))
Let me know, if that worked for you!
When you are validating multiple inputs, I usually make a separate function to do so. While it may not be necessary here, it is a good habit to factor out repeated code. It will exit if either of the inputs are not floats. Here's how I would do it, using a try block with a ValueError exception. By the way, newlines can be achieved by putting '\n' at the end of the desired strings. Using print() is a sloppy way of doing it.
import sys
def checkNum(number):
try:
number = float(number)
except ValueError:
print("That is not a float.")
sys.exit()
return number
Then, you can use the original code like so:
print ('Hello There, what is your name?') #String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname + '\n')#String responds "Nice to meet you" and input the users name that was entered
print ('We want to some math today!\n') #String tells user we want to do some math today
num1 = checkNum(input("Enter first number"))
num2 = checkNum(input("Enter second number"))
sum = num1+num2
if sum >100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') #If inputs are > 100 prints "They add up to a big number" and the users name
elif sum <=100 : #Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))
New to programming. How to count and print iterations(attempts) I had on guessing the random number?` Let's say, I guessed the number from 3-rd attempt.
import random
from time import sleep
str = ("Guess the number between 1 to 100")
print(str.center(80))
sleep(2)
number = random.randint(0, 100)
user_input = []
while user_input != number:
while True:
try:
user_input = int(input("\nEnter a number: "))
if user_input > 100:
print("You exceeded the input parameter, but anyways,")
elif user_input < 0:
print("You exceeded the input parameter, but anyways,")
break
except ValueError:
print("Not valid")
if number > user_input:
print("The number is greater that that you entered ")
elif number < user_input:
print("The number is smaller than that you entered ")
else:
print("Congratulation. You made it!")
There are two questions being asked. First, how do you count the number of iterations? A simple way to do that is by creating a counter variable that increments (increases by 1) every time the while loop runs. Second, how do you print that number? Python has a number of ways to construct strings. One easy way is to simply add two strings together (i.e. concatenate them).
Here's an example:
counter = 0
while your_condition_here:
counter += 1 # Same as counter = counter + 1
### Your code here ###
print('Number of iterations: ' + str(counter))
The value printed will be the number of times the while loop ran. However, you will have to explicitly convert anything that isn't already a string into a string for the concatenation to work.
You can also use formatted strings to construct your print message, which frees you from having to do the conversion to string explicitly, and may help with readability as well. Here is an example:
print('The while loop ran {} times'.format(counter))
Calling the format function on a string allows you replace each instance of {} within the string with an argument.
Edit: Changed to reassignment operator
I am trying to write a program that asks the user for two strings and creates a new string by merging the two together (take one letter from each string at a time). I am not allowed to use slicing. If the user enters abcdef and xyzw, program should build the string: axbyczdwef
s1 = input("Enter a string: ")
s2 = input("Enter a string: ")
i = 0
print("The new string is: ",end='')
while i < len(s1):
print(s1[i] + s2[i],end='')
i += 1
The problem I am having is if one of the strings is longer than the other I get an index error.
You need to do your while i < min(len(s1), len(s2)), and then make sure to print out the remaining part of the string.
OR
while i < MAX(len(s1), len(s2)) and then only print s1[i] if len(s1) > i and only print s2[i] if len(s2) > i in your loop.
I think zip_longest in Python 3's itertools gives you the most elegant answer here:
import itertools
s1 = input("Enter a string: ")
s2 = input("Enter a string: ")
print("The new string is: {}".format(
''.join(i+j for i,j in itertools.zip_longest(s1, s2, fillvalue=''))))
Here's the docs, with what zip_longest is doing behind the scenes.