Python - How to take user input and use that in function - python-2.7

Please help me why on executing the below program an error coming on m variable
x=int(input("Enter first number"))
y=int(input("Enter second number"))
def multiplication():
m=x*y
print("Multiplication result"m)

In Python 2, you should accept user inputs with raw_input(): Check this.
x=int(raw_input("Enter first number"))
y=int(raw_input("Enter second number"))
Please follow a proper indentation plan with python:
Also, you did not accept the variables while defining your function, and learn how to use print:
def multiplication(x, y):
m = x * y
print "Multiplication result: %d" % m
Finally, to call this function, use:
multiplication(x, y)

x=int(raw_input("enter first number"))
os=raw_input("Enter the sign of what you wanna do +,-,/,*")
y=int(raw_input("enter second number"))

You can also do like this if you want to keep it in functions.
def input_function():
x = int(raw_input("Enter first number"))
y = int(raw_input("Enter second number"))
return x,y
def multiplication():
x,y = input_function()
m = x * y
print "Multiplication result", m
multiplication()
Or like this, in one function. But it doesn't look so pretty.
def multiplication(x,y):
m = x * y
print "Multiplication result",m
multiplication(int(raw_input('Enter first number')),int(raw_input('Enter second number')))

def r():
v = int(input("voltage: "))
i = int(input("current: "))
resistance = v*i
return(resistance,'ohms')

Related

How To Make raw_input Not A String In python

I want to make this program do the summation of something with their input. My code thus far
def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
eqn = lambda n: raw_input("Equation?: ")
sum = 0
for i in range(start , end + 1):
sum += eqn(i)
return sum
print summation() # start will be 1, end will be 5 , equation will be n + 1. Should print 20
I get the error that I can't add an integer and a string together so is there any way to make the raw_input for equation not a string. Like instead of it being 'n + 1', I want it to be n + 1.
You could use input instead of raw_input, but this isn't really a good idea, since every time eqn is called it will call a input and prompt you for the equation.
A better method is to store the equation beforehand (using raw_input), and then use eval in the lambda function. Something like:
def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
fx = raw_input("Equation: ")
eqn = lambda n: eval(fx)
sum = 0
for i in range(start , end + 1):
sum += eqn(i)
return sum
print summation()
Don't you need to surround your raw_input in your eqn variable with an int()?
I use python 3, but that should fix your problems.

count index in a list to x number python

I have a list with like this that goes from 0 to 1000 .
x = ['0_1','0_2','0_3' ..., '1000_1','1000_2','1000_3']
I need it to count every time the char in index changes like I show below.
list_leng = len(x)
for i in range(0, list_leng):
y = x[i]
z = y[0]
print this should iterate through all the list and only print when the z number changes ' # how should I make it print '
If I understood your question well, the answer must be something like this;
comparisonText = ""
for each in x:
preNumber = each.split('_')[0]
if comparisonText != preNumber:
print preNumber, 'is different than previous.'
comparisonText = preNumber #change the comparisonText

Convert from decimal to binary - python

I'm having an issue with this piece of code I wrote. I'm trying to convert an integer input and print an output with its equivalent in binary base. For example for 5 it should drop an output of '101' however it just prints '10' like if it doesn't take into account the last digit. Please any comments would be greatly appreciated
T = raw_input()
for i in range(0, int(T)):
n = raw_input()
dec_num = int(n)
cnv_bin = ''
while dec_num//2 > 0:
if dec_num%2 == 0:
cnv_bin += '0'
else:
cnv_bin += '1'
dec_num = dec_num//2
print cnv_bin[::-1]
while dec_num//2 > 0:
should be:
while dec_num > 0:
The first time through the loop, 5//2==2, so it continues.
The second time through the loop, 2//2==1, so it continues.
The third time, 1//2==0 and the loop quits without handling the last bit.
Also, you can just do the following to display a number in binary:
print format(dec_num,'b')
Format string version:
print '{0} decimal is {0:b} binary.'.format(5)
Why not use the build-in function bin()?
eg:
bin(5)
output
0b101
If you don't want the prefix(0b), you can exclude it.
bin(5)[2:]
hope to be helpful!
import math
def roundup(n):
return math.ceil(n)
D = eval(input("Enter The Decimal Value: "))
n = roundup(math.log2(D+1))-1
bi = 0
di = D
qi = 0
i = n
print("Binary Value:",end = " ")
while(i>=0):
qi = math.trunc(di/2**i)
bi = qi
print(bi,end = "")
di = di - bi*(2**i)
i = i-1

How to avoid duplicate printing of random choiced names from list ( Python)

This program prints duplicate names generated from list please help me get rid of it I added a operator fr it but it's not working
#Subscriber Selector
import random
print "Welcome to Subscriber Picker"
sub_list = ["Ali Abbas","Ansar Abbasi","Hasan Abidi","Saadia Afzaal","Iqbal Ahmad","Iftikhar Ahmad","Khaled Ahmed","Ahmed Tamim","Maulana Mahboob Alam","Malik Barkat Ali"]
def add_list():
input_1 = int(raw_input("How many new users do you want to add? "))
for z in range (0,input_1):
sub_list.append(raw_input ("Enter Name" +" "+ str(z+1) + ":"))
return
add_list()
def generator():
input_2=int(raw_input("How many subscribers to generate? "))
print "-----"
index=0
temp_list = []
ran_name = random.randint(0, len(sub_list)-1)
temp_list.append(sub_list[ran_name])
while len(temp_list) < input_2:
ran_name=random.randint(0,len(sub_list)-1)
temp_list.append(sub_list[ran_name])
if(temp_list[index] == temp_list[index+1]):
temp_list.pop(index)
else:
index = index + 1
for x in temp_list:
print x
print"-----"
return
generator()
Here you go:
temp_list = random.sample( sub_list, input_2 )

exceptions.TypeError unhashable type list. How do I fix this?

import time
dictionary = {}
def add():
x = int(raw_input("Please enter the hour of your event in 24 hour time"))
y = raw_input("Please enter the name of your activity")
dictionary[x] = y
print (dictionary[x] + " was added succesfully")
main()
def view():
theTime = time.localtime()
print "the hour is: ", theTime.tm_hour
theHour = theTime.tm_hour
x = dictionary.keys()
if x in dictionary:
print "The current event is", x
print "Your full shcedule for today is: ", dictionary
main()
def remove():
print dictionary
x = int(raw_input("which time slot would you like to clear?"))
z = dictionary.pop(x)
print z + " was removed"
main()
table = {
1 : add,
2 : view,
3 : remove
}
def run(x):
table[x]()
def main():
x = int(raw_input("Please select and option! \n\n1. Add an event \
\n2. View an event \n3. Remove an event \n4. Exit"))
if x == 4:
exit()
run(x)
main()
Alright, So the only thing that is not working for me is the view function. After I add an event, and then I try to view it I get an unhashable type: "list" error. Why is this and how can I fix it? Thank you
You are assigning x = dictionary.keys(), which means that x is a list (of all the keys in the dictionary). You then do if x in dictionary, which asks if the key x is a key in the dictionary. But a list is mutable, so it's not allowed to be a key.
Did you actually mean to say if theHour in dictionary?