Breaking a while loop without using break statement - python-3.x

Problem
How can I stop the loop from asking "Input string" again without using break? Thanks.
Code
# Remove Break
def main():
inp = 0
while inp <= 0:
inp = int(input("Enter Number: "))
if inp > 0:
string = ""
while string != "you" or string != "me":
string = input("Input string: ")
if string == "you":
stringYou(inp)
break
elif string == "me":
stringMe(inp)
break
def stringYou(inp):
sentence = "I love You"
print(sentence * inp)
def stringMe(inp):
sentence = "You love Me"
print(sentence * inp)
main()

while string != "you" or string != "me":
The condition here is a tautology meaning it will always be true.
There are three interesting cases for your variable string here:
string is equal to "you". The first condition string != "you" is obviously false. The second however isn’t: string != "me". string is "you" which is not equal to "me". So false or true gives you true.
string is equal to "me". With the same reasoning, except in the opposite order, we get true or false which is also true.
string is something else. Both the subconditions are true, so true or true gives true.
So the condition is always true, and the while condition never stops on its own. So you have to break in order to get out of it.
The fix is to simply fix your conditions so that they make sense and the loop properly ends on its own:
while string != "you" and string != "me":
Note the and: Now, the loop only continues when string is neither "you" nor "me". This is equivalent to your break logic where you stopped the iteration when the string became either of those strings.
So it now looks like this:
string = ''
while string != "you" and string != "me":
string = input("Input string: ")
if string == "you":
stringYou(inp)
elif string == "me":
stringMe(inp)

Related

How can I change upper case to lower and vice versa?

I am playing around with a small script, just for fun. I'm trying to reverse the items in a string and witch the upper case to lower and lower to upper. The reverse part works, but the case part doesn't. What am I doing wrong here?
def reverse(s):
if len(s) == 0:
return s
else:
if s.lower():
s.upper()
else:
s.lower()
return reverse(s[1:]) + s[0]
mytxt = reverse("I wonder how this text looks like Backwards")
print(mytxt)
Here is my current output.
sdrawkcab ekil skool txet siht woh rednow I
str.lower does not return a boolean of whether it's lowercase or not. It returns a string in lowercase. It also doesn't change a string in place.
Since that is the case you need to check the character you are currently interested in.
In this case s[0]. Additionally, strings aren't mutable so you can't change them in place. You'll need a temp variable.
def reverse(s):
if len(s) == 0:
return s
else:
# The character of interest
char = s[0]
# If it's equal to the lowercase version of it
if char == char.lower():
# Change it to upper
char = char.upper()
else:
# and vice versa
char = char.lower()
return reverse(s[1:]) + char
mytxt = reverse("I wonder how this text looks like Backwards")
print(mytxt)
s.lower() and s.upper() do not modify s but instead return another string with all letters converted to lowercase or uppercase, respectively. They don't return booleans, either (which is done by s.islower() and s.isupper()).
If you want to rewrite s, you must construct a new string from the return values.
def reverse(s):
if len(s) == 0:
return s
else:
s0 = s[0]
if s0.islower():
s0 = s0.upper()
elif s0.isupper():
s0 = s0.lower()
return reverse(s[1:]) + s0
mytxt = reverse("I wonder how this text looks like Backwards")
print(mytxt)
Here I checked for both islower and isupper, because both return False in the absence of cased characters (e.g. "0".islower() and "0".isupper() are both false).
str.lower() and str.upper() return a copy of the string converted to lower and upper case. To check whether a string is lower or uppercase, use str.islower() and str.isupper()
Python also has str.swapcase() to do exactly what you want.
Reversing a string can be done simply by using the slice notation, no need for recursion or loops. Your code could be simplified to something like:
def swapcasereverse(s):
return s[::-1].swapcase()
If you want to write your own code for swapcase as an exercise, here's a pythonic way:
def swapcasereverse(s):
newlist = [c.upper() if c.islower() else c.lower() for c in reversed(s)]
return "".join(newlist)
This function uses a list comprehension to
iterate over s in reverse order, with each character going in c
if c is lowercase, adds c.upper() to the list
otherwise, adds c.lower() to the list
Joins the list with "" to make a string, returns the joined string
def reverse(s):
if len(s) == 0:
return s
else:
if s.lower():
s.upper()
else:
s.lower()
return reverse(s[1:]) + s[0]
mytext = reverse("I wonder how this text looks like Backwards").swapcase()
print(mytext)

How can I find a string in sequence (with Booleans)?

I receive a String. For example in here I have :
Mystring= ‘alohrefllluqoo’
I can see all the letter of 'Hello' word, in the correct sequence, in Mystring string
is it possible to use Booleans?
in that string the final output would be 'YES', cause when I remove extra letter I can see the 'Hello' word (in correct sequence) in string.
and if the sequence is not correct and the word can not be found, the output will be 'NO'
This is one approach.
Ex:
Mystring= 'alohrefllluqoo'
to_find = "hello"
def check_string(Mystring, to_find):
c = 0
for i in Mystring:
if i == to_find[c]:
c += 1
if c == len(to_find):
return "YES"
return "NO"
print(check_string(Mystring, to_find))
You can use something like this:
mystring = 'alohreflllouq'
wordtofind = "hello"
i=0
word=''
for char in mystring:
if char == wordtofind[i]:
word = word + char
i+= 1
if word == wordtofind:
break
result = "YES" if word == wordtofind else "NO"
print(result)
making a function, and passing your string, and the thing you search for:
def IsItHere(some_string, sub_string)
try:
some_string.index(sub_string)
return 'YES'
except:
return 'NO'

My if statement always does the not equal, even if the answer is equal

It always turn out to print out "Sorry", even if the number is the same. Why doesn't this if statement work?
import random
high_number = input("What is the maximum number?\nExample(20): ")
print('0-{}'.format(high_number))
guess = input("Guess the number: ")
high_number = int(high_number)
value = random.randint(0, high_number)
if value != guess:
print("Sorry.")
elif value == guess:
print("Hurray!")
Issue: input() returns String and not int
input() returns a string and you are comparing int value to String guess which is always false. Change value!=guess to value!=high_number and it should work.
Use high_number which is the integer value of the String guess.

Reverse loop for palindrome

My teacher wants me to use a reverse loop instead of the reverse function I am using right now. I can't seem to get one that works.
def palindrome():
myInput = input("Enter a Word: ")
word = myInput[::-1]
if myInput == word:
print("That is a palindrome")
return True
else:
print("That is not a palindrome")
return False
palindrome()
def palindrome():
string = input("Enter a Word: ")
for i,char in enumerate(string):
if char != string[-i-1]:
return False
return True
Edited for below comment:
the enumerate() function adds a counter to an iterable.
>>> string = "PARAM"
>>> for count, elem in enumerate(string):
... print count, elem
...
0 P
1 A
2 R
3 A
4 M
so line if char != string[-i-1] will try to match one character from front and one character from end.
You could try the code below, but I really recommend you to try it yourself first. (Because, if you're able to write a recursive call, you should be able to write an iterative one yourself too.)
def reverse(text):
rev = ""
final = ""
for a in range(0,len(text)):
rev = text[len(text)-a-1]
final = final + rev
return final

Need help on python 3x on creating an input string that gives a true or false output

Each single digit from 0-9 is valid.
two or more digits are valid as long as it doesn't start with 0.
x+y
x-y
x/y
x*y
are valid expressions
Nothing else is a valid expression
Probably what you need based on those rules : https://i.stack.imgur.com/zwgaO.png
import re
userInput = input("Enter expression : ")
if re.match(r'^([0-9]|[1-9][0-9]+)([\+\-\*/]([0-9]|[1-9][0-9]+))*$', userInput):
print("Valid expression")
else:
print("Invalid expression")
Here's some explanation of the regex used :
"^([0-9]|[1-9][0-9]+)([\+\-\*/]([0-9]|[1-9][0-9]+))*$"
First part : ([0-9]|[1-9][0-9]+)
You either match a single digit within range 0-9 or 2+ digits with the first digit within range 1-9 (excluding 0)
Second part : ([\+\-\*/]&first_part)*
First of all you search for any of these operators : + - * /, you need to escape +, - and * characters because they are used in the Python regex syntax. No need to escape the / character though.
The * at the end means you expect the second part to be repeated 0 or more times.
What if I don't want to use regexes ?
userInput = input("Expression : ")
allowedDigits, allowedOPs = [str(a) for a in range(10)], ["+", "-", "*", "/"]
pile = ""
valid = True
for c in userInput:
if c in allowedDigits and pile != "" and pile[0] == "0": valid = False
elif c in allowedDigits: pile += c
elif c in allowedOPs and pile == "": valid = False
elif c in allowedOPs: pile = ""
else: valid = False
if pile == "": valid = False
if valid:
print("Valid Expression !")
else:
print("Invalid Expression !")
This code is pretty simple and straightforward, we just detect the 4 possible fail cases :
The number contains more than one digit and begins with 0
if c in allowedDigits and pile != "" and pile[0] == "0"
There's an operator and no number before
elif c in allowedOPs and pile == ""
There's a non-allowed character
else
Expression ends with an operator (doesn't end with a number)
if pile == ""

Resources