This program will ask the user a series of questions about two numbers. These two numbers will be generated randomly between 1 and 10 and it will ask the user 10 times. At the end of these 10 questions the program will display how many the user got correct out of those questions.
Each question should randomly decide between asking for the product, sum, or difference. Separate the question asking into a function, as well as the validating user input.
I tried using with three product, sum or difference in random to generate. I tried to use z = random.randint(1, 4) is to select from 1 is product, 2 is sum, or 3 is difference and then I used with if variable z is 1, then do product math or if var z is 3, then it should be difference like this x / y, but I couldn't figure it finish it up. I have the expected result when I first run with product but it works so I just need to add with sum and difference included.
EXPECTED OUTPUT with product (Some are incorrect for testing with scores):
> python3 rand3.py
What is 3 x 4
Enter a number: 12
What is 3 x 7
Enter a number: 27
What is 6 x 3
Enter a number: 18
What is 7 x 10
Enter a number: 70
What is 9 x 10
Enter a number: 90
What is 9 x 7
Enter a number: 72
What is 5 x 9
Enter a number: 54
What is 6 x 8
Enter a number:
Incorrect Input!
Enter a number: 48
What is 1 x 5
Enter a number: 5
What is 10 x 3
Enter a number: 30
You got 7 correct out of 10
My Work for Product Only (Success):
import random
def askNum():
while(1):
try:
userInput = int(input("Enter a number: "))
break
except ValueError:
print("Incorrect Input!")
return userInput
def askQuestion():
x = random.randint(1, 100)
y = random.randint(1, 100)
print("What is " + str(x) + " x " +str(y))
u = askNum()
if (u == x * y):
return 1
else:
return 0
amount = 10
correct = 0
for i in range(amount):
correct += askQuestion()
print("You got %d correct out of %d" % (correct, amount))
My Currently Work: (I am working to add sum and difference like the expected output
UPDATED: After the expected output works well with product so I am trying to add new random int for z with 1-3 which means I am using with 1 is for product, 2 is for sum and 3 is difference by using if-statement by given random select. I am struggle at this is where I stopped and figure it out how to do math random because I am new to Python over a month now.
import random
def askNum():
while(1):
try:
userInput = int(input("Enter a number: "))
break
except ValueError:
print("Incorrect Input!")
return userInput
def askQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
z = random.randint(1, 4)
print("What is " + str(x) + " "+ str(z)+ " " +str(y))
u = askNum()
if (z == 1):
x * y #product
return 1
else if (z == 2):
x + y #sum
return 1
else if (z == 3):
x / y #difference
return 1
else
return 0
amount = 10
correct = 0
for i in range(amount):
correct += askQuestion()
print("You got %d correct out of %d" % (correct, amount))
OUTPUT:
md35#isu:/u1/work/python/mathquiz> python3 mathquiz.py
File "mathquiz.py", line 27
if (z == 1):
^
IndentationError: unexpected indent
md35#isu:/u1/work/python/mathquiz>
With this currently output, I double checked with corrected Python formatting and everything are sensitive, and still the same as running output. Any help would be more appreciated with explanation. (I hope my English is okay to understand since i'm deaf) I have started this since on Saturday, than expected on time to meet.
Your problem is that python 3 does not allow mixing spaces and tabs for indentation. Use an editor that displays the whitespace used (and fix manually) or one that replaces tabs into spaces. It is suggested to use 4 spaces for indentation - read PEP-0008 for more styling tips.
You can make your program less cryptic if you use '+','-','*','/' instead of 1,2,3,4 to map your operation: ops = random.choice("+-*/") gives you one of your operators as string. You feed it into a calc(a,ops,b) function and return the correct result from it.
You can also shorten your askNum and provide the text to print.
These could look like so:
def askNum(text):
"""Retunrs an integer from input using 'text'. Loops until valid input given."""
while True:
try:
return int(input(text))
except ValueError:
print("Incorrect Input!")
def calc(a,ops,b):
"""Returns integer operation result from using : 'a','ops','b'"""
if ops == "+": return a+b
elif ops == "-": return a-b
elif ops == "*": return a*b
elif ops == "/": return a//b # integer division
else: raise ValueError("Unsupported math operation")
Last but not least you need to fix the division part - you allow only integer inputs so you can also only give division problems that are solveable using an integer answer.
Program:
import random
total = 10
correct = 0
nums = range(1,11)
for _ in range(total):
ops = random.choice("+-*/")
a,b = random.choices(nums,k=2)
# you only allow integer input - your division therefore is
# limited to results that are integers - make sure that this
# is the case here by rerolling a,b until they match
while ops == "/" and (a%b != 0 or a<=b):
a,b = random.choices(nums,k=2)
# make sure not to go below 0 for -
while ops == "-" and a<b:
a,b = random.choices(nums,k=2)
# as a formatted text
result = askNum("What is {} {} {} = ".format(a,ops,b))
# calculate correct result
corr = calc(a,ops,b)
if result == corr:
correct += 1
print("Correct")
else:
print("Wrong. Correct solution is: {} {} {} = {}".format(a,ops,b,corr))
print("You have {} out of {} correct.".format(correct,total))
Output:
What is 8 / 1 = 3
Wrong. Correct solution is: 8 / 1 = 8
What is 5 - 3 = 3
Wrong. Correct solution is: 5 - 3 = 2
What is 4 - 2 = 3
Wrong. Correct solution is: 4 - 2 = 2
What is 3 * 1 = 3
Correct
What is 8 - 5 = 3
Correct
What is 4 / 1 = 3
Wrong. Correct solution is: 4 / 1 = 4
What is 8 * 7 = 3
Wrong. Correct solution is: 8 * 7 = 56
What is 9 + 3 = 3
Wrong. Correct solution is: 9 + 3 = 12
What is 8 - 1 = 3
Wrong. Correct solution is: 8 - 1 = 7
What is 10 / 5 = 3
Wrong. Correct solution is: 10 / 5 = 2
You have 2 out of 10 correct.
def askQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
z = random.randint(1, 4)
print("What is " + str(x) + " "+ str(z)+ " " +str(y))
u = askNum()
if (z == 1):
x * y #product
return 1
elif (z == 2):
x + y #sum
return 1
elif (z == 3):
x / y #difference
return 1
else:
return 0
Write your block like this your u = askNum() and next if loop should be on same vertical line.
To Generate n number of random number you can use
random.sample(range(from, to),how_many_numbers)
User this as reference for more info on random
import random
low=0
high=4
n=2 #no of random numbers
rand = random.sample(range(low, high), n)
#List of Operators
arithmetic_operators = ["+", "-", "/", "*"];
operator = random.randint(0, 3)
x = rand[0];
y = rand[1];
result=0;
# print(x, operator, y)
if (operator == 0):
result = x + y# sum
elif(operator == 1):
result = x - y# difference
elif(operator == 2):
result= x / y#division
else :
result=x * y# product
print("What is {} {} {}? = ".format(x,arithmetic_operators[operator],y))
The following stores a random number(int)
operator = random.randint(0, 3)
to compare it with the list for operators.
Example: operator = 2
elif(operator == 2):
result= x / y#division
than this code will executed and because operator=2, 3rd element from list(/) will be selected
Output:
What is 3 / 2?
Related
So basically what i am trying to achieve is get my program to perform a n number of iterations on one input variable(i use a for loop for this). After the for loop ends the program asks the user if they want to continue, for yes the program then asks the user for another n number of iterations to perform on the same input variable. The program then has to start the operation from where it left from the previous value, i used a dictionary for this but cant find it working. Would be great if i can get some help.
my code is pasted below:
def function(x, i):
return x**i
num_dic = {}
j = 1
while True:
if j == 1:
start = 1
n = int(input("number of iterations: "))
x = int(input("Number to perform operation: "))
for i in range(start, n + 1):
total = function(x, i)
print(f"{x}", "**", i, "=", total)
num_dic[f"{i}"] = total
elif j > 1:
start = int(sorted(num_dic.keys())[-1]) + 1
x = sorted(num_dic.values())[-1]
n = int(input("number of iterations: "))
for i in range(start, n + 1):
total = function(x, i)
print(f"{x}", "**", i, "=", total)
num_dic[f"{i}"] = total
j += 1
while True: # while loop for repeating program
ask = input("Do you want to continue?(Y to continue/ N to exit): ")
if ask.upper() == "Y":
break
if ask.upper() == "N":
break
else:
print("Please enter a correct operation (Y/N) ")
continue
if ask.upper() == "Y":
continue
else:
break
current output i am getting:
number of iterations: 5
Number to perform operation: 2
2 ** 1 = 2
2 ** 2 = 4
2 ** 3 = 8
2 ** 4 = 16
2 ** 5 = 32
Do you want to continue?(Y to continue/ N to exit): y
number of iterations: 5
after this part it just doesn't do anything.
the desired output should look like:
number of iterations: 5
Number to perform operation: 2
2 ** 1 = 2
2 ** 2 = 4
2 ** 3 = 8
2 ** 4 = 16
2 ** 5 = 32
Do you want to continue?(Y to continue/ N to exit): y
number of iterations: 5
2 ** 6 = 64
2 ** 7 = 128
2 ** 8 = 256
2 ** 9 = 512
2 ** 10 = 1024
You don't need a dictionary for this operation. You just need a clean and proper while-loop that can keep track of your variables, specifically the exponent (variable j in your original code) and your number of iterations, n.
base doesn't change, so it should be left outside the while-loop, as advised by the #Blckknght's answer to this question.
exponent = 1
base = int(input("Number to perform operation: "))
n = None # initialize n to None
while True:
# logic to keep track of n in the previous loop, if there is one.
if n:
n += int(input("number of iterations: ")) # cumulatively increment n if user wishes to continue.
else:
n = int(input("number of iterations: "))
# while-loop that prints the output for a single set of x and n values
while n >= j:
print(f"{base} ** {exponent} = {base ** exponent}")
exponent += 1
# get user input for continuation
ask = input("Do you want to continue?(Y/ N): ")
# while loop to handle user input values
while ask.upper() not in ["Y", "N"]:
ask = input("Please enter a correct operation (Y/N).")
if ask.upper() == 'Y':
continue # loop back to the outer while-loop and ask for another set of user input
elif ask.upper() == 'N':
break # break if user says no
Since you only need to keep track of where you left off, there's no need to store many values in a dictionary. Just remembering the base and the last exponent used is enough. And conveniently, the variables x and i that you're using won't automatically get reset between iterations, so you can just start the next iteration from i + 1:
elif j > 1:
n = int(input("number of iterations: "))
for i in range(i+1, i + n + 1):
total = function(x, i)
print(f"{x}", "**", i, "=", total)
Indeed, you could probably simplify things so that you don't need a special case for the first iteration. Just ask for the base before the loop starts! Here's how I'd do it (using more descriptive variable names too):
base = int(input("Number to perform operation: "))
start_from = 1
while True:
n = int(input("number of iterations: "))
for exponent in range(start_from, start_from + n):
print(f'{base} ** {exponent} = {function(base, exponent)}')
start_from = start_from + n
# ask about continuing down here, optionally break out
If you really want to prompt for the number of iterations first, before asking for the base, you could probably make that work by using a sentinel value like None to indicate when it hasn't been set yet, so that you only prompt for it the first iteration (without explicitly counting):
base = None
start_from = 0
while True:
n = int(input("number of iterations: "))
if base is None:
base = int(input("Number to perform operation: "))
# ...
This is my code, it outputs a multiplication table but it's not what I wanted!
num = int(input("Multiplication using value? : "))
while num <= 10:
i = 1
while i <= num:
product = num*i
print(num, " * ", i, " = ", product, "\n")
i = i + 1
print("\n")
num = num + 1
I am basically creating a multiplication table from the user's input from 1-9.
Ex. If the user inputs "3",
I should get this output:
1*1=1
1*2=2
1*3=3
2*1=2
2*2=4
2*3=6
3*1=3
3*2=6
3*3=9
The reason why you have an infinite loop on your hands is because you are comparing i to num, while also increasing num on every run. If you make sure i is always <= 10, you get your desired output:
while num <= 10:
i = 1
while i <= 10:
product = num*i
print(num, " * ", i, " = ", product, "\n")
i = i + 1
num = num + 1
print("\n")
Even if the code you posted is not pythonic at all (it is very close to what could be written in C language), it nearly works: with minimum modifications, it can be fixed as follows to give your expected ouput:
numInput = int(input("Multiplication using value? : "))
num = 1
while num <= numInput:
i = 1
while i <= numInput:
product = num*i
print(num, " * ", i, " = ", product)
i = i + 1
print("") # no need to add explicit newline character because it is automatically added
num = num + 1
In a more pythonic way, you can also do the following:
numInput = int(input("Multiplication using value? : "))
for i in range(1,numInput+1):
for j in range(1,numInput+1):
print(i, " * ", j, " = ", i*j)
print("")
For this problem it's easier to use for loops.
num = int(input("Multiplication using value? : "))
for left in range(1,num+1): # 1st loop
for right in range(1,num+1): # 2nd loop (nested)
print(left, " * ", right, " = ", left * right)
print() # newline
To understand this problem, look at the two multiplicands: left and right.
Left multiplicand goes from (1-->num), hence the first for loop.
Then, for each value of the left multiplicand, the right multiplicand goes from (1-->num), hence the 2nd loop is nested inside the first loop.
You've lots of logical error. Please have a look at this updated code:
num = int(input("Multiplication using value : "))
i=1 #you haven't initialized this variable
while i <=num:
j=1
while j <= num:
product = i*j #updated
print(i, " * ", j, " = ", product, "\n") #updated
j = j + 1
print("\n")
i = i + 1
Output (for input 3):
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
In Python 3.6+, you can use f-strings with a nested for loop:
num = int(input("Multiplication using value? : "))
for i in range(1, num+1):
for j in range(1, num+1):
print(f'{i} * {j} = {i*j}')
Multiplication using value? : 3
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
multiplication table using while loop in python
num = int(input("enter the number= "))
i = 1
while i<=10:
print(num, "X", i, "=", num * i)
i = i+1
output
enter the number= 33
33 X 1 = 33
33 X 2 = 66
33 X 3 = 99
33 X 4 = 132
33 X 5 = 165
33 X 6 = 198
33 X 7 = 231
33 X 8 = 264
33 X 9 = 297
33 X 10 = 330
num = int(input("Enter the number: "))
i = 1
print("Mulltiplication of number:", num)
while i<=10:
print(f"{num}X{i}={num*i}")
i = i + 1
Multiplication table 1 to 10
for x in range(1,11):
for y in range(1,11):
print(x*y, end='\t')
print()
print()
input any number to get your normal multiple table(Nomenclature) in 10 iterate times.
num = int(input("Input a number: "))
# use for loop to iterate 10 times
for i in range(1,11):
print(num,'x',i,'=',num*i)
num = int(input('Enter the number you want the multiplication table for:'))
i=1
while i<=10:
product = num*i
print(product)
i=i+1
print('Thank you')
Creating a multiplication table using while loop is shown below:
b = int(input('Enter the number of the multiplicaction table : '))
print('The multiplication table of '+ str(b) + 'is : ')
a=0
while a<=11:
a=a+1
c= a*b
print( str(b)+' x '+str(a)+' ='+str(c))
print('done!!!!')
To create a multiplication table in python:
name=int(input("Enter the number of multiplication"))
i=1
while(i<=10):
print(str(name)+"X"+str(i)"="+str(name*i))
i=i+1
I tried to create a python-based ISBN13 Validity Calculator, which is supposed to work according to the following snip of code. It takes in an argument of type string and prints the result.
I don't understand where I got wrong here, In this program, common sense tells me num will give a 3 or a 1 alternatively.
def isbncheck(isbn):
num = int(0)
for i in range(0,12):
if num % 2 is 1:
num = num + (int(isbn[i])*3)
print(isbn[i] + " * 3 + at i=" + str(i))
elif num % 2 is 0:
num = num + (int(isbn[i]))
print(isbn[i] + " * 1 + at i=" + str(i))
else:
print("Unhandled Exception.")
print("_"*7)
print(num)
num = num%10
print(num)
print(isbn[12])
print(int(isbn[12]))
if num != int(isbn[12]):
print("This is not valid")
else:
print("It is Valid.")
print(isbncheck("9788177000252"))
I expected the output to alternate factors of 1 and 3. Instead, I got this:
9 * 1 + at i=0
7 * 3 + at i=1
8 * 1 + at i=2
8 * 1 + at i=3
1 * 1 + at i=4
7 * 3 + at i=5
7 * 1 + at i=6
0 * 3 + at i=7
0 * 3 + at i=8
0 * 3 + at i=9
2 * 3 + at i=10
5 * 3 + at i=11
_______
96
6
2
2
This is not valid
None
How do you work around it? Other than not expanding the loop?
Your problem is here:
for i in range(0,12):
if num % 2 is 1:
num is your accumulated sum. You have to check the index, not the sum so far.
for i in range(len(isbn)):
digit = int(isbn[i])
if i % 2 == 1:
num += 3 * digit
Also note some minor improvements:
Since you have to refer to the value twice, convert to int and hold it in a temporary digit.
use == for numerical comparison; is gives you object comparison, which will fail for general cases.
According to the ISBN spec, the 3 goes on every other digit, so your if statement should be if i % 2 is 1:, not if num % 2 is 1: (and the elif should be changed accordingly).
Also, you must take 10 minus the result of the modulo operation; so after num = num%10 you would have the new line num = 10 - num. Otherwise your computed check digit (num) will be incorrect.
Another note: is only works on some implementations to compare numbers between -1 and 256 (source), which is why it works in this case. But in general == is more suited for comparing two numbers.
So this is a cs assignment, and I wrote code that works for 2 out of the 9 test cases (which are unknown), but I don't know why it won't work/pass any other ones. I understand I should try to figure out how to do this on my own, and I have tried, but I am really lost and need help!
"Write a file named credit_card.py containing a single function, check. Check accepts a single input – a positive integer. It returns True if the integer represents a valid credit card number. As with all functions that return a bool value, if it does not return True it should return False.
Credit card numbers have what is called a check digit. This is a simple way of detecting common mis-typings of card numbers. The algorithm is as follows:
Form a sum of every other digit, including the right-most digit; so 5490123456789128 (5490123456789128) sums to 4 + 0 + 2 + 4 + 6 + 8 + 1 + 8 = 33.
Double each remaining digit, then sum all the digits that creates it; the remaining digits (5 9 1 3 5 7 9 2) in our example (5490123456789128) double to 10 18 2 6 10 14 18 4, which sums to 1+0 + 1+8 + 2 + 6 + 1+0 + 1+4 + 1+8 + 4 = 37
Add the two sums above (33 + 37 = 70)
If the result is a multiple of 10 (i.e., its last digit is 0) then it was a valid credit card number."
def check(x):
num1 = 0
num2 = 0
if x < 0:
return False
for i in str(x) [1::2]:
num1 += int(i)
return num1
for i in str(x) [0::2]:
num2 += int(int(i * 2) % 10) + int(int(i * 2) / 10)
return num2
check_digit = num1 + num2
if check_digit % 10 == 0:
return True
else:
return False
def check(x):
if x[0] == '-': # x is [str], "x < 0" is wrong
return False
try:
nums = map(int, x)
except Exception:
return False
sum1 = 0
sum2 = 0
for i in nums[1::2]:
sum1 += int(i)
for i in nums[0::2]:
sum2 += ((i * 2) % 10 + (i * 2) / 10) # i is [str], "i * 2" is wrong
check_digit = sum1 + sum2
if check_digit % 10 == 0:
return True
else:
return False
How can I take an integer as input, of which the output will be the Collatz sequence following that number. This sequence is computed by the following rules:
if n is even, the next number is n/2
if n is odd, the next number is 3n + 1.
e.g. when starting with 11
11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
This is my code now:
n = int(raw_input('insert a random number'))
while n > 1:
if n%2 == 0:
n_add = [n/2]
collatz = [] + n_add
else:
n_add2 = [3*n + 1]
collatz = [] + n_add2
print collatz
if I execute this and insert a number, nothing happens.
You are never changing the number n, so it will be the same each time round. You are also only printing if the number is odd. Also, square brackets [] indicate an array - I'm not sure what your goal is with this. I would probably rewrite it like this:
n = int(raw_input('insert a random number'))
while n > 1:
if n%2 == 0:
n = n/2
else:
n = 3*n + 1
print n
You might want to take some time to compare and contrast what I'm doing with your instructions - it is almost literally a word-for-word translation (except for the print
It is a little unclear from your code if you want to just print them out as they come out, or if you want to collect them all, and print them out at the end.
You should be modifying n each time, this will do what you want:
n = int(raw_input('insert a random number'))
while n > 1:
n = n / 2 if not n & 1 else 3 * n + 1 # if last bit is not set to 1(number is odd)
print n
## -- End pasted text --
insert a random number11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Using your own code to just print out each n:
n = int(raw_input('insert a random number'))
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
print n
Or keep all in a list and print at the end:
all_seq = []
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
all_seq.append(n)
print(all_seq)
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = number * 3 + 1
print(number)
try:
num = int(input('Please pick any whole number to see the Collatz Sequence in action.\n'))
collatz(num)
except ValueError:
print('Please use whole numbers only.')
I've also been working on it for a while now, and here's what I came up with:
def collatz (number):
while number != 1:
if number == 0:
break
elif number == 2:
break
elif number % 2 == 0:
number = number // 2
print (number)
elif number % 2 == 1:
number = 3 * number + 1
print (number)
if number == 0:
print ("This isn't a positive integer. It doesn't count")
elif number == 2:
print ("1")
print ("Done!")
elif number == 1:
print ("1")
print ("Done!")
try:
number = int(input("Please enter your number here and watch me do my magic: "))
except (ValueError, TypeError):
print ("Please enter positive integers only")
try:
collatz(number)
except (NameError):
print ("Can't perform operation without a valid input.")
Here is my Program:
def collatz(number):
if number % 2 == 0:
print(number//2)
return number // 2
elif number % 2 == 1:
print(3*number+1)
return 3*number+1
else:
print("Invalid number")
number = input("Please enter number: ")
while number != 1:
number = collatz(int(number))`
And the output of this program:
Please enter number: 12
6
3
10
5
16
8
4
2
1