Can't print a number despite using str/int - python-3.x

I'm a noob trying to learn python 3 and I'm trying to include the half_age as a string without using directly writing the number 9 as a string but I couldn't figure it out.
I've tried:
print = str(18//2)
print = int(18//2)
print = float(18/2)
my_age = 18
half_age = (18//2)
name = "Kenny!"
greeting = "Kia Ora, "
print(greeting + name)
print("Your age is " + my_age + "and half your age is " + str(half_age ))
print("Your age is " + my_age + "and half your age is " + str(half_age ))
TypeError: can only concatenate str (not "int") to str

Try formatting all of your numbers with str ie.
my_age = 18
half_age = (18//2)
name = "Kenny!"
greeting = "Kia Ora, "
print(greeting + name)
print("Your age is " + str(my_age) + " and half your age is " + str(half_age))

Just use modern f-strings:
my_age = 18
half_age = (18//2)
name = "Kenny"
greeting = "Kia Ora"
print(f'{greeting}, {name}!')
print(f"Your age is {my_age} and half your age is {half_age}")
or
print(f"Your age is {my_age} and half your age is {my_age/2}")

Related

What is wrong with this tiny python program?

I'm completely new to python and have been trying to experiment with things that I've been learning as I learn them. One of these things is using if statements. As you can see, when you run the program and input the correct answer which is 11 you will get a "yes!" message. Or else you will get a message that tells you the number you input plus 33 is not 44. However, when I input the correct answer (11) it still tells me that 11 + 33 is not 44. Curious why this is & if I am missing something?
num_in = input("what + 33 is 44?: ")
set_num = str(22 + 11)
if(num_in + set_num == str(44)):
print(" Yes!")
else:
print(num_in + " + " + set_num + " is not 44.")
+ operator has different meanings for different types. For str it is concatenation, for int add operation in math:
>>> 11 + 22
33
>>> "11" + "22"
'1122'
In your particular case try to use int everywhere where integer type variable is needed, and format output if necessary:
num_in = int(input("what + 33 is 44?: "))
set_num = 22 + 11
if num_in + set_num == 44:
print("Yes!")
else:
print("{} + {} is not 44.".format(num_in, set_num))
Here, num_in and set_num are strings, and string concatenation doesn't follow math. Here, let num_in is "11" and set_num is "33" then set_num+num_in is "3311" which is not str(44), just take int values
Edited code:
num_in = int(input("what + 33 is 44?: "))
set_num = 33
if(num_in + set_num == 44):
print(" Yes!")
else:
print(f"{num_in} + {set_num} is not 44.")

Can someone try to make this a bit better so I can see my mistakes or to make it more efficient I'm a beginner in python

It's a quiz for covid-19, if you have any symptoms it first asks for your name, then asks if you have any symptoms like a cough or a headache. If you say no, it asks more questions and if you say yes it says you have covid-19. It's in the newest python
name = input("your name is ")
bad = input("hi " + name + " do you have a cough ")
if bad == "no":
bad2 = input("hello " + name + " do you have a sore throat ")
if bad2 == "no":
bad3 = input("hi " + name + " do you have a headache ")
if bad3 == "no":
bad4 = input("hi " + name + " do you have any pain ")
if bad4 == "no":
bad5 = input("hi " + name + " do you fell tired ")
if bad5 == "no":
print("hi " + name + " you don't have covid")
if bad == "yes" or bad2 == "yes" or bad3 == "yes" or bad4 == "yes" or bad5 == "yes":
print("sorry " + name + " you have covid-19 ..... and here a ticket of 1,000")
Exactly the same thing using a bit more tidy and readable approach.
"Readable code is maintainable code."
name = input("Your name: ")
# array containing questions
q = [
f"Hi, {name} do you have a cough? ",
"Do you have a soar throat? ",
"Do you have a headache? ",
"Do you feel tired? ",]
# user promt
for i in q:
response = input(i)
if response == "yes":
print(f"-> Sorry {name}, you have covid-19 ....." +
"and here's a ticket of 1,000.")
break
else:
print("-> You don't have Covid.")

Expression was too complex to be solved in reasonable time;

I have just upgraded from Xcode 8.3 to Xcode 9.4 and it kept indexing until it crashed, then it output an error.
Swift - Expression was too complex to be solved in reasonable time;
consider breaking up the expression into distinct sub-expressions
Is this a bug in Xcode 9 and Swift 4.1?
let fromString = convenience.getTimeAsString(timeStamp: timeStampDateAndTime, timeFormat: "HH:mm")
let toString = convenience.getTimeAsString(timeStamp: toTimeStamp, timeFormat: "HH:mm")
var cellData = "Booking: " + booking.BookingNumber + "\n" + "Area: " + booking.Locality + "\n" + "Postcode: " + booking.PostCode + "\n" + "Time: " + fromString + " - " + toString
How I fixed it?
var cellData = " \("Booking: ") \(booking.BookingNumber) \("\n") \("Area: ") \(booking.Locality) \("\n") \("Postcode: ") \(booking.PostCode) \("\n") \("Time: ") \(fromString) \(" - ") \(toString) "

Replace series of Unicode characters / Python / Twitter

I am pulling text from a tweet using the Twitter API and Python 3.3 and I'm running into the part of the tweet where the tweeter put three symbols in the tweet. They are shown below.
The two flags and the thumbs up seem to be causing the problem. The following is the plain text tweet.
RT #John_Hunt07: Just voted for #marcorubio is Florida! I am ready for a New American Century!! #FLPrimary \ud83c\uddfa\ud83c\uddf8\ud83c\uddfa\ud83c\uddf8\ud83d\udc4d
The following is the code I'm using.
import json
import mysql.connector
import sys
from datetime import datetime
from MySQLCL import MySQLCL
class Functions(object):
"""This is a class for Python functions"""
#staticmethod
def Clean(string):
temp = str(string)
temp = temp.replace("'", "").replace("(", "").replace(")", "").replace(",", "").strip()
return temp
#staticmethod
def ParseTweet(string):
for x in range(0, len(string)):
tweetid = string[x]["id_str"]
tweetcreated = string[x]["created_at"]
tweettext = string[x]["text"]
tweetsource = string[x]["source"]
tweetsource = tweetsource
truncated = string[x]["truncated"]
inreplytostatusid = string[x]["in_reply_to_status_id"]
inreplytouserid = string[x]["in_reply_to_user_id"]
inreplytoscreenname = string[x]["in_reply_to_screen_name"]
geo = string[x]["geo"]
coordinates = string[x]["coordinates"]
place = string[x]["place"]
contributors = string[x]["contributors"]
isquotestatus = string[x]["is_quote_status"]
retweetcount = string[x]["retweet_count"]
favoritecount = string[x]["favorite_count"]
favorited = string[x]["favorited"]
retweeted = string[x]["retweeted"]
if "possibly_sensitive" in string[x]:
possiblysensitive = string[x]["possibly_sensitive"]
else:
possiblysensitive = ""
language = string[x]["lang"]
#print(possiblysensitive)
print(Functions.UnicodeFilter(tweettext))
#print(inreplytouserid)
#print("INSERT INTO tweet(ExTweetID, TweetText, Truncated, InReplyToStatusID, InReplyToUserID, InReplyToScreenName, IsQuoteStatus, RetweetCount, FavoriteCount, Favorited, Retweeted, Language, TweetDate, TweetSource, PossiblySensitive) VALUES (" + str(tweetid) + ", '" + Functions.UnicodeFilter(tweettext) + "', " + str(truncated) + ", " + Functions.CheckNull(inreplytostatusid) + ", " + Functions.CheckNull(inreplytouserid) + ", '" + Functions.CheckNull(inreplytoscreenname) + "', " + str(isquotestatus) + ", " + str(retweetcount) + ", " + str(favoritecount) + ", " + str(favorited) + ", " + str(retweeted) + ", '" + str(language) + "', '" + Functions.ToSQL(tweetcreated) + "', '" + Functions.ToSQL(tweetsource) + "', " + str(possiblysensitive) + ")")
#MySQLCL.Set("INSERT INTO tweet(ExTweetID, TweetText, Truncated, InReplyToStatusID, InReplyToUserID, InReplyToScreenName, IsQuoteStatus, RetweetCount, FavoriteCount, Favorited, Retweeted, Language, TweetDate, TweetSource, PossiblySensitive) VALUES (" + str(tweetid) + ", '" + tweettext + "', " + str(truncated) + ", " + Functions.CheckNullNum(inreplytostatusid) + ", " + Functions.CheckNullNum(inreplytouserid) + ", '" + Functions.CheckNull(inreplytoscreenname) + "', " + str(isquotestatus) + ", " + str(retweetcount) + ", " + str(favoritecount) + ", " + str(favorited) + ", " + str(retweeted) + ", '" + language + "', '" + str(Functions.FormatDate(tweetcreated)) + "', '" + str(Functions.UnicodeFilter(tweetsource)) + "', " + str(possiblysensitive) + ")")
#staticmethod
def ToBool(variable):
if variable.lower() == 'true':
return True
elif variable.lower() == 'false':
return False
#staticmethod
def CheckNullNum(var):
if var == None:
return "0"
else:
return str(var)
#staticmethod
def CheckNull(var):
if var == None:
return ""
else:
return var
#staticmethod
def ToSQL(var):
temp = var
temp = temp.replace("'", "")
return str(temp)
#staticmethod
def UnicodeFilter(var):
temp = var
temp = temp.replace(chr(0x2019), "")
temp = temp.replace(chr(0x003c), "(lessthan)")
temp = temp.replace(chr(0x003e), "(greaterthan)")
temp = temp.replace(chr(0xd83c), "")
temp = temp.replace(chr(0xddfa), "")
temp = temp.replace(chr(0xddf8), "")
temp = temp.replace(chr(0xd83d), "")
temp = temp.replace(chr(0xdc4d), "")
temp = Functions.ToSQL(temp)
return temp
#staticmethod
def FormatDate(var):
temp = var
dt = datetime.strptime(temp, "%a %b %d %H:%M:%S %z %Y")
retdt = str(dt.year) + "-" + str(dt.month) + "-" + str(dt.day) + "T" + str(dt.hour) + ":" + str(dt.minute) + ":" + str(dt.second)
return retdt
As you can see, I've been using the function UnicodeFilter in order to try to filter out the unicode characters in hex. The function works when dealing with single unicode characters, but when encountering multiple unicode characters placed together, this method fails and gives the following error:
'charmap' codec can't encode characters in position 107-111: character maps to 'undefined'
Do any of you have any ideas about how to get past this problem?
UPDATE: I have tried Andrew Godbehere's solution and I was still running into the same issues. However, I decided to see if there were any specific characters that were causing a problem, so I decided to print the characters to the console character by character. That gave me the error as follows:
'charmap' codec can't encode character '\U0001f1fa' in position 0: character maps to 'undefined'
Upon seeing this, I added this to the UnicodeFilter function and continued testing. I have run into multiple errors of the same kind while printing the tweets character by character. However, I don't want to have to keep making these exceptions. For example, see the revised UnicodeFilter function:
#staticmethod
def UnicodeFilter(var):
temp = var
temp = temp.encode(errors='ignore').decode('utf-8')
temp = temp.replace(chr(0x2019), "")
temp = temp.replace(chr(0x003c), "(lessthan)")
temp = temp.replace(chr(0x003e), "(greaterthan)")
temp = temp.replace(chr(0xd83c), "")
temp = temp.replace(chr(0xddfa), "")
temp = temp.replace(chr(0xddf8), "")
temp = temp.replace(chr(0xd83d), "")
temp = temp.replace(chr(0xdc4d), "")
temp = temp.replace(chr(0x2026), "")
temp = temp.replace(u"\U0001F1FA", "")
temp = temp.replace(u"\U0001F1F8", "")
temp = temp.replace(u"\U0001F44D", "")
temp = temp.replace(u"\U00014F18", "")
temp = temp.replace(u"\U0001F418", "")
temp = temp.replace(u"\U0001F918", "")
temp = temp.replace(u"\U0001F3FD", "")
temp = temp.replace(u"\U0001F195", "")
temp = Functions.ToSQL(temp)
return str(temp)
I don't want to have to add a new line for every character that causes a problem. Through this method, I have been able to pass multiple tweets, but this issue resurfaces with every tweet that contains different symbols. Is there not a solution that will filter out all these characters? Is it possible to filter out all characters not in the utf-8 character set?
Try the built-in unicode encode/decode error handling functionality: str.encode(errors='ignore')
For example:
problem_string = """\
RT #John_Hunt07: Just voted for #marcorubio is Florida! I am ready for a New American Century!! #FLPrimary \ud83c\uddfa\ud83c\uddf8\ud83c\uddfa\ud83c\uddf8\ud83d\udc4d
"""
print(problem_string.encode(errors='ignore').decode('utf-8'))
Ignoring errors removes problematic characters.
> RT #John_Hunt07: Just voted for #marcorubio is Florida! I am ready for a New American Century!! #FLPrimary
Other error handling options may be of interest.
xmlcharrefreplace for instance would yield:
> RT #John_Hunt07: Just voted for #marcorubio is Florida! I am ready for a New American Century!! #FLPrimary πŸ‡ΊπŸ‡ΈπŸ‡ΊπŸ‡ΈπŸ‘
If you require custom filtering as implied by your UnicodeFilter function, see Python documentation on registering an error handler.
Python provides a useful stacktrace so you can tell where errors are coming from.
Using it, you will have found that your print is causing the exception.
print() is failing because you're running Python from the Windows console, which, by default only, supports your local 8bit charmap. You can add support with: https://github.com/Drekin/win-unicode-console
You can also just write your data straight to a text file. Open the file with:
open('output.txt', 'w', encoding='utf-8')
Found the answer. The issue was that there was a range of characters in the tweets that were causing problems. Once I found the correct Unicode range for the characters, I implemented the for loop to replace any occurrence of any Unicode character within that range. After implementing that, I was able to pull thousands of tweets without any formatting or MySQL errors at all.
#staticmethod
def UnicodeFilter(var):
temp = var
temp = temp.replace(chr(0x2019), "'")
temp = temp.replace(chr(0x2026), "")
for x in range(127381, 129305):
temp = temp.replace(chr(x), "")
temp = MySQLCL.ToSQL(temp)
return str(temp)

subset of a database using SUM

rs = s.executeQuery("SELECT Class1_predicted, Class2_predicted, Class3_predicted, Class_predicted"
+ SUM(PROFIT_LOSS) AS "Total Profit",
+ "FROM xxxxxx "
+ "WHERE CLASS1_PREDICTED = curr_class1_predicted, CLASS2_PREDICTED = curr_class2_predicted, CLASS3_PREDICTED = curr_class3_predicted, CLASS_PREDICTED = curr_class_predicted,"
+ "PROFIT_LOSS >= 0,"
+ "GROUP BY Class1_predicted, Class2_predicted, Class3_predicted,Class_predicted");
rs.next();
int recordCount = rs.getInt(1);
myConsole.getOut().println("Number of records in subset of table xxxxx where P/L >= 0: " + recordCount);
I am getting an error on the AS in the second line ?
Not sure how to correct ?
Bob M
You should put the whole query in a String.
It seems like here you are not actually quoting the expression:
+ SUM(PROFIT_LOSS) AS "Total Profit",
It should be something like this:
+ "SUM(PROFIT_LOSS) AS Total_Profit,"

Resources