I am very new to python and coding as a whole, so this might be something very basic. I am trying to execute this code, but instead of multiplying the value, it just doubles the numerical. I have tried changing it multiple times in different places, but nothing works. Here is the code:
num=input("Enter a number:")
doub=num*2
print("Double of {0}, is {1}".format(num,doub))
If num is 4, instead of outputting num*2 as 8, it outputs it as 44.
I attached the link to the image as well, hopefully, it is displayed properly here, while I earn some reputation points lol.
Thanks!
You need to convert the num variable from string to integer or decimal:
num = input("Enter a number:")
doub = int(num) * 2 # <-- HERE
print("Double of {0}, is {1}".format(num, doub))
Related
so im learning programming (python, visual studio community) and im trying to write a game in python and the best way of describing it is mastermind (a chosen length of numbers are randomly generated, you guess and it tells you if there are correct numbers in the correct position but not which position they are in) it seems as if everything else in this works so far apart from the fact that because this program will be able to do an infinite length i must check these numbers using a variable that increases by 1 each time if guess[y]==randomnumber[y]:, every time i run this i get the error msg:"'int' object is not subscriptable".
here is the full code:
length=int(input("what length do you want: "))
import random
if length==0:
length=int(input("what length do you want: "))
if length!=0:
x=0
while x!=length:
randomnumber=[int(random.randint(0,9))]
x=x+1
x=0
game_over=0
while game_over==0:
guess=int(input("your guess: "))
y=0
round_score=0
y=int(y)
while y!=length:
if guess[y]==randomnumber[y]:
round_score=round_score+1
y=y+1
if round_score==length:
game_over=1
You want to convert the guess to a list of ints.
Get input as string:
guess = input("your guess: ")
Sequence of characters (aka string) to int list:
guess = [int(c) for c in guess]
This could be written in one line but I think it is more clear this way.
Alrighty, first post here, so please forgive and ignore if the question is not workable;
Background:
I'm in computer science 160. I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced. We have been working in Python and each week we are prompted to write a program.
I have been working with this problem for over a week and am having a hard time even starting.
The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent. Now, I have gotten some tips from a classmate and it sent me at least in a direction.
Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.
I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.
setbitval = 0
counter = 0
user = int(input("enter a binary value. "))
if user % 2 == 1:
user = (user/10) - .1
setbitval += 1
This is all I've got so far.. My thinking is getting in the way. I've searched and searched, even through these forums.
Any information or thoughts are extremely appreciated,
T
Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.
for i in reversed(bits):
decimal += 2**counter * int(i)
counter += 1
This is the formula someone here gave me and I've been trying different iterations of "for i in bits: if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".
Any thoughts?
you can use this code:
binary= raw_input("Binary: ")
d= int(binary, 2)
print d
To convert binary value to decimal you need to do the following:
Take the least significant bit and multiply it by 2^0, then take the next least significant beat and multiply it by 2^1, next one by 2^2 and so on...
Let's say, for example you need to convert a number 1010 to decimal:
You would have 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10
So in your python code, you need to:
read the int that the user inputted (representing the binary value).
convert that int and convert it to string, so you can break it into list of digits
make a list of digits from the string you created (a list int python can be created from a string not an int, that's why you need the conversion to string first)
go trough that list of bits in reverse and multiply every bit by 2^k, k being the counter starting from 0
Here's the code that demonstrates what I just tried to explain:
user_input = int(input("enter a binary value"))
bits = list(str(user_input))
decimal = 0
counter = 0
for i in reversed(bits):
decimal += 2**counter * int(i)
counter+=1
print 'The decimal value is: ', decimal
I'll agree this is close to the "code this for me" territory, but I'll try to answer in a way that gets you on the right track, instead of just posting a working code snippet.
A simple way of doing this is just to use int()'s base argument, but I'm guessing that is disallowed.
You already have a way of testing the current bit in your question, namely checking whether n % 2 == 1. If this is the case, we need to add a power of two.
Then, we need some way of going to the next bit. In binary, we would use bit shifts, but sadly, we don't have those. a >> b is equivalent to a // (2**b) - can you write a decimal equivalent to that?
You also need to keep a counter of which power of two the current bit represents, a loop, and some way of detecting an end condition. Those are left as exercises to the reader.
I’d recommend reading the following articles on Wikipedia:
https://en.wikipedia.org/wiki/Radix
https://en.wikipedia.org/wiki/Binary_number
The first one gives you an idea how the numeral systems work in general and the second one explains and shows the formula to convert between binary and decimal systems.
Try to implement the solution after reading this. That’s what I did when I dealt with this problem. If that doesn’t help, let me know and I’ll post the code.
Hopefully, this code clarifies things a bit.
x = input("Enter binary number: ").strip()
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
print(decimal)
This code takes in a binary number as a string, converts it to a decimal number and outputs it as an integer. The procedure is the following:
1st element of binary number * 2^(length of binary number - 1)
2nd element of binary number * 2^(length of binary number - 2)
and so on till we get to the last element and ...2^0
If we take number 10011, the conversion using this formula will look like this:
1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0, which equals to 19.
This code, however, assumes that the binary number is valid. Let me know if it helps.
Another implementation using while loop might look like this. Maybe it'll be easier to understand than the code with the for loop.
x = input("Enter binary number: ").strip()
decimal = 0
index = 0
exp = len(x) - 1
while index != len(x):
decimal += int(x[index]) * 2**exp
index += 1
exp -= 1
print(decimal)
In this one we start from the beginning of the number with the highest power, which is length of binary number minus one, we loop through the number, lowering the power and changing index.
Regarding checking if number is binary.
Try using helper function to determine if number is binary and then insert this function inside your main function. For example:
def is_binary(x):
""" Returns True if number x is binary and False otherwise.
input: x as a string
"""
for i in list(x):
if i not in ["1", "0"]:
return False
return True
def binary_decimal(x):
""" Converts binary to decimal.
input: binary number x as a string
output: decimal number as int
"""
if not is_binary(x):
return "Number is invalid"
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
return decimal
The first function checks if number consists only of ones and zeros and the second function actually converts your number only if it's binary according to the first function.
You can also try using assert statement or try / except if you'd better raise an error if number is not binary instead of simply printing the message.
Of course, you can implement this solution without any functions.
I am taking GCSE programming and have be set a task to create a program which takes "n" amount of numbers and works out the average.
#presets for varibles
nCount = 0
total = 0
average = 0.0
Numbers = []
ValidInt = False
#start of string
nCount = (input("How many numbers? "))
print(nCount)
while not ValidInt:
try:
int(nCount)
ValidInt = True
except:
nCount = input("Please Enter An Interger Number")
#validation loops untill an interger is entered
for x in range (int(nCount)):
Numbers.append(input("Please Enter The Next Number"))
This is what i have so far but cannot think how i can code it to work out an average from this information? Any help is much appreciated, Thank you(i am not looking for answers just help in what function as i should use)
You're really close to the answer. Looks like you've got everything setup and ready to calculate the average, so very good job.
Python's got two built-in functions sum and len which can be used to calculate the sum of all the numbers, then divide that sum by how many numbers have been collected. Add this as the last line in your program and check the output.
Note: Since inputs were taken as integers (whole numbers) and the average will usually be a non-whole number, we make one of the numbers a float before calculating the average:
print(sum(Numbers)/float(len(Numbers)))
Edit: Or, since you've got a variable that already holds how many numbers the user has input, nCount, we can use this calculation, which will give the same answer:
print(sum(Numbers)/float(nCount)).
Try both and choose one or make your own.
please help me... "Read in two numbers from user input without a prompt, add them, and print the result.
Hint: Use int() to convert the numbers to integers.
Note: These activities may test code with different test values. This activity will perform two tests: the first with num1 = 5 and num2 = 10, the second with num1 = 6 and num2 = 3. "
I tried just doing one and it didn't work but I can't wrap my head around how to do two tests let alone one...
I tried this so far and it came out with 510..noob please help
num1=int(input(5))
num2=int(input(10))
num3=num1 + num2
The argument to the input() function is the string to display as a prompt.
In your case, you'd want that to be simply input().
in fact you need just:
num1 = int(input())
num2 = int(input())
num3 = num1+num2
print(num3)
Don't pass parameters into input. You're asking the user for input.
I don't think the assignment is asking you to write your own tests. I think it's saying that whatever code you give it will be tested.
person_name = input()
person_age = int(input())
I'm trying to make a basic dice roller. When i run this program in Codeskulptor, it throws an error on the randint function. Can I not set the range for it using raw_input plugged into variables? Is there a different function I should use?
"""Program to roll random numbers within the ranges set."""
import random
sides_of_die=raw_input("Enter how many sides your die has: ")
number_of_dice=raw_input("Enter number of dice you have: ")
total=sides_of_die*number_of_dice
rollinput=raw_input("Would you like to roll now?")
rollinputcap=rollinput.upper()
if rollinputcap =="Y":
print random.randint(number_of_dice,total)
else:
print "What do you want then?"
raw_input() returns a string, not an integer. To convert it to an integer type, use int():
sides_of_die = int(raw_input("Enter how many sides your die has: "))
number_of_dice = int(raw_input("Enter number of dice you have: "))
What's happening in your code is, you may input "6" and "2", so when you do total = sides_of_die * number_of_dice, you're getting a TypeError
This is just because raw_input returns a string, not a number, while randint accept two numbers as arguments
so you should do
total = int(raw_input(..))
Point is, this is not always secure. Exceptions are very likely to be thrown, so you might want to use a try block; but for the time being, I think it's okay (I'm assuming you're just learning Python).
Another thing, which is rather important:
Look at the exception! If you'd read it, you would have known exactly what the problem was.
Beside the raw_input() problem pointed out by the others, #Mark Ransom's comment is important: the sum of dice value eventually follows normal distribution. See: http://en.wikipedia.org/wiki/Dice#Probability
Your:
if rollinputcap =="Y":
print random.randint(number_of_dice,total)
should be changed to
if rollinputcap =="Y":
sum_dice=[]
for i in range(number_of_dice):
sum_dice.append(random.randint(1, sides_of_dice))
print sum(sum_dice)