Temperature converter in python - python

I went through a couple of converters in python but they entered the int value seperately. If the input is 100C i want the output in F and if its 50F i want it in C. I'm new to python and tried some simple lines but the error says its impossible to concatenate str and int.
a = raw_input(" enter here")
char = "f"
char2 = "c"
for s in a:
if s in char:
b=(5*(a-32))/9
print(b,"c")
continue
elif s in char2:
d = (9*a/5)+32
print(d,"f")
continue

Since the user will enter a number followed by the unit, you need to only check if the last character of the string to understand which conversion to do.
You can use slicing, here is an example:
>>> a = '45F'
>>> a[-1]
'F'
>>> a[:-1]
'45'
Of course '45' is a string not a number, converting it to a number with int() will allow you do math on it.
Putting all that together, we have something like this:
a = raw_input('Enter here: ')
number = int(a[:-1])
letter = a[-1].lower()
if letter == 'f':
print('{} in C is {}'.format(a, 5*(number-32)/9))
if letter == 'c':
print('{} in F is {}'.format(a, 9*(number/5)*32))

Related

I wished to check if an input is in the string and then print the output

I intended to let the program check if the input matches with any character in a str and then print out the result, the player input and the underscores in the correct places. This is my test code so far:
astring = "apple"
bstring = "_ " * 5
print(bstring)
my_input = input("enter a letter")
for i, n in enumerate(astring):
if my_input == i:
bstring[n] = my_input
else:
i = i + 1
print(bstring)
However, only the underscores are being printed out. Can anyone help me?
In your loop, you should be checking to see if the letter at your current index of your string is the same as the letter at the current index of your input string, to do this you can use:
if i < len(my_input) and my_input[i] == n:
Also, strings in Python are immutable, and so you can't change them via index. Instead, use an array of _, so that you can change what is at a particular index. Then, at the end, join each element in your list by a space.
Lastly, there is no need to increment i, as this is done for you by your for loop:
astring='apple'
bstring=['_']*len(astring)
print(bstring)
my_input = input('enter a letter')
for i,n in enumerate(astring):
if i < len(my_input) and my_input[i] == n:
bstring[i] = n
print(' '.join(bstring))
for i,n in enumerate(astring):
'i' is the index, 'n' is the character. You have it the other way around in 'if'.
hope it will help you
astring='apple'
bstring=["_" for i in range(len(astring))]
print(bstring)
my_input=input('enter a letter')
for i,n in enumerate(astring):
if my_input==n:
bstring[i]=my_input
else:
i=i+1
print(*bstring)

The python program does not work

I need help with my python program. I'm doing a calculator.
The numbers must be formed, but for some reason they do not add up.
It seems that I did everything right, but the program does not work.
Please help me. Picture
Code:
a = input('Enter number A \n');
d = input('Enter sign operations \n')
b = input('Enter number B \n')
c = a + b
if str(d) == "+":
int(c) == "a + b"
print('Answer: ' + c)
Please don't post screenshots. Copy and paste text and use the {} CODE markdown.
What data type is returned by input()? It's always a string. It doesn't matter what you type.
Where is the variable c actually calculated in this program? Line 4.
What types of data are used to compute c? Two strings.
What happens when you use the "+" operation on two strings instead of two numbers? Try running your program and when it prompts you to "enter number A", type "Joe". When it prompts you to "enter number B", type "Bob". What does your program do?
You need to create numerical objects from each of the strings you entered if you want to do arithmetic.
I think that you tried what you thought would do that on line 7. It doesn't work though. "==" is used to test for equality, not to assign a value. The single "=" is used to bind values to variable names. You do that correctly on lines 1 through 4. Notice that the plain variable name is always by itself on the left of the "=" sign. You do all the fancy stuff on the right side of the "=".
You can actually delete lines 6 and 7 and the output of the program will not change.
a and b are strings.
a + b concatenates strings a and b.
You need to convert the strings to int:
c = int(a) + int(b)
And remove the lines:
if str(d) == "+":
int(c) == "a + b"
Here is the complete code, that should to what you want:
a = input('Enter number A \n');
operation = input('Enter sign operations \n')
b = input('Enter number B \n')
c = a + b
if operation == "+":
c= int(a) + int(b)
print('Answer:', c)
Since it looks like you also want to enter an operation sign you might also try eval
a = input('Enter number A \n');
d = raw_input('Enter sign operations \n')
b = input('Enter number B \n')
eval_string = str(a) + d + str(b)
print ( eval(eval_string) )
You should know input accepts only integers and raw_input even if given an integer saves it as a string so it saves only strings.

checking if string only contains certain letters in Python

i'm trying to write a program that completes the MU game
https://en.wikipedia.org/wiki/MU_puzzle
basically i'm stuck with ensuring that the user input contains ONLY M, U and I characters.
i've written
alphabet = ('abcdefghijklmnopqrstuvwxyz')
string = input("Enter a combination of M, U and I: ")
if "M" and "U" and "I" in string:
print("This is correct")
else:
print("This is invalid")
i only just realised this doesnt work because its not exclusive to just M U and I. can anyone give me a hand?
if all(c in "MIU" for c in string):
Checks to see if every character of the string is one of M, I, or U.
Note that this accepts an empty string, since every character of it is either an M, I, or a U, there just aren't any characters in "every character." If you require that the string actually contain text, try:
if string and all(c in "MIU" for c in string):
If you're a fan of regex you can do this, to remove any characters that aren't m, u, or i
import re
starting = "jksahdjkamdhuiadhuiqsad"
fixedString = re.sub(r"[^mui]", "" , starting)
print(fixedString)
#output: muiui
A simple program that achieve your goal with primitive structures:
valid = "IMU"
chaine = input ('enter a combination of letters among ' + valid + ' : ')
test=True
for caracter in chaine:
if caracter not in valid:
test = False
if test :
print ('This is correct')
else:
print('This is not valid')

Convert a number into its respective letter in the alphabet - Python 2.7

I am currently working on a python project to take a string of text, encrypt the text by adding a keyword to it and then outputting the result. I currently have all the features of this program operational except converting the numerical value back into text.
For example, the raw text will be converted into a numerical value, for instance [a, b, c] will become [1, 2, 3].
Currently I have no ideas of how to correct this issue and would welcome any help, my current code is as follows:
def encryption():
print("You have chosen Encryption")
outputkeyword = []
output = []
input = raw_input('Enter Text: ')
input = input.lower()
for character in input:
number = ord(character) - 96
output.append(number)
input = raw_input('Enter Keyword: ')
input = input.lower()
for characterkeyword in input:
numberkeyword = ord(characterkeyword) - 96
outputkeyword.append(numberkeyword)
first = output
second = outputkeyword
print("The following is for debugging only")
print output
print outputkeyword
outputfinal = [x + y for x, y in zip(first, second)]
print outputfinal
def decryption():
print("You have chosen Decryption")
outputkeyword = []
output = []
input = raw_input('Enter Text: ')
input = input.lower()
for character in input:
number = ord(character) - 96
output.append(number)
input = raw_input('Enter Keyword: ')
input = input.lower()
for characterkeyword in input:
numberkeyword = ord(characterkeyword) - 96
outputkeyword.append(numberkeyword)
first = output
second = outputkeyword
print("The following is for debuging only")
print output
print outputkeyword
outputfinal = [y - x for x, y in zip(second, first)]
print outputfinal
mode = raw_input("Encrypt 'e' or Decrypt 'd' ")
if mode == "e":
encryption()
elif mode == "d":
decryption()
else:
print("Enter a valid option")
mode = raw_input("Encrypt 'e' or Decrypt 'd' ")
if mode == "e":
encryption()
elif mode == "d":
decryption()
Although Your Question is not quite clear I wrote a script which do encryption using Dictionary
plaintext = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') #Alphabet String for Input
Etext = list('1A2B3C4D5E6F7G8H90IJKLMNOP') """Here is string combination of numbers and alphabets you can replace it with any kinda format and your dictionary will be build with respect to the alphabet sting"""
def messageEnc(text,plain, encryp):
dictionary = dict(zip(plain, encryp))
newmessage = ''
for char in text:
try:
newmessage = newmessage + dictionary[char.upper()]
except:
newmessage += ''
print(text,'has been encryptd to:',newmessage)
def messageDec(text,encryp, plain):
dictionary = dict(zip(encryp,plain))
newmessage = ''
for char in text:
try:
newmessage = newmessage + dictionary[char.upper()]
except:
newmessage += ''
print(text,'has been Decrypted to:',newmessage)
while True:
print("""
Simple Dictionary Encryption :
Press 1 to Encrypt
Press 2 to Decrypt
""")
try:
choose = int(input())
except:
print("Press Either 1 or 2")
continue
if choose == 1:
text = str(input("enter something: "))
messageEnc(text,plaintext,Etext)
continue
else:
text = str(input("enter something: "))
messageDec(text,Etext,plaintext)
Suppose you've got a list of numbers like a = [1, 2, 3] and an alphabet: alpha = "abcdef". Then you convert this as follows:
def NumToStr(numbers, alpha):
ret = ""
for num in numbers:
try:
ret += alpha[num-1]
except:
# handle error
pass
return ret
Going by your question , you want to convert number back to text.
You can have two list declared for both the number and alphabet, such as:
num=[1,2,3....26]
alpa=['a','b','c'....'z']
and after that find the index/position from the num list and find the alphabet for that index in alpa list.
A couple of things. The first is to convert the coded values back to characters you can use the chr(i) command. Just remember to ad the 96 back on.
for code in outputfinal:
print chr(code + 96),
I tried 'aaa' as my plaintext and 'bbb' as my keyword and this printed 'ccc' which is what I think you are trying to do.
Another thing. The zip command iterates over two lists but (in my playing) only until one of the lists runs out of members. If your plaintext is 10 characters and your keyword is only 5 then only the first 5 characters of your plaintext get encrypted. You will need to expand or inflate your key to the length of your plaintext message. I played with something like this:
plaintext = ['h','e','l','l','o',' ','w','o','r','l','d']
keyword = ['f','r','e','d']
index = len(keyword) # point to the end of the key word
keyLength = len(keyword)
while index < len(plaintext): # while there are still letters in the plain text
keyword.append(keyword[index - keyLength]) # expand the key
index += 1
print keyword
for a,b in zip(plaintext, keyword):
print a, b
I hope this helps. Please let me know if I have misunderstood.

How to use input string as variable call in python?

I am a beginner python learner. I was wondering if it was possible to create a basic massage encrypting system without using any modules. I want my programm to check and use variable name that is in string.
let's say,
a = 'l'
b = '5'
c = 'o'
x = input("Enter your massage: ")
print(x, 'THE_USER INPUT matching the variable name and values')
I know I can do this with while or if, but it would take forever. Also, how do you separate each string letters before you match the variable.
I am using python 3. Thanks :)
I have no idea if this is what you are trying to do, but here goes:
a = 'l'
b = '5'
c = 'o'
x = input("Enter your message: ")
values = [globals().get(var, '') for var in list(x)]
print "".join(values)
EXAMPLE
Enter your message: abc
l5o
A more appropriate way to do this would likely be:
replacements = { 'a': 'l', 'b': '5', 'c': 'o' }
x = input("Enter your message: ")
print "".join([replacements.get(val, "") for val in x])
use string.translate this is a much more correct way to do what it sounds like you want
from string import maketrans
in_tab = "abcdefghijklmnopqrstuvwxyz "
out_tab = "5QR&*(=-;Wwz%$^##!yY~:123xq"
t = maketrans(in_tab,out_tab)
print ("Hello World".translate(t))
In case you meant substituting every occurrence of a given character by another one, have a look at the str.translate function.
You could extend your example code as follows:
import string
in = input("Enter your message: ")
mapping = string.maketrans('abc', '15o')
out = in.translate(mapping)
print(out)
Every a is substituted by a 1, every b by 5, every c by o.

Categories