Writing Program in Python with different levels(or cases) - python

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")

Related

Can I add two VALUES to a dictionary from user input?

I keep getting an error when I run this functions. Everything goes through and then it shows this error. I have tried adding .items() to the end when I print the dictionary and still throws this error.
CLARIFICATION just realized. Not getting any type errors or anything. It prints fine but when doesn't add the second variable to the dictionary. Instead it prints this..
{'Frappe': ('small', function type_of_milk at 0x000002BE2BCD2F78>)}
def order():
ready_to_order = True
while ready_to_order != False:
ordering_q = input(
"""Do you know what you would like to order or do you need to see the menu?
[M]enu or [R]eady to order or [Q]uit: """)
if ordering_q.upper() == "Q":
sys.exit()
elif ordering_q.upper() == "M":
print(Menu())
elif ordering_q.upper() == "R":
ready_to_order = False
else:
print("Please enter valid letters only, try again.")
print(" ")
print(" ")
add_cart = True
while add_cart != False:
order1 = input("What would you like to order?")
if order1.upper() == "Done":
add_cart = False
elif order1 == 'a1':
print("Frappe added to cart")
global total_order
total_order += 3
drink_size()
type_of_milk()
order_dict['Frappe'] = (drink_sizes, type_of_milk)
add_cart = False
print(order_dict)
This line:
order_dict['Frappe'] = (drink_sizes, type_of_milk)
is adding the function type_of_milk to your dict, which is why you see function type_of_milk at 0x000002BE2BCD2F78> when you print the dict out. Maybe you meant to say type_of_milk()?

why does this python while loop not work in the program?

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))

Calling specific objects within a list in python?

I've defined the following:
class SMSMessage(object):
def __init__(self, hasBeenRead, messageText, fromNumber):
self.hasBeenRead = hasBeenRead
self.messageText = messageText
self.fromNumber = fromNumber
hasBeenRead = "False"
fromNumber = "07189202003"
With the following functions:
def MarkAsRead(self):
if hasBeenRead == "False":
return hasBeenRead == "True"
def add_sms():
sms1 = (hasBeenRead, messageText, fromNumber)
return SMSStore.append(sms1)
def get_count():
return len(SMSStore)
def get_message(i):
for i in SMSStore:
return messageText
def get_unread_messages(i):
for i in SMSStore:
if hasBeenRead == "False":
return messageText
This is the Logic for the SMS simulation where a user is meant to send messages to a list (SMSStore[ ]) and then recall specific messages from the list:
userChoice = ""
while userChoice != "quit":
userChoice = raw_input("What would you like to do - read/send/quit?")
if userChoice == "read":
unreadChoice = raw_input("Would you like to retrieve all unread messages or one of your own choice? - all unread/custom ")
if unreadChoice == "custom":
messageNo = int(raw_input("Please enter which messsage number you want to read: "))
print get_message(messageNo)
print MarkAsRead(messageNo)
elif unreadChoice == "all unread":
print get_unread_messages(hasBeenRead)
else:
print "incorrect entry"
elif userChoice == "send":
messageText = raw_input('Please type in your message')
add_sms()
print SMSStore
My main issue is that I am able to send the (hasBeenRead, messageText, fromNumber) to SMSStore but when trying to read I can't seem to return the messagetext of the user selected messageNo. It always returns the messageText of the last item in the list. I'm still new to coding so any help would be greatly appreciated.
Thanks
I'm not sure what is the role of SMSStore, but this block of code looks suspicious to me:
def get_message(i):
for i in SMSStore:
return messageText
Why are you iterating the SMSStore but just to return messageText ? Would that be a missing Indent over there ?

How to get a user string input on Telepot?

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

Problems transferring information from one part of a function to another

While working on my program I have run into a problem where the information stored in Menu option 1 is not being transferred to Menu option 2. As you can see it is correctly stored when in menu one. When it returns to go to menu option 2 its like it never went to option 1.
update #1:
some suggestions I've had is to understand scope? from what I can tell the program is not passing the data along to its parent program even though I've typed out return in each of the definitions.
#Must be able to store at least 4 grades
#Each class can have up to 6 tests and 8 hw's
#Weighted 40%*testavg 40% hw average attendance is 20%
#User must be able to input a minimum grade warning
#after each test the your program must calculate the students average and issue warning if necessary
##Define the Modules##
import math
def menu (a): #2nd thing to happen
menuend = 'a'
while menuend not in 'e':
menuend = raw_input("Type anything other then 'e' to continue:\n")
print "What would you like to do ?"
menudo = 0
print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
menudo = input("Enter Selection:")
if (menudo == 1):
menuchck = 0
menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
if menuchck in ["Yes","yes","y","Y"]:
x = m1()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 2):
menuchck1 = 0
menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
if menuchck1 in ["Yes","yes","y","Y"]:
x = m2()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 3):
print "Entered 3"
elif (menudo == 4):
print "Entered 4"
else:
print "Anything Else Entered"
def course(): #3rd thing to happen
b = {}
while True:
while True:
print "\n",name,", please enter your courses below ('e' to end):"
coursename = raw_input("Course Name:")
if (coursename == 'e'):
break
will = None
while will not in ('y','n'):
will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
if will=='y':
b[coursename] = {}
print "\n",name,", current course load:\n",b
coursechck = None
while coursechck not in ('y','n'):
coursechck = raw_input("Are your courses correct (y/n)")
if coursechck =='y':
return b
else:
b = {}
print
##Menu Options##
def m1():
a = course()
return a
def m2():
print "Excellent",name,"lets see what courses your enrolled in\n"
print x
return x
###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)
raw_input("This is the end, my only friend the end")
In your if-elif blocks in the do==1 case, you write m1(), but for the last case, you write x=m1(). You should have the latter everywhere (by typing m1() you only run the function, but do not store the returned x anywhere).
By the way, you can avoid this if-elif confusion using if chck in ["Yes","yes","Y","y"]:

Categories