I don't realize what is my mistake, this is how far I got now:
x = 1
e = 0
while x <= 50:
print "Please enter a number (from 1 to 9):"
b = float(raw_input())
asd = 0
if asd == 0:
h = b
l = b
asd = 1
if b < l:
l = b
elif b > h:
h = b
if 1 <= b or b <= 9:
x = x * b
print x
else:
print "Number is too large or too small."
e = e + 1
print "You have reached a value over 50."
print "Highest number entered:", h
print "Lowest number entered:", l
print "Entered numbers:", e
This is the program's output:
Please enter a number (from 1 to 9):
5
5.0
Please enter a number (from 1 to 9):
4
20.0
Please enter a number (from 1 to 9):
5
100.0
You have reached a value over 50.
Highest number entered: 5.0
Lowest number entered: 5.0
Entered numbers: 3
Why is the program giving me 5 instead of 4 as lowest number entered and how can I correct that?
You keep resetting asd each iteration, you need to set the variables outside the loop, I would use a list and that will enable you to get the min/max and number of valid inputs :
nums = [] # hold all nums outside the loop
limit = 1
while 50 >= limit:
num = float(raw_input("Please enter a number (from 1 to 9)")
if 1 <= num <= 9:
limit *= num
nums.append(num) # add all to list
else:
print "Number is too large or too small."
print "You have reached a value over 50."
print "Highest number entered:", max(nums)
print "Lowest number entered:", min(nums)
print "Entered numbers:", len(nums)
Everytime you go through the loop, you are setting asd to 0, causing the if statement below it to execute every single time, so you are always blindly updating l with the value the user just entered, which you have named as b
just for fun :)
def get_float_input(msg="Enter a Number:"):
while True:
try:
return float(raw_input(msg))
except ValueError:
print "Invalid Input Please Enter A Float!"
from itertools import takewhile
my_list = sorted(takewhile(lambda val:val < 50,iter(get_float_input,"Y")))
print "You Have Entered A # Greater than 50"
print "Min:",my_list[0]
print "Max:",my_list[-1]
print "Entered %d Numbers"%len(my_list)
Related
I already solved this with list.append() function however my instructor told me to just use the basic python functions. Here is my code:
a = 0
b = 0
s = 0
x = str(s)
print ('Enter the first number: ', end = '')
c = input()
a = int(c)
finished = False
while not finished:
print ('Enter the next number (0 to finish): ', end ='')
n = input()
b = int(n)
if b != 0:
if b == a:
x = ('Same')
elif b > a:
x = ('Up')
elif b < a:
x = ('Down')
a = b
s = x
else:
finished = True
print (str(x))
I am aiming to print (e.g. Up Down Up Down Same in comparing the input integers) in one line at the end of the while loop. Let me know how can I improve my code. Thank you very much
Use string concatenation to get the result you want without using a list:
http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python
I'll give you two hints on how to do this for your program:
Initialize x as an empty string by replacing
x=str(s)
with
x=""
There is no need for it to begin as the string "0", which str(s) does since s is 0.
Instead of saying
x=('SAME')
x=('UP')
x=('DOWN')
try saying
x=x+'SAME'
x=x+'UP'
x=x+'DOWN'
I removed the parentheses because they are not necessary.
As for style, it is good practice to name your variables as useful things instead of just letters. Last staement in an if/else chain that covers all bases should just be else. Best of luck to you sir
Not sure what result you're looking for, but perhaps this works:
a = 0
b = 99
result = ""
a = int(input('Enter the first number: '))
while b != 0:
b = int(input('Enter the next number (0 to finish): '))
if b == a:
result += ' Same'
elif b > a:
result += ' Up'
elif b < a:
result += ' Down'
a = b
print(result.strip())
Output:
Enter the first number: 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 5
Enter the next number (0 to finish): 0
Same Same Down Same Up Down
You can simply initialize x with an empty string and keep concatenating to it.
a = 0
b = 0
s = 0
x = ''
print('Enter the first number: ', end='')
c = input()
a = int(c)
finished = False
while not finished:
print('Enter the next number (0 to finish): ', end='')
n = input()
b = int(n)
if b != 0:
if b == a:
x += 'Same\n'
elif b > a:
x += 'Up\n'
elif b < a:
x += 'Down\n'
a = b
s = x
else:
finished = True
print(str(x))
I want to print "Same number" if the new number value equals to the last one(same number), else print number variable value if it has changed. How can I do that?
from random import randint
x=0
number=(randint(0,9))
while(x<10):
x+= 1
if(number=="""LAST PRINTED VALUE NUMBER"""):
print ("Same number")
else:
print(number)
You can chage last number in the while loop:
x, last = 0, -1
while (x < 10):
number = randint(0, 9)
if (number == last):
print ("Same number")
else:
print("Last number is {0} now it is {1}".format(last,number))
last = number
x += 1
Output:
Last number is -1 now it is 1
Last number is 1 now it is 2
Last number is 2 now it is 4
Same number
Last number is 4 now it is 2
Last number is 2 now it is 6
Last number is 6 now it is 7
Same number
Last number is 7 now it is 2
Same number
Just save the last one:
from random import randint
x=0
old = number= randint(0,9)
while(x<10):
x+= 1
if(number==old and x > 0):
print ("Same number")
else:
print(number)
old = number
number = randint(0,9)
from random import randint
x = 0
number = -1
while(x < 10):
y = number
number=(randint(0,9))
x+= 1
if(number== y):
print ("Same number")
else:
print(number)
You just need a third variable. Within the "else" after the print statement, set this third variable to "number".
I have a different method:
from random import randint
new = randint(0, 10)
old = new
for i in range(10):
new = randint(0, 10)
if new == old:
print("Same number ({0})".format(new))
else:
print("Diffrent (Last: {0} Now: {1})".format(old, new))
old = new
Output:
Diffrent (Last: 6 Now: 9)
Diffrent (Last: 9 Now: 0)
Diffrent (Last: 0 Now: 2)
Same number (2)
Diffrent (Last: 2 Now: 6)
Same number (6)
Diffrent (Last: 6 Now: 7)
Diffrent (Last: 7 Now: 4)
Same number (4)
Diffrent (Last: 4 Now: 10)
I am trying to complete a Python code that counts each beat and places an X if its divisible by a number.
Example :
Divisions: 3
Divisible by: 2
Divisible by: 3
Divisible by: 4
Number of beats to print: 10
1:
2:X
3: X
4:X X
5:
6:XX
7:
8:X X
9: X
10:X
You see how 2 is divisible by 2 so it prints an X on the first column? And 6 is divisible by both 2 and 3 so it prints an X on the first and second column? I need help doing that :)
This is my code so far, can anyone please complete it or help me complete it? I think i need to put the second loop inside another loop, because i need to loop over the numbers from 1 to c, working out for each beat whether it is divisible by each d (the numbers from list1). I probably need to make the loop increment b from 1 to c.
My Workaround :
list1 = []
a = int(input("Divisions: "))
for b in range(1,a+1):
z = int(input("Divisible by: "))
list1.append(z)
c = int(input("Number of beats to print: "))
for e in range(1,c+1):
for d in list1:
remainder = b%d
if remainder == 0:
print(" "+str(e)+":","X")
divs = [int(input('Divisible by: ')) for _ in range(int(input('Divisions: ')))]
for beat in range(1, int(input('Number of beats to print: ')) + 1):
print '%2d:%s' % (beat, ''.join(
'X' if (beat % div) == 0 else ' ' for div in divs).rstrip())
Using the test case you provided:
Divisions: 3
Divisible by: 2
Divisible by: 3
Divisible by: 4
Number of beats to print: 10
1:
2:X
3: X
4:X X
5:
6:XX
7:
8:X X
9: X
10:X
list1 = []
a = int(input("Divisions: "))
for b in range(1,a+1):
z = int(input("Divisible by: "))
list1.append(z)
c = int(input("Number of beats to print: "))
for e in range(1,c+1):
print('%3d:'%(e), end='')
string=''
for d in list1:
remainder = e%d
if remainder == 0:
string += 'X'
else:
string += ' '
print(string.rstrip())
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!'