I'm relatively new to python and in my code I am attempting to get variables to create a drawing, although when I reset the variable c to false again it shows up red for some reason. For some reason putting a space in front of it changes it back but otherwise I am not too sure how to solve this as nothing seems inherently wrong.
from turtle import *
speed(100)
c = False
while c == False:
n = int(input("How many sides? "))
if n > 3 and n < 10 :
c == True
print("Correct integer input detected for number of sides")
print()
else:
print("Only enter integers between 3 and 10")
print()
#It's this one that shows up as incorrect
c = False
while c == False:
l =int(input("Enter side length between 20 & 80: "))
if l > 20 and l < 80 :
c == True
print("Correct integer input detected for side length")
print()
else:
print("Only enter integers between 20 and 80")
print()
image of issue on my screen
Your Code
from turtle import *
speed(100)
c = False
while c == False:
n = int(input("How many sides? "))
if n > 3 and n < 10 :
c == True
print("Correct integer input detected for number of sides")
print()
else:
print("Only enter integers between 3 and 10")
print()
#It's this one that shows up as incorrect
c = False
while c == False:
l =int(input("Enter side length between 20 & 80: "))
if l > 20 and l < 80 :
c == True
print("Correct integer input detected for side length")
print()
else:
print("Only enter integers between 20 and 80")
print()
Just Change
c == True
to
c = True
Because
c == True
returns True if c is equal to True
and
c = True
set's the variable to True
If you have any queries Please Ask
c == True
This is comparing if "c" is equal to True. It is not assigning True to "c". To do that you need
c = True
Related
I'm starting to practice Python programming so please excuse if it's some very basic concept for you.
I'm trying to print result based on number comparison.
User Input: Any number between 1 to 100
Outputs: Based on comparisons, the output should be printed accordingly. Please look at the code below:
x = int(input("Enter a number: ").strip())
if 0<x<101:
if (x%2 == 1):
print("Weird")
elif (x%2 == 0 & 1<x<6):
print("Not Weird - between 2 to 5; inclusive")
elif (x%2 == 0 & 5<x<21):
print("Weird - between 5 to 20; inclusive")
elif (x%2 == 0 & x>=20):
print("Not Weird - Greater than 20")
else:
print("Please enter a number between 1 & 100, limits inclusive. Exiting program...")
It does the job for first 3 if comparisons. But if I input any even number above 20, it prints the final else loop statement.
I modified the last if to 20<x<100, then it runs properly.
For some reason, I can't get the x>20 condition work. Any ideas what I'm doing wrong?
Quick Answer: Use and instead of &. and is for boolean operators and & is used for bitwise operations (can be good for arrays which this is not).
Another note, you have 5<x<20 which is not actually inclusive of 5 and 20 (use 5<=x<=20 or 4<x<21) and x>=20 is not just greater than 20 it is also equal (use x>20). However if you actually want to restrict it to less than or equal to 100 obviously use 20<x<101.
As suggested by outflanker in the comments above, pasting the corrected code.
x = int(input("Enter a number: ").strip())
if 0<x<101:
if (x%2 == 1):
print("Weird")
elif (x%2 == 0 and 1<x<6):
print("Not Weird - between 2 to 5; inclusive")
elif (x%2 == 0 and 5<x<21):
print("Weird - between 5 to 20; inclusive")
elif (x%2 == 0 and x>=20):
print("Not Weird - Greater than 20")
else:
print("Please enter a number between 1 & 100, limits inclusive. Exiting program...")
I am having an issue with Python validation. I was wondering if there was a simple way to put validation on two input numbers to check a few things:
If the inputs are ints
if neither of the inputs equals a certain number, they are not valid. (For example, this would mean one of them would have to be 5. So a = 1 b = 4, a = 3 b = 2, a = 1 b = 1 wouldn't work)
If the two numbers are the same number that is required it will not work (E.G. if a = 5 b = 5 will not work as 5 is the required number, however a = 1 b = 5 would work as 5 is only being inputted once).
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
val = int(a)
val1 = int(a)
if val1 != 5 or val != 5:
print("I'm sorry but it must be a pos int and equal 5")
continue
break
except ValueError:
print("That's not an int")
This is what I was trying to do, but I think I may be dreadfully wrong?
Any help appreciated!
Thanks.
Logical xor
You should continue the loop if exactly one a and b is equal to 5. It means you need a logical xor. Parens are needed to avoid comparing a to 5 ^ b:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
if (a != 5) ^ (b != 5):
print("I'm sorry but it must be a pos int and equal 5")
continue
break
except ValueError:
print("That's not an int")
It might not be very readable though.
Count 5's
You could count the number of ints equal to 5:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
count5 = [a, b].count(5)
if count5 == 1:
break
else:
print("Exactly one input should be equal to 5.")
except ValueError:
print("That's not an int")
If you want to differentiate between errors:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
count5 = [a, b].count(5)
if count5 == 2:
print("Inputs cannot both be equal to 5.")
elif count5 == 0:
print("At least one input should be equal to 5.")
else:
break
except ValueError:
print("That's not an int")
Here's an example:
Enter first input: 3
Enter second input: 1
At least one input should be equal to 5.
Enter first input: 5
Enter second input: 5
Inputs cannot both be equal to 5.
Enter first input: 3
Enter second input: 5
Logic... if True then break, False then print error message...
Two things... you want logical exclusive or so that True ^ True = False
You aren't storing b. The text you're printing doesn't explain what's happening.
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a) # like the readable code using a not val1...
b = int(b)
if (a != 5) ^ (b != 5): # added parens as suggested
break
else:
print("I'm sorry but it must be a pos int and equal 5")
continue
except ValueError:
print("That's not an int")
Output
Enter first input: 5
Enter second input: 5
I'm sorry but it must be a pos int and equal 5
Enter first input: 1
Enter second input: 5
runfile('...')
Enter first input: 5
Enter second input: 5
I'm sorry but it must be a pos int and equal 5
You could use:
(a == 5 and b != 5) or (a != 5 and b == 5)
Or this:
(a == 5) != (b == 5)
(!= is the boolean equivalent of bitwise xor)
I'm sorry in advance for the noobishness. I'm very new to this whole thing. Like, has-been-only-doing-this-for-four-days new.
clears throat Anyway, I am dealing with the assignment "Exercise: vara varb" in the course "6.00.1x Introduction to Computer Science and Programming Using Python" by MITx. It is causing me quite a bit of trouble.
Assume that two variables, varA and varB, are assigned values, either numbers or strings.
Write a piece of Python code that evaluates varA and varB, and then prints out one of the following messages:
"string involved" if either varA or varB are strings
"bigger" if varA is larger than varB
"equal" if varA is equal to varB
"smaller" if varA is smaller than varB
Here's a solution :
varA = input("A : ")
varB = input("B : ")
try: # to avoid errors when converting strings that have non-digits to numbers
varA = float(varA)
varB = float(varB)
if varA > varB:
print("bigger")
elif varA < varB:
print("smaller")
else:
print("equal")
except ValueError: # that means that python couldn't convert one of the variables to a number, which means it's a string
print("string involved")
Replace A and B with values.
A = Value
B = Value
try:
if A < B:
print('smaller')
elif A > B:
print('bigger')
elif A == B:
print('equal')
except(TypeError,ValueError):
print('string involved')
If you want to assign random values, you could use:
import random
import string
def find_value():
num = random.randrange(1,3)
if num == 1:
characters = list(string.ascii_lowercase)
x = ''
for num3 in range(6): # six letters
num2 = random.randrange(0,26)
x = x + characters[num2]
return x
elif num == 2:
x = random.randrange(0,101) #between 0 through 101, never 0 and 101
return x
A = find_value()
B = find_value()
try:
if A < B:
print('smaller')
elif A > B:
print('bigger')
elif A == B:
print('equal')
except(TypeError,ValueError):
print('string involved')
You could also have it repeat infinitely.
import random
import string
import time
def find_value():
num = random.randrange(1,3)
if num == 1:
characters = list(string.ascii_lowercase)
x = ''
for num3 in range(6): # six letters
num2 = random.randrange(0,26)
x = x + characters[num2]
return x
elif num == 2:
x = random.randrange(0,101) #between 0 through 101, never 0 and 101
return x
while True:
time.sleep(1)
A = find_value()
B = find_value()
try:
if A < B:
print('smaller')
elif A > B:
print('bigger')
elif A == B:
print('equal')
except(TypeError,ValueError):
print('string involved')
input_list = input("Enter numbers separated by spaces: ")
number = input_list.split()
for n in number:
a = int(n)
if len(number)!=5 or number>5 or number<0 :
print ('invalid input')
if 0< a <=5:
print ('x'* a)
elif a == 0:
print ('.')
My program is checking the 5 digits which are inputted as if they are one number but I want my program to first make sure that 5 digits are inputed and then check if they are between 0 and 5 but the program combines all 5 digits into one number, I want the program to check each element of the list on it's own and before printing anything I want the program to check if the inputted number meets all the conditions and if does not to print (Invalid Input) and stop their
input_list = input("Enter numbers separated by spaces: ")
numbers = input_list.split()
if len(numbers) == 5 and all(0 <= int(n) <= 5 for n in numbers):
print("ok")
print("".join(numbers))
else:
print("invalid")
I use raw_input in python 2. input is fine for python 3.
input_list = raw_input("Enter numbers separated by spaces: ").split()
numbers = [int(n) for n in input_list if 0 <= int(n) <= 5]
if len(numbers) != 5:
print ('invalid input')
for a in numbers:
if a == 0:
print ('.')
else:
print ('x'* a)
input_list = input("Enter numbers separated by spaces: ")
number = input_list.split()
if len(number) == 5:
for n in number:
a = int(n)
if 0< a <=5:
print ('x'* a)
elif a == 0:
print ('.')
else:
print ("Number does not lie in the range 0 to 5.")
else:
print ("Invalid Input.")
Yes, the above works but is should check input first to make sure it is valid
number = raw_input("Enter numbers separated by spaces: ")
2 num_list = number.split()
3 for n in num_list:
4 a = 'True'
5 if int(n) <0 or int(n) >5:
6 a = 'False'
7 break
8 if (len(num_list) == 5) and a == 'True':
9 for n in num_list:
10 b = int(n)
11 if 0< b <=5:
12 print ('x'* b)
13 elif b == 0:
14 print ('.')
15 else:
16 print 'Invalid Input!'
input_list = raw_input("Enter numbers separated by spaces: ")
number = input_list.split()
if len(number) == 5:
for n in number:
a = int(n)
if 0< a <=5:
print 'x'* a
elif a == 0:
print '.'
else:
print "Number does not lie in the range 0 to 5."
else:
print "Invalid Input."
I want my program to check if the 5 inputted numbers meets all the conditions and if even one them fails to print INVALID INPUT and stop the program. Also I don't quite understand how my program checks each inputted number on its own as my teacher helped me but didn't explain it .
The program should ask for the number five times before printing anything
The program must check that the input are numbers are between 0 and 5. It will also fail if a number of digits is entered other than 5. Failed input can terminate the program with an appropriate error message.
Inputted numbers may be duplicates. (ex. 3, 3, 3, 0, 0 is acceptable input.)
This is what Python's assert statement does:
>>> x = 5
>>> try:
... assert(x==4)
... except(AssertionError):
... print("Error!")
...
>>> Error!
In the assert clause, you are stating a boolean condition which you are forcing to be true. If it is not true, you can catch the error using the except statement and handle it there.
In your case you could have:
assert(((x <= 5) and (x >= 0)))
number = raw_input("Enter numbers separated by spaces: ")
2 num_list = number.split()
3 for n in num_list:
4 a = 'True'
5 if int(n) <0 or int(n) >5:
6 a = 'False'
7 break
8 if (len(num_list) == 5) and a == 'True':
9 for n in num_list:
10 b = int(n)
11 if 0< b <=5:
12 print ('x'* b)
13 elif b == 0:
14 print ('.')
15 else:
16 print 'Invalid Input!'