I'm new in Python and in Telegram bot, I hope you can help me understand this with a simple example.
What I need is to define a method that returns me a string to complete a url.
In Python what I need is:
user = input("Insert a username to see the graph:")
graphUrl = "https://www.graphsss123.com/ser/graph/" + user + "-123.jpg"
print(graphUrl)
how could I get the same result using Telepot?
Thank you
There is no exclusive function for receiving messages in telepot(I guess!!),so you will have to maintain the states (here i have done that using step).The snippet below is an example for adding 2 numbers given by user through telegram
ref:https://github.com/nickoala/telepot/issues/209
global step, no1
if step == 1:
if msg['text'] == 'add':
bot.sendMessage(chat_id, "input no1")
step = 2
else:
bot.sendMessage(chat_id, "please provide no")
elif step == 2:
no1 = msg['text']
bot.sendMessage(chat_id, "input no2")
step = 3
elif step == 3:
no2 = msg['text']
no3=no1+no2
bot.sendMessage(chat_id,no3)
step = 1
Related
I want to write a program in python having 7-8 different cases.
like- Case 1, Name, Case 2- DOB, Case 3- City... etc
Also, I want to take the input from user and store in mysql.
How can I have that in Python? Any ideas?
I have my code-
Kindly ignore indentations-
levels = 1
i= 1
while (i<=5):
if (levels==i and (re.search(r'\bhello\b', incoming_msg)) or re.search(r'\bhi\b', incoming_msg)):
# incoming_msg=='hello' or incoming_msg=='hi' :
reply = ("Kindly provide your full name")
print(levels)
msg.body(reply)
return str(resp)
levels=levels +1
i+=1
if (levels==i and incoming_msg.isdigit()==False):
print(levels)
reply = ("Thank you for providing your name.\n\n"
"Kindly provide your DOB:\n")
msg.body(reply)
return str(resp)
levels = 3
if((levels==i) and and incoming_msg.isdigit()==False):
reply =('Kindly provide your DOB.")
msg.body(reply)
return str(resp)
i =4
levels = 4
if((levels==i) and incoming_msg.isdigit()==True)):
reply =("Thanks for the info")
msg.body(reply)
return str(resp)
i = 5
levels = 5
else:
# prompt user to check his/her query
reply = "Sorry, but I didn't understand your query. Kindly select the correct option"
msg.body(reply)
return str(resp)
This is how you do cases.
case = input("what is your case? ")
if case == "nominative":
print("mensa")
elif case == "vocative":
print("mensa")
elif case == "accusative":
print("mensam")
elif case == "genitive":
print("mensae")
elif case == "dative":
print("mensae")
elif case == "ablative":
print("mensa")
else:
print("never heard of it")
I am self-learning Python (no prior programming experience) and I am trying this question:
ask the user to input as many bank account numbers as they’d like, and store them within a list initially. once the user is done entering information, convert the list to a frozenset and print it out.
This is my code:
# create global variables
b_accounts = []
fzb_accounts = frozenset()
# Create add account function
def addAccount(account):
b_accounts.append(account)
print('Account number: {} has been added'.format(account))
return b_accounts
# create covert from a list to a frozenset function
def convertFz():
if b_accounts:
globals()['fzb_accounts'] = frozenset(b_accounts)
return fzb_accounts
else:
print('List of account does not exist!')
# create show account function
def showAccount():
convertFz()
if fzb_accounts:
#print('Here your enique entered accounts:{}'.format(fzb_accounts))
for acc in fzb_accounts:
print(acc)
else:
print('No account!')
# create main function
def main():
done = False
while not done:
ans = input('Please select add/show/quit account: ').lower()
if ans == 'add':
account = input('Enter account number: ')
addAccount(account)
elif ans =='show':
showAccount()
elif ans =='quit':
done = True
print('Bye!')
else:
print('Invalid option')
main()
I want to add the following account numbers:
1234
12345
1234
the output should be:
1234
12345
Thank all, code updated and work as expected.
I am trying to write a basic Twitter scraper in Python and while I have it so that it can scrape for hard coded terms, I'm trying to set it to take the search term from user input.
While my if/else statement accepts input when asked, it then fails to run stating that rawinput is not defined. The rawinput is within the if statement I've included my code below
I should mention I'm fairly new to Python.
I've tried removing the rawinput from the if/else and kept it separate but the same issue happens.
userinp = input("Select search type. 1 = tweets. 2 = people")
if userinp == 1:
entry = rawinput
query = u'q='
elif userinp == 2:
entry = rawinput
query = u'f=users&vertical=default&q='
searchurl = baseurl + query + entry
The expected result is that the user selects option 1 or 2 then is asked to enter their search term.
Results are:
Select search type. 1 = tweets. 2 = people1
Traceback (most recent call last):
File "Scrape.py", line 22, in <module>
userentry = rawinput('enter search term')
NameError: name 'rawinput' is not defined
Thanks in advance for any help given.
Use input() instead and don't forget the parentheses!
Additionally, input() converts your input to a string, so your if condition will never be met if it uses integers. Consider replacing with if userinp == '1': and elif userinp == '2':.
It should be raw_input() not rawinput. so your code should be like this...
userinp = input("Select search type. 1 = tweets. 2 = people")
if userinp == 1:
entry = raw_input()
query = u'q='
elif userinp == 2:
entry = raw_input()
query = u'f=users&vertical=default&q='
searchurl = baseurl + query + entry
I'm trying to run the program in the following article:
https://blockgeeks.com/guides/python-blockchain-2/
I've copied all of the code into my Spyder IDE. When i run it there's a while loop which starts up asking the user to choose a number from the list of options it prints.
After selecting a number the program should perform the requested action. When i select it though it just loops back to the start of the while loop.
It appears to be ignoring the rest of the code in the while loop (the if statement part).
Confusingly if i take the parts of the code from the program which are used in the while loop and run them separately they work i.e if i run the below code and select the number 1 for my choice it will run the code in the if statement.
Why would the if statement run here but not in the main program?
#function 1:
def get_user_choice():
user_input = input("enter a number: ")
return user_input
#function 2:
def get_transaction_value():
tx_recipient = input('Enter the recipient of the transaction: ')
tx_amount = float(input('Enter your transaction amount '))
return tx_recipient, tx_amount
while True:
print("Choose an option")
print('Choose 1 for adding a new transaction')
print('Choose 2 for mining a new block')
print('Choose 3 for printing the blockchain')
print('Choose anything else if you want to quit')
user_choice = get_user_choice()
if user_choice == '1':
tx_data = get_transaction_value()
print(tx_data)
Update:
Sorry i realise i may not have been very clear what the problem is.
The above code is part of the code from the entire program and runs as expected in isolation from the main program.
The below code is the entire program from the article in the link. It includes all of the code in the program. If i run this main program the while loop doesn't use the if statement. It appears to just be breaking straight out of the loop after i select 1, 2 or 3 (any other number should break out of the loop anyway).
Here's a link for a screen shot showing what the console looks like after i have selected the number 1 for the option.
https://ibb.co/RNy2r0m
# Section 1
import hashlib
import json
reward = 10.0
genesis_block = {
'previous_hash': '',
'index': 0,
'transaction': [],
'nonce': 23
}
blockchain = [genesis_block]
open_transactions = []
owner = 'Blockgeeks'
def hash_block(block):
return hashlib.sha256(json.dumps(block).encode()).hexdigest()
# Section 2
def valid_proof(transactions, last_hash, nonce):
guess = (str(transactions) + str(last_hash) + str(nonce)).encode()
guess_hash = hashlib.sha256(guess).hexdigest()
print(guess_hash)
return guess_hash[0:2] == '00'
def pow():
last_block = blockchain[-1]
last_hash = hash_block(last_block)
nonce = 0
while not valid_proof(open_transactions, last_hash, nonce):
nonce += 1
return nonce
# Section 3
def get_last_value():
""" extracting the last element of the blockchain list """
return(blockchain[-1])
def add_value(recipient, sender=owner, amount=1.0):
transaction = {'sender': sender,
'recipient': recipient,
'amount': amount}
open_transactions.append(transaction)
# Section 4
def mine_block():
last_block = blockchain[-1]
hashed_block = hash_block(last_block)
nonce = pow()
reward_transaction = {
'sender': 'MINING',
'recipient': owner,
'amount': reward
}
open_transactions.append(reward_transaction)
block = {
'previous_hash': hashed_block,
'index': len(blockchain),
'transaction': open_transactions,
'nonce': nonce
}
blockchain.append(block)
# Section 5
def get_transaction_value():
tx_recipient = input('Enter the recipient of the transaction: ')
tx_amount = float(input('Enter your transaction amount '))
return tx_recipient, tx_amount
def get_user_choice():
user_input = input("Please give your choice here: ")
return user_input
# Section 6
def print_block():
for block in blockchain:
print("Here is your block")
print(block)
# Section 7
while True:
print("Choose an option")
print('Choose 1 for adding a new transaction')
print('Choose 2 for mining a new block')
print('Choose 3 for printing the blockchain')
print('Choose anything else if you want to quit')
user_choice = get_user_choice()
if user_choice == 1:
tx_data = get_transaction_value()
recipient, amount = tx_data
add_value(recipient, amount=amount)
print(open_transactions)
elif user_choice == 2:
mine_block()
elif user_choice == 3:
print_block()
else:
break
[1]: https://i.stack.imgur.com/FIrn7.png
When comparing values, Python takes a stronger route regarding data types than some other languages. That means no string in Python will equal a number.
Or in other terms "1" == 1 will be False.
That means you have to consider that in Python 3 you will receive a string from input() (not necessarily so in Python 2).
You can either compare this directly to another string:
user_choice = input()
if user_choice == "1":
print("You chose item 1")
Or you can convert it into a number first and compare it to a number:
user_choice = int(input())
if user_choice == 1:
print("You chose item 1")
Note that in the former case it might not be robust if the user enters extra spaces and in the latter case it will fail very loudly with an exception if the user doesn't enter an integer (or even nothing at all).
Both ways can be handled with extra code if necessary. In the former case, you can strip whitespace with user_input = input().strip() and in the latter case you can catch the exception with a try ... except ... block.
You have only handled the case for user_choice == '1'. If you enter anything other than 1, the program will return control to the beginning of the while loop.
I'll suggest you use a debugger to see what user_choice is before the if condition. If not, just use prints.
print("user_choice: {}, type: {}".format(user_choice, type(user_choice))
I want to make this program that acts as a bank, how do I make sure the correct ID number must be entered with the correct pin and have it depending on the id you entered print hello then their name and prompt how much money they have in the bank.
attempts = 0
store_id = [1057, 2736, 4659, 5691, 1234, 4321]
store_name = ["Jeremy Clarkson", "Suzanne Perry", "Vicki Butler-Henderson", "Jason Plato"]
store_balance = [172.16, 15.62, 23.91, 62.17, 131.90, 231.58]
store_pin = [1057, 2736, 4659, 5691]
start = int(input("Are you a member of the Northern Frock Bank?\n1. Yes\n2. No\n"))
if start == 1:
idguess = ""
pinguess = ""
while (idguess not in store_id) or (pinguess not in store_pin):
idguess = int(input("ID Number: "))
pinguess = int(input("PIN Number: "))
if (idguess not in store_id) or (pinguess not in store_pin):
print("Invalid Login")
attempts = attempts + 1
if attempts == 3:
print("This ATM has been blocked for too many failed attempts.")
break
elif start == 2:
name = str(input("What is your full name?: "))
pin = str(input("Please choose a 4 digit pin number for your bank account: "))
digits = len(pin)
balance = 100
while digits != 4:
print("That Pin is Invalid")
pin = str(input("Please choose a 4 digit pin number for your bank account: "))
digits = len(pin)
store_name.append(name)
store_pin.append(pin)
I'm very impressed by how much you've elaborated on your program. Here's how I would view your solution.
So to create a login simulation, I would instead use a dictionary. That way you can assign an ID to a PIN. For example:
credentials = {
"403703": "121",
"3900": "333",
"39022": "900"
}
Where your ID is on the left side of the colon and the PIN is on the right. You would also have to assign the ID to a name that belongs to that ID using, you guessed it, a dictionary!
bankIDs = {
"403703": "Anna",
"3900": "Jacob",
"39022": "Kendrick"
}
Now that you've done that, you can create your virtual login system using if/else control flow. I've made my code like this:
attempts = 0
try:
while attempts < 3:
id_num = raw_input("Enter your ID: ")
PIN = raw_input("Password: ")
if (id_num in credentials) and (PIN == credentials[id_num]):
print "login success."
login(id_num)
else:
print "Login fail. try again."
attempts += 1
if attempts == 3:
print "You have reached the maximum amount of tries."
except KeyboardInterrupt:
print "Now closing. Goodbye!"
Note the try and except block is really optional. You could use the break operator like you did in your code if you wanted to, instead. I just like to put a little customization in there (Remember to break out of your program is CTRL-C).
Finally, Python has a way of making life easier for people by using functions. Notice I used one where I put login(id_num). Above this while loop you'll want to define your login so that you can display a greeting message for that particular person. Here's what I did:
def login(loginid):
print "Hello, %s!" % bankIDs[loginid]
Simple use of string formatting. And there you have it. The same can be done with displaying that person's balance. Just make the dictionary for it, then print the code in your login definition.
The rest of the code is good as it is. Just make sure you've indented properly your while-loop inside the elif on the bottom of your code, and your last 2 lines as well.
Hope I helped. Cheers!