This is Python. I'm trying to write a program that asks the user for a string input without using global variables. If the string has parentheses only side by side, then it's even. if it has letters, numbers, or the parentheses are spaced out, then it's uneven. For example, () and ()() and (()()) is even, whereas (() and (pie) and ( ) is not. Below is what I've written so far. My program keeps on printing 'Enter your string' infinitely, I'm stuck with that problem right now.
selection = 0
def recursion():
#The line below keeps on repeating infinitely.
myString = str(input("Enter your string: "))
if not myString.replace('()', ''):
print("The string is even.")
else:
print("The string is not even.")
while selection != 3:
selection = int(input("Select an option: "))
#Ignore this.
if selection == 1:
print("Hi")
#This won't work.
elif selection == 2:
def recursion():
recursion()
This outputs the correct even/not even answers.
selection = 0
def recursion():
myString = str(raw_input("Enter your string: ")) #Use raw_input or ( ) will be ()
paren = 0
for char in myString:
if char == "(":
paren += 1
elif char == ")":
paren -= 1
else:
print "Not Even"
return
if paren < 0:
print "Not even"
return
if paren != 0:
print "Not even"
return
print "Even"
return
while selection != 3:
selection = int(input("Select an option: "))
#Ignore this.
if selection == 1:
print("Hi")
#This won't work.
elif selection == 2:
recursion() #This isn't a recursive function - naming it as so is...
Unless you're using Python 3, you should use raw_input instead of input, because input gives back the result in whatever type matches the input best, whereas raw_input always returns a string. In Python 3, input always returns a string. Also, why are you redefining recursion? Just call it from the elif statement. Example:
selection = 0
def recursion():
#The line below keeps on repeating infinitely.
myString = raw_input("Enter your string: ") # No need to convert to string.
if not myString.replace('()', ''):
print("The string is even.")
else:
print("The string is not even.")
while selection != 3:
selection = int(raw_input("Select an option: "))
#Ignore this.
if selection == 1:
print("Hi")
#This won't work.
elif selection == 2:
recursion() # Just call it, as your program already
# recurs because of the if statement.
Related
Is there any simple method to return to menu by entering a special key? If the user made a mistake while entering the input, user can return to main menu by pressing # (a special key) key at the end of the input.
x = input("Enter first number: ")
Here, user enter 5, but want to exit by input #. So, x = 5#
I tried some including this
x=input("Enter first number: ")
print(int(a))
if x == "#":
exit()
Also tries this too
for x in ['0', '0$']:
if '0$' in x:
break
But, unable to handle numbers and string values together.
while True:
x = input()
if x[-1] == '#':
continue
# other stuff
this should work
Try
user_input = input("Enter your favirote deal:")
last_ch = user_input[-1]
if(last_ch == "#"):
continue
else:
//Your Logic
int(x) will not work if it contains characters other than numbers.
use this construction (# will be ignored by converting a string to int)
x=input("Enter first number: ")
print(int(x if "#" not in x else x[:-1])) # minus last if has #
if "#" in x:
exit() # or break or return, depends what you want
I'm new to python and I'm trying to help out a friend with her code. The code receives input from a user until the input is 0, using a while loop. I'm not used to the python syntax, so I'm a little confused as to how to receive user input. I don't know what I'm doing wrong. Here's my code:
sum = 0
number = input()
while number != 0:
number = input()
sum += number
if number == 0:
break
In your example, both while number != 0: and if number == 0: break are controlling when to exit the loop. To avoid repeating yourself, you can just replace the first condition with while True and only keep the break.
Also, you're adding, so it is a good idea to turn the read input (which is a character string) into a number with something like int(input()).
Finally, using a variable name like sum is a bad idea, since this 'shadows' the built-in name sum.
Taking all that together, here's an alternative:
total = 0
while True:
number = int(input())
total += number
if number == 0:
break
print(total)
No need last if, and also make inputs int typed:
sum = 0
number = int(input())
while number != 0:
number = int(input())
sum += number
You can actually do:
number=1
while number!=0:
number = int(input())
# Declare list for all inputs
input_list = []
# start the loop
while True:
# prompt user input
user_input = int(input("Input an element: "))
# print user input
print("Your current input is: ", user_input)
# if user input not equal to 0
if user_input != 0:
# append user input into the list
input_list.append(user_input)
# else stop the loop
else:
break
# sum up all the inputs in the list and print the result out
input_sum = sum(input_list)
print ("The sum is: ", input_sum)
Or
If you don't want to use list.
input_list = 0
while True:
user_input = int(input("Input an element: "))
print("Your current input is: ", user_input)
if user_input != 0:
input_list += user_input
else:
break
print ("The sum is: ", input_list)
Note:
raw_input('Text here') # Python 2.x
input('Text here') # Python 3.x
I'm building my first calculator. Trying to implement While loop to get a number through user input. I want the While to break once user put a number.
num1 = raw_input("Add mumber one: " )
try:
input = int(num1)
except ValueError:
print "This is not a number"
attempt = 0
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
print "You are not putting number. So, goodbuy"
operation = raw_input("Add Operator: ")
Try this:
for _ in range(5):
num1 = unicode(raw_input("Add number one: "))
if num1.isnumeric():
break
Another method you can try is to have num1 and do the following in the while loop:
if type(num1) is int:
break
What this does is check the type of the variable num1. If it is an integer, int, then it breaks out of the while loop.
I want the While to break once user put a number.
You already are doing that in the condition for your while loop by having type(num) != int so your while loop should stop after the user enters an integer.
You have several errors here:
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
The break statement shoud be inside the loop, but the indentation is wrong. As you write, it is after the loop (hence useless). Also, when you read from standard input, you always get a string even if it is a number. So when you check type(num1) != int this is always false. You must convert num1 with int() each time you read from standard input, not only the first time:
while True:
num1 = raw_input("Add Number one again: " )
try:
input = int(num1)
break
except ValueError:
print "This is not a number"
if attempt == 5:
break
attempt += 1
Here I try to convert to an integer the string read from stdin. If it works, I break the loop immediately. If it does not work (the except clause) I check how many attempts have been done, and break the loop if the attempts are equal to 5.
Hi everyone I’m writing because I’m stuck with an exercise in which I should only use for loops and if/else statements. I found a way but practically I’m iterating the same block of code four times and I’m really looking for a way to automate it.
I know that probably this is not the best way to solve the exercise but now I’m not looking for the most efficient way (I already found on the solutions of the exercise), I’m asking you how can I use for to iterate the block of code
The exercise tells me to create a program that takes an IP address from the keyboard and validates that it can be interpreted as a valid IP address.
An IP address consists of 4 numbers, separated from each other with a full stop. Each number can have no more than 3 digits. (Examples: 127.0.0.1)
Important
This challenge is intended to practise for loops, and if/else statements, so although it would probably be written for real using regular expressions we don't want you to use them here even if you know what they are.
This is what I made:
# ipAddress = input("please enter an ipAddress: ")
ipAddress = "192.168.7.7" #test ip address
# check if number of dots is 3
numberOfDot = 0
for char in ipAddress:
if char == '.':
numberOfDot += 1
totNumbOfDot = numberOfDot # output of this section is totNumberOfDot, to be checked at the end
if totNumbOfDot != 3:
print("You inserted a wrong ip address")
# first number check # THIS IS THE BLOCK OF CODE I WANT TO
number1 = '' # ITERATE WITH FOR IF POSSIBLE
for char in ipAddress:
if char in "0123456789":
number1 += char
if char == '.':
break
if 1 <= len(number1) <= 3:
print("First number: OK")
else:
print("First number: Fail")
digitN1 = len(number1) + 1
print(number1)
# second number check
numberMinus2 = ipAddress[digitN1:]
number2 = ''
for char in numberMinus2:
if char in "0123456789":
number2 += char
if char == '.':
break
if 1 <= len(number2) <= 3:
print("Second number: OK")
else:
print("Second number: Fail")
digitN2 = len(number2) + digitN1 +1
print(number2)
# third number check
numberMinus3 = ipAddress[digitN2:]
number3 = ''
for char in numberMinus3:
if char in "0123456789":
number3 += char
if char == '.':
break
if 1 <= len(number3) <= 3:
print("Third number: OK")
else:
print("Third number: Fail")
digitN3 = len(number3) + digitN2 + 1
print(number3)
# fourth number check
numberMinus4 = ipAddress[digitN3:]
number4 = ''
for char in numberMinus4:
if char in "0123456789":
number4 += char
if char == '.':
break
if 0 < len(number4) <= 3:
print("Fourth number: OK")
else:
print("Fourth number: Fail")
digitN4 = len(number4) + digitN3 + 1
print(number4)
I would also say, split() is the way to go. Your question was if there was a way to use your logic and still not have to repeat code 4 times. To achieve that you could do something like this:
numberOfDot=0
number=""
for char in ip+'.':
if char=='.':
numberOfDot+=1
if len(number) in [1,2,3]:
print("number %d OK"%numberOfDot)
else:
print("number %d not OK"%numberOfDot)
print(number)
number=""
elif char in '1234567890':
number+=char
else:
print("character not valid")
if numberOfDot!=4:
print("you inserted a wrong ip")
As i said, i would also recommend using split() - this is just to try and provide an answer closer to your question. Also please note that this code (same as yours) will mark ip adresses containing letters, not only numbers, as OK.
Well, you have to ask yourself the right question: "can I do better?". Please always do that. Yes, in fact, you can. The code that deals with numbers validation between dots is essentially the same. So you should split the string on dots and use for loop to validate each group:
for str in ipAddress.split("."):
your validation here
how about that? split the string at the dots . and check if between the dots there are numbers in the valid range (that would also accept '255.255.255.255')
def valid(ipaddress):
# we need 3 dots; otherwise this is no ipaddress.
if not ipaddress.count('.') == 3:
return False
# check what is before, between and after the dots
for byte in ipaddress.split('.'):
# if byte can not be interpreted as an integer -> no good!
try:
i = int(byte)
except ValueError:
return False
# now check if byte is in the valid range
if i < 0:
return False
if i > 255:
return False
return True
print(valid(ipaddress='192.168.7.7')) # -> True
print(valid(ipaddress='.168.7.7')) # -> False
print(valid(ipaddress='721.168.7.7')) # -> False
I know all my questions are really easy but I'm a beginner so here it is...
I have been developing the guessing number thing after everyones help, but I want to then return to a menu which has just been left. Here's the code:
import time
import random
animalmenu()
def animalmenu():
print()
print()
print()
print()
print('Welcome to the menu. I am thinking of a menu. Select the option\'s below to try and guess my animal.')
print()
print('a) No. of Legs')
print('b) Type of animal')
print('c) Preffered Climate')
print('d) Size')
print('e) Colour')
print('f) Diet')
print('g) Habitat')
print('h) Can be kept as pet')
print('i) Guess animal')
print()
print('When in a menu, type in \'555\' to return here')
AniChoice = input('Choose your option: ')
if AniChoice == 'a':
loop = 10
while loop == 10:
print()
print('')
print()
guessleg = int(input('Guess the number of legs: '))
if leg == guessleg:
print('True')
elif leg != guessleg:
print('False')
print('r = Return to menu, g = guess again.')
rg = input()
if rg == 'g':
print('Loading...')
elif rg == 'r':
loop = 0
time.sleep(1)
print('Returning to menu...')
time.sleep(1)
animalmenu()
everytime I run it, I type in a number as the code asks but then, instead of asking if I want to return to the menu it just asks the question again and again, 'Guess the number of legs: '. I know this is something to do with my looping method but I do not understand and because of the integer setting I cannot just make another if, like so:
guessleg = int(input('Guess the number of legs: '))
if leg == guessleg:
print('True')
elif leg != guessleg:
print('False')
elif guessleg == 'back':
loop = 0
animalmenu()
And I do not see any other way of doing it as neither way seems to work? How would you suggest returning to animalmenu()?
As the message is telling you, 'back' is not an integer, but you are comparing it to a variable into which you have put an integer value. Specifically, your line:
guessleg = int(input('Guess the number of legs: '))
puts an integer value into guessleg (or more properly tries to) from the user's input.
One approach to resolve this is to capture the user's input in a string variable, compare that string to 'back' first, and then convert to an integer if needed.
Another approach is to wrap a try/except around the integer conversion and proceed with the integer check if the conversion is successful and with the check against 'back' if the exception is encountered. This is probably preferred these days and I've put it into code:
inp_val = raw_input('Guess the number of legs: ')
try:
guess_num = int(inp_val)
if guess_num == leg:
print('True')
else:
print('False')
except ValueError:
if inp_val == 'back':
loop = 0
else:
print 'Invalid entry'
animalmenu()
because the you convert your input into integer and store it into guessleg which means guessleg is also an integer. However, 'back' is a string. You can't compare the string with integer. the 3 == 'back'means nothing.
and syntax error may because of your indent.
UPDATE:
if you want to return to the top menu, you can do something like:
def animalmenu():
while True:
print your menu here
and do something....
while ...:
get input and do something...
if get the input of 'back to menu':
break
UPDATE again:
I don't think you shall use input() here, try readline() or raw_input() instead.